Archive

Archive for the ‘.NET’ Category

Cool Things to Do with Dynamics in dotNET 4

December 21, 2009 7 comments

Are Extension Methods a Code Smell?

December 21st | 2009

Cool Things to Do with Dynamics in .NET 4.0

In An Overview of C# 4.0 I discussed some of new features in C# 4.0. One thing that I didn’t cover was the dynamic keyword.

Put simply, something marked as dynamic does not have any compile-time enforced semantics. Instead, all members of the instance are resolved at runtime by the Dynamic Language Runtime (DLR). Here is a simple example:

static void Main(string[] args)
{
    dynamic int1 = 1;
    dynamic int2 = 2;
    dynamic result = int1 + int2;
    Console.WriteLine(result);
}

This, as expected, will print 3. However, the operator + and what int1 and int2 really are is resolved at run time. I’ll demonstrate this using the following code (which looks like it shouldn’t compile, but actually does):

static void Main(string[] args)
{
    dynamic int1 = 1;
    dynamic ex1 = new Exception("Oops!");
    dynamic result = int1 + ex1;
    Console.WriteLine(result);
}

This normally wouldn’t compile since an int type and the Exception type do not have a + operator. Regardless, this code compiles just fine. It’s only at runtime that we get an error:

Unhandled Exception: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: Operator ‘+’ cannot be applied to operands of type ‘int’ and ‘System.Exception’

So, what use is this? Why don’t we just use the real types rather than dynamic? Possible scenarios for using dynamic are: when we don’t know what the type is; or when it came from an odd place, such as reflection. If a type is resolved via reflection, we can treat it as a dynamic and not worry about calling “Invoke” or “GetProperty” on it. The same goes with COM Interop. If a complete wrapper is missing then we can declare it as dynamic and continue to use it without significant complex code.

But the most interesting use of a dynamic is declaring your own. Enter the DynamicObject base type. This allows us to tell the object how to behave at run time and instruct it how to handle the resolution of properties and methods. We can build some very powerful tools with this.

I’ve done some neat things with PowerShell, and the thing that particularly amazed me was how easy it is to consume and manipulate XML. Here’s a PowerShell snippet that loads an XML file:

$xmlConfig = New-Object XML

$xmlConfig.Load(“Some XML Path”);

$backup = ($xmlConfig.configuration.appSettings.add | where {$_.key –eq ‘BackupEveryInMinutes’}).value;

This XML file looks something like this:

<configuration>
    <appSettings>
        <add key="BackupEveryInMinutes" value="1440" />
    </appSettings>
</configuration>

$backup will be assigned to 1440. I like the way you can just access the properties off of the $xmlConfig as if they were always there. In C# and .NET previously, this would have been impossible. However, using the DynamicObject, we can build one that does. Let’s start!

Let’s make a class that derives from DynamicObject.

public class DynamicXml : DynamicObject
{
}

An important concept in this is being able to override TryGetMember. This is how we tell the DLR how to dynamically resolve something.

public class DynamicXml : DynamicObject
{
    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
    }
}

· binder – this is what is attempting to be bound, or resolved. It can tell us what the DLR is trying to figure out, such as a property name

· result – to tell the DLR the value of what is being resolved.

· return – if the dynamic was successfully resolved. In our case, we will return false if the XML document doesn’t contain a node. This will cause the DLR to throw an exception if the return value is false.

First we must load our XML document. Let’s use an XmlDocument (as opposed to the newer XDocument) as an example. The constructor will take an XmlNode since XmlDocument inherits from XmlNode.

So the usage scenario for our code will be something like this:

XmlDocument document = new XmlDocument();

document.Load(“pathtoxml.xml”);

dynamic dynamicXml = new DynamicXml(document);

string value = dynamicXml.configuration.appSettings.add.value;

The properties being used on the dynamicXml are the nodes of what we are trying to access. We can check the binder to see what property is being resolved. We can recursively return our dynamic object to continue resolution, too. The final result looks like this:

using System.Xml;
using System.Collections.Generic;
using System.Dynamic;

namespace CSharp4
{
    public class DynamicXml : DynamicObject
    {
        private readonly XmlNode _node;

        public DynamicXml(XmlNode node)
        {
            _node = node;
        }

        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            result = null;
            XmlNodeList nodes = _node.SelectNodes(binder.Name);
            if (nodes.Count == 0)
                nodes = _node.SelectNodes("@" + binder.Name); //Check and see if it's an attribute.
            if (nodes.Count == 0)
                return false;
            if (nodes.Count == 1)
            {
                XmlNode node = nodes[0];
                result = GetContent(node);
            }
            else
            {
                List<dynamic> results = new List<dynamic>();
                foreach (XmlNode node in nodes)
                {
                    results.Add(GetContent(node));
                }
            }
            return true;
        }

        private dynamic GetContent(XmlNode node)
        {
            if (node.NodeType == XmlNodeType.Attribute)
                return node.Value;
            if (node.HasChildNodes || node.Attributes.Count > 0)
                return new DynamicXml(node);
            return node.InnerText;
        }

        public override string ToString()
        {
            return this;
        }

        public static implicit operator string(DynamicXml xml)
        {
            return xml._node.InnerText;
        }
    }
}

Sure, it’s not perfect. It could handle collections better instead of returning a list and support for types other than a string. And this isn’t the best solution either. It’s a nice syntax but using the XDocument and LINQ is a better alternative. However I think it’s a great use for dynamics.

Do you agree? Let us know. Based on your feedback, we may include another installment on this subject—with improvements.

Kevin Jones is a Team Lead at Thycotic Software, an agile software services and product development company based in Washington DC. Secret Server is our flagship password management software product. On Twitter? Follow Kevin

Categories: .NET

Are Extension Methods a Code Smell

December 10, 2009 18 comments

Are Extension Methods a Code Smell?

December 10th | 2009

Are Extension Methods a Code Smell?

The extension method is a handy feature that came in C# 3.0/VB.NET 9.0 and .NET Framework 3.5. Quite simply, it allows the appearance of extending a class and giving it additional functionality without actually having to modify that class. Here’s an example:

class OtherClass
{
    public void Foo()
    {
        User user = new User();
        user.DisplayUserName();
    }
}

public class User
{
    public string UserName { get; set; }
}

public static class Extensions
{
    public static void DisplayUserName(this User user)
    {
        string userName = user.UserName;
        //Display userName
    }
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

In the “Foo” method we are calling a method “DisplayUserName” which appears to belong to the User class, but is actually a static method in a completely different location.

Extension methods are currently present in the .NET Framework. Their most notable use is in LINQ. All of LINQ’s operators are implemented as an extension method on the IEnumerable<T> interface.

But can they be a code smell? In most cases I would say yes, for several reasons.

Firstly, if it is something simple, why not just implement it in the object? In the case of the User, it may not be his responsibility to display to the interface. Therefore, to avoid violating the Single Responsibility Principle, it would be better to keep the functionality out of the User class. However, this turns something that might have been better as a service into a concrete static implementation, and this could be difficult to test by mocking. By creating a service and adding it to a container, we have a more appropriate solution.

Secondly, new developers—or even experienced ones—might be confused. It’s impossible to tell just by looking at the code if it’s an extension method or an actual method on the object. If you have multiple extension methods the code can be extremely difficult to read. It may even introduce bugs or make code reviews labor intensive.

A third scenario where I see extension methods as problematic is in the fact that they seem to be instance-based. That is, they have the appearance of accessing a method on an instance of an object. In actual fact, the compiler is just translating it to a normal static method. A developer might be tempted to do something like this:

public static class Extensions
{
    private static string _userName;
    public static void DisplayUserName(this User user)
    {
        _userName = user.UserName;
        DoDisplay();
    }

    public static void DoDisplay()
    {
        //Do something with _userName
    }
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

This is perfectly legal and working code, but by introducing something outside of the scope that is static, and not tied to an instance of User, we’ve introduced thread safety issues. I believe this is one of the reasons Extension Properties were not introduced—it’s an invitation for this sort of code.

Extension methods can be a slippery slope. While they may have been introduced for a perfectly valid and specific reason, there’s a broken window effect: if there’s one broken window in the neighborhood, it’s an invitation for other windows to be broken too. There’s an obvious invitation for extension methods to be written in such a way that if one extension method is written, then you’re inviting other people to use them in possibly careless ways.

Are they useful in any context at all? Yes, I believe they are. Usually for extending sealed classes for which you don’t have the source. A common pattern is to make string helpers as extension methods. Here’s an example:

class Program
{
    static void Main(string[] args)
    {
        string sample = "the quick brown fox jumped over the lazy dog";
        string titled = sample.ToTitleCase();
        //titled will be "The Quick Brown Fox Jumped Over The Lazy Dog"
    }
}

public static class StringExtensions
{
    public static string ToTitleCase(this string s)
    {
        return System.Globalization.CultureInfo.CurrentUICulture.TextInfo.ToTitleCase(s);
    }
}

 

This might be an acceptable use of an extension method. We are extending a sealed and well-known class “string” and giving it additional functionality.

I could also see it working, on owned-code, with helper methods in unit test projects.

As far as organization goes, try keep extension methods down to a minimum, or none if possible. If you must use them, organize them in way that all the extensions are organized in <ClassBeingExtended>Extensions static class. Or to take it step further, append the extension method with “Extension” so it is easily identified as one.

I think they are cool – but ultimately the possible negatives outweigh the positives.

What say you readers? Are extension methods a quick way to shoot yourself in the foot?

Kevin Jones is a Team Lead at Thycotic Software, an agile software services and product development company based in Washington DC. Secret Server is our flagship password management software product. On Twitter? Follow Kevin

Categories: .NET, C#

Some Love for VB.NET 10 Too

November 24, 2009 11 comments

Some Love for VB.NET 10 Too

November 24th | 2009

Some Love for VB.NET 10 Too

At Thycotic we typically work with C#. In fact, 90% of the code that we write is written in C#. However, it’s no secret that I am a VB.NET Fanatic. Generally, C# developers don’t look kindly on VB.NET developers because they consider VB.Net an inferior language. But I particularly like how it’s implemented in Visual Studio.

One of the criticisms of VB.NET is that is that some of its features are not up to par with C#. That’s an indisputable fact, I’ll admit. But a lot has been done to the upcoming VB.NET 10 for the .NET Framework 4.0, to bring VB.NET closer to C# for syntactic sugar.

Auto Properties

C# 3.0 introduced a really cool feature called automatic properties. Essentially, the C# compiler emits a backing field for you so you don’t have to do it yourself. This feature will be available in VB.NET 10. Its syntax looks like this:

Public Property MyAutoProperty As Object

That’s it! It’s just that one line; even simpler than C#. Of course you can decorate it with ReadOnly or WriteOnly so that it only has a getter or setter. The one thing it can do that C# 3.0 or 4.0 doesn’t let you do, however, is auto-initialize it.

Public Property MyAutoInteger As Integer = 10

MyAutoInteger will default to 10. The VB.NET compiler will secretly put this in the constructor or static constructor if the property is static, similar to the way fields can be auto-initialized.

Subs as Lambdas

C# 3.0 introduced a rich syntax for Lambda expressions, and VB.NET followed suit to support LINQ. One limitation is that the passed in delegate must be a function that returns a value, and not a sub. Consider the following:

Sub Main()
    DoWork(Sub(x) Console.WriteLine(x))
End Sub

Public Sub DoWork(ByVal work As Action(Of String))
    work("Some String Maybe")
End Sub

This simply wouldn’t compile in VB.NET 9 with Visual Studio 2008 because DoWork expects an Action delegate, which does not return anything thus making it a Sub, not a Function. I’m happy to say this will compile in Visual Studio 2010.

Collection Initializers

If you’ve ever had a List or Dictionary you wanted to quickly initialize with data for something simple like a unit test, C# made this easy with collection initializers. VB.NET 10 introduces a similar syntax to allow initializing a collection.

Dim helloWorld As New List(Of String) From {"Hello", "World"}

This will create a list with “Hello” and “World” in the list. Likewise for a dictionary:

Dim helloWorld As New Dictionary(Of Integer, String) From {{1, "Hello"}, {2, "World"}}

Good stuff!

Line Continuations

VB.NET was criticized for its reliance on line feeds to decide where the next statement block would start. Previously, to continue the statement to the next line you had to use an underscore to indicate that the next line was part of the current one. In VB.NET 10, that remains true. But VB.NET 10 allows flexibility while implicitly understanding where the underscore is. For Example:

Dim someNumber As String = "Hello" &
     "World"

or

Dim someNumber As Integer = 10 +
     40

Better COM Support & Indexed Properties

C# 4.0 introduced better handling for “missing” arguments in COM. VB.NET has had that for a while.

C# 4.0 has partial support for indexed properties to complete their COM enhancements. Sadly, C# only lets you consume them from COM, not declare them, which VB.NET has been able to do since its inception.

And let’s not forget that VB.NET has plenty of other language tools that C# lacks such as the “With” construct:

Dim builder = New StringBuilder()
With builder
    .Append("The ")
    .Append("Quick ")
    .Append("Brown ")
    .Append("Fox ")
    .Append("Jumped ")
    .Append("Over ")
    .Append("The ")
    .Append("Lazy ")
    .Append("Dog.")
End With

A contrived example, sure, but you get the idea of its usefulness. The “Handles” as a way of handling events is one of my favorite features. Of course C# developers will quickly to tell you that it’s a horrible syntax.

Conclusion

Both languages definitely have their advantages and disadvantages. Clearly though, VB.NET 10 has a lot of polish on it that cannot be ignored.

Kevin Jones is a Team Lead at Thycotic Software, an agile software services and product development company based in Washington DC. Secret Server is our flagship password management software product. On Twitter? Follow Kevin

Categories: .NET

Bringing Plausible Deniability to Development: the Strategy Pattern

July 30, 2009 3 comments

July 30th 2009 | David Cooksey

Bringing Plausible Deniability to Development: the Strategy Pattern

If the template pattern is a benevolent dictator the strategy pattern is a politician concerned with plausible deniability: Don’t tell me the details, just do it. The strategy is defined solely in terms of its inputs and outputs.

Let’s say you are writing a program that cuts checks for employees. The code that handles the physical printing of the checks is complete, all that remains is determining how much to print on the check for each person. The company contains both salaried and hourly employees in addition to salesmen whose pay is based on commissions. Also, the company sends out holiday checks to all employees at various times of the year based on how the company performed recently.

You want to be flexible, so your payment generator is designed as a windows service that polls a PaymentRequest table periodically. It then examines the type of payment to determine how the amount should be calculated. The next step is to write and organize implementations of the different ways to calculate payments.

The design should be flexible enough that it makes adding new payment types as simple as possible, while also providing as much flexibility as possible with respect to implementation details. You don’t want to mandate that a particular step in calculation occur, because you don’t know what future payment types might require.

This is where the strategy pattern comes into play. You can use a simple interface that defines your payment strategy to streamline your code and cut down on the number of decision points. All you really need is a block of code that looks at the payment record and decides what strategy to use. The other code should be the same regardless of the payment type. Here is some pseudo code for what this would look like:

public interface IPaymentStrategy
  {
    double CalculateAmount(IPaymentRequest paymentRequest);
  }

public class PaymentGenerator
  {
    public void LookForPaymentRequests()
    {
      IPaymentRequest[] paymentRequests= GetNewPaymentRequests();
      foreach (IPaymentRequest paymentRequest in paymentRequests)
      {
        Process(paymentRequest);
      }
    }

    private void Process(IPaymentRequest request)
    {
      IPaymentStrategy strategy;
      switch (request.PaymentType)
      {
        case 1:
          strategy = new HourlyPayment();
          break;
        case 2:
          strategy = new SalariedPayment();
          break;
        case 3:
          strategy = new CommissionPayment();
          break;
        case 4:
          strategy = new HolidayPayment();
          break;
        default:
          strategy = new FlatPayment();
          break;
      }
      double amount = strategy.CalculateAmount(request);
      WriteCheck(amount);
    }
}

IPaymentStrategy defines a simple interface that accepts an IPaymentRequest and returns the amount calculated. The PaymentGenerator pulls in new payment requests from a table. It picks the appropriate payment calculation method based on the payment type Id and uses it to generate the correct payment amount.

If a new payment type is added, it requires no code restructuring other than the creation of a new class that inherits from IPaymentStrategy, a new case block, and a new row in the PaymentType table.

This code structure places no restrictions at all on the implementation details of the individual payment types. If a lot of code is shared among the payment types, inheritance, a common dependency, or any other method can be used to reduce or eliminate code duplication entirely at the discretion of the programmer.

This makes it easier to ignore the gritty details of payment calculation which a more strict pattern such as the Template Pattern would force you to consider.

Flexible

Maintainable

Plausibly Deniable

The Strategy Pattern.

David Cooksey is a Senior .NET Consultant at Thycotic Software, an agile software services and product development company based in Washington DC. Secret Server is our flagship password management software product.

A stranger in a strange land: A graphic designer in a dot NET Agile sprint planning world

April 30, 2009 Leave a comment

Josh Frankel: Stranger in a Strange Land a Graphic Designer in a .NET Agile planning meeting

April 30th 2009 | Josh Frankel

Stranger in a strange land: A graphic designer in a .NET Agile Sprint planning world

Agile Planning is an effective way of gauging how much work can get done in a given period of time. By measuring things in relative units of effort one should be able to approximate units of work required for a task. Our team uses a point system to avoid being influenced by a system based on hours. Hours may seem easier to use but they are not necesarily representative of the proportional relationship between work that has been completed and work that needs to be accomplished.

Shortly after joining Thycotic as a Web designer I was given a brief overview of Test Driven Development and Agile Planning practices and immediately recruited to participate in the bi-weekly sprint meetings. But with my skill set rooted firmly in the design arena and my vast development skills limited to CSS and HTML-I had absolutely no idea what was being discussed.

As the team went through the challenges and methods of each task I realized that my grasp of programming was comparable to my grasp of Mandarin Chinese. When it came to discussing point efforts needed for tasks, my guesses were wildly different from the rest of the team’s.

It’s been a few months now and sprint planning meetings are a lot easier. My assessment of the point effort needed for a task is usually pretty close to the developer’s approximations. Although I understand the planning terminology, I still don’t know squat about programming- for the purpose of Agile sprint planning, I really don’t need to. I only need a grasp of how or what is going to be done based on it’s relative difficulty to other tasks. What I’m trying to figure out during each sprint meeting though, is how much harder the current task is when compared to one that’s worth one point.

With buzzwords like ‘synergy’ and ‘cross-functional’ being thrown around so much, isn’t it time consideration was given to how Agile techniques might be expanded and enriched by those of us outside the traditional developer role?

Josh Frankel is the junior graphic designer and marketing team member at Thycotic Software Ltd, an agile software consulting and product development company based in Washington DC.  Secret Server is our flagship enterprise password management product.
On Twitter? Follow Josh

Announcement – Intro to TDD Presentation

March 24, 2009 Leave a comment

Our CEO, Jonathan Cogley, will be presenting an introduction to Test Driven Development on March 25th for the DC ALT.NET user group.  The session will focus on walking through and solving a “real world” problem by identifying and isolating the dependencies in the logic.

This is a great chance for aspiring and veteran TDD developers to touch up on the basics.

Details
Date: Wednesday, March 25
Time: 7-9pm
Location: Motley Fool, 2000 Duke Street, Alexandria, VA, 22314

Writing Silverlight apps with Dynamic languages like IronRuby and IronPython

February 12, 2009 Leave a comment

Ben Yoder: Iron Python

February 12th 2009 | Ben Yoder

Writing Silverlight Apps with IronRuby and IronPython

As someone who started programming with Java and then moved over to C# and .NET, I have had very few opportunities to program in different languages. This isn’t a bad thing, but there are so many interesting languages out there and few opportunities to apply them.

Fortunately some languages are getting ported over to run on the CLR. This isn’t new: IronPython has been around for a while; as has IronRuby; and the Ada port for .NET (A#) has been available for even longer. There are some new ones on the way as well, such as IronScheme—a Scheme/Lisp port.

But now, with new Open Source Silverlight Dynamic Languages SDK and the Dynamic Language Runtime (DLR) there is an emerging framework for writing Silverlight apps with Dynamic languages such as IronRuby and IronPython.

After visiting the Microsoft Dynamic Language site I was able to get going fairly quickly. Initially I made the mistake of downloading an older version of the Silverlight Dynamic Languages SDK which was compiled with an older version of Silverlight. This caused some issues when trying to run the applications, which I resolved by recompiling the SDK source with references to the current Silverlight dlls.  This is a pain though, and can be avoided by making sure you download the latest version of the SDK which is currently in version 0.4.0. The SDK download page also includes a reference to the version of Silverlight it targets, so double-check the version of Silverlight you are running against the version the SDK uses.

I’m new to these languages, but there is an abundance of information and tools to help you get started. So check out Dynamic Languages SDK 0.4.0, and download Sliverlight if it’s not already installed on your machine.

Those are the only two installs you need to get started.

I used trusty Notepad++ for my text editor and used the included Chiron program to run my apps. This works well, but there are some better options if your looking to integrate with the more familiar environment of Visual Studio. Laurence Moroney at MSDN Blogs explains how to integrate Chiron into a Visual Studio DLR web app. This allows you to code in VS, and start your website using Chiron.

There is also the IronPython Studio which is free and based on the VS 2008 Shell runtime. Even if you don’t have a licensed installation of Visual Studio you can still develop IronPython code in a Visual Studio style environment for free.

While I doubt I’ll be able to integrate any IronPython into our Secret Server Password Management Software anytime soon, it’s great utilizing my Microsoft development tools and knowledge with multiple new languages.


Ben Yoder is a senior .NET developer at Thycotic Software Ltd.