Living in the Tech Avalanche Generation

A practitioner’s introspective on technology

Archive for the 'C#' Category

Using Ruby Naming Conventions in C# code? Is that madness?

During my journey in learning Ruby / IronRuby, I have caught myself often naming things in C# with a Ruby convention or BDD test naming regime. To be extreme here’s an example:

var customer_to_make_preferred = Get_Customer_By_Id<ICustomerMakePrefered>();

//OR METHODS LIKE THIS

public void Group_By_Orders_And_Print_To_Console_Window()
{
    //…..etc
}

I really find a benefit in greater understanding when reading code when I take this approach. Now it’s true I have been programming in C# for some 10 years and I don’t know if this kind of behaviour will see me excommunicated from the circle of brethren or not but I would like to know what others think.

Opinions please! And yes I know this is gonna be like waving a red flag in front of a raging bull :). And for the Ruby people, I am only proposing the extended underscored naming convention and nothing else – it’s all about naming and that’s it – ya basta!

Share/Save/Bookmark

6 comments

Curried Event Handlers or - Lazy Event Handling in Functional C#

There has been a lot of buzz lately about the ‘other’ styles of programming that exist outside of our warm and cosy statically typed imperative world. Dynamic and Functional programming languages are starting to generate some deep interest in the community and anyone who reads this blog from time to time would know that I too have been dragged in by the gravity of IronRuby.

F#, whilst interesting to me, alas must take a back seat to IronRuby as it’s going to have to be one language at a time for this little polyglot, however I keep coming across interesting information that promotes a Functional approach in C# and VB.NET. The approach leverages some of the newer (3.5) language features syntactically but really the core of what’s possible lies in the what became available in C# 2.0. There is of course always a ubiquitous example so lets stick with that - a function that takes an integer as an argument and returns a function that also takes an integer as an argument and returns an integer that adds the two together. Consider this code:

[Test()]
public void CurryInTwoDotZeroFramework()
{
    FuncInTwoZeroStyle two_zero_func =
        new FuncInTwoZeroStyle(delegate(int x)
            {
                return delegate(int y)
                {
                    return  x + y;
                };
            });

    var first_func_has_10 = two_zero_func(10);
    var second_func_has_another_10_makes_20 =
        first_func_has_10(10);

    Assert.AreEqual(20,
        second_func_has_another_10_makes_20);
}

functional_delegates_watch 

What’s happening here is that we get a kind of closure behaviour where 10 gets stored away with the function. From the compilers point of view we know that delegates at runtime have a class generated with a target and a method and in our example we have 10 as the object instance being the target and the returned function is the “Method” that gets wrapped up in our runtime generated class. For a good discussion on how delegates work under the hood it’s worth reading this post.

Currying – a style of cooking or programming practice?

Something that Functional devotees often talk about is the ability to write functions that return functions, often referred to as “currying”. Interestingly the Wikipedia definition includes the following:

The practical motivation for currying is that very often the functions obtained by supplying some but not all of the arguments to a curried function (often called partial application) are useful; for example, many languages have a function or operator similar to plus_one. Currying makes it easy to define these functions.

Our .NET 2.0 example above can be redefined in 3.5 with some syntactic sugar like this:

public void basic_add_Curry()
{
    Func<int, Func<int, int>> curry_add_ten =
        x => y => x + y;

    var add_to_10 = curry_add_ten(10);

    var should_be_20 = add_to_10(10);
    var should_be_30 = add_to_10(20);
    var should_be_40 = add_to_10(30);

    Assert.AreEqual(20, should_be_20);
    Assert.AreEqual(30, should_be_30);
    Assert.AreEqual(40, should_be_40);
}

 

You mentioned Events?

I don’t want to go over ground already largely covered elsewhere so let me focus in what I thought was a slight deviation that offered up an interesting possibility. What about event subscriptions? Can we ‘curry’ event handlers? The answer is yes of course we can. Let me demonstrate.

internal class MyObjectWithAnEvent
{
    internal event EventHandler subscribe_with_action_event;

    internal void on_subscribe_with_action_event()
    {
        if(subscribe_with_action_event != null )
            this.subscribe_with_action_event
                ("’an event subscribed to by Action<>’",
                    new EventArgs());
    }
}

and we can subscribe to the event in this class like this:

public void event_handling_curry()
{
    //simple Action delegate
    Action<int, int> takes_two_ints =
        (x, y) => Console.WriteLine(x + y);

    takes_two_ints.Invoke(2,3);

    //Action matching signiture of EventHandler delegates
    Action<object, EventArgs> a_standard_event_delegate =
        (x, y) => Console.WriteLine(String.Format("{0}:{1}", x, y));

    //new up an object that has an event to subscribe to
    MyObjectWithAnEvent obj_to_subscribe_on =
        new MyObjectWithAnEvent();

    //subscribe to the event that implements 
    //an EventHandler delegate
    obj_to_subscribe_on.subscribe_with_action_event +=
        new EventHandler(a_standard_event_delegate);

    //call a method to raise the event
    obj_to_subscribe_on.on_subscribe_with_action_event();

    //declares a function that returns an event handler
    Func<int, Action<object, EventArgs>>
        func_that_returns_event_delegate =
        x => (y, z) => Console.WriteLine(
            string.Format("The values passed to the function was {0} " +
            "and the sender was {1}", x, y));

    //store the value of 100 with the returned event handler
    var action_with_int = func_that_returns_event_delegate(100);

    //subscribe to an event with the delegate 
    //returned by the function
    obj_to_subscribe_on.subscribe_with_action_event +=
        new EventHandler(action_with_int);

    //raise the event
    obj_to_subscribe_on.on_subscribe_with_action_event();
}

What is evident here is that we have returned a delegate that also has access to the contextual data that we had available at runtime when the delegate was computed. This delegate along with the the contextual data (x being equal to 100) might subsequently be used in a further computation at such time as any event is raised in which that delegate in question has been applied as a handler in any such events invocation list. I call this ‘contextual delayed subscription’. Perhaps I want to get a reference to a handler for an event that has not yet occurred and upon certain conditions or actions I will subscribe to that event at a later time or perhaps Just in Time. For example you might choose to store away the delegates and their contextual state until a user of your application indicates that they are interested having an event subscribed where actions occurring in the past are also of interest.

Share/Save/Bookmark

1 comment

LINQ To XML and the Specification Pattern - [In a static world]

I have documented quite extensively on how to use the Specification Pattern and in particular how that can work with a variety of LINQ flavours. The pattern has proven useful in matching objects based on a computation that seeks to test equality and when turned slightly on it’s head a little, it can provide dynamic querying capability to the current Microsoft group of ORM products, namely LINQ To SQL and the Entity Framework. You can check out most of the series on this topic from here. In more recent times I looked at how to use the same pattern with IronRuby which whilst very satisfying for the author, it currently lacks the ability to produce expressions that either ORM products are capable of utilising.

So, for the moment I want to go back again to the Specification pattern and explore it’s use specifically in the world of C# and it’s statically typed sibling languages. The Specification that I currently use is based primarily around our ability to push around Expression<Func<T>> and Func<T> as delegates that can be used as arguments to the extension methods in a given LINQ implementation. Therefore, LINQ to XML should be no exception. Given that the class at the centre of all this ( Specification<T> ) matches objects that satisfy a boolean condition that is asserted using the generic T argument, we are able to specify a function to pass to any extension method implemented by the LINQ To XML provider, that takes a generic as it’s input parameter and returns a boolean. A quick reminder of the Specification classes interface:

public interface ISpecification<T>
{
    Expression<Func<T, bool>> EvalPredicate { get; }
    Func<T, bool> EvalFunc { get; }
    bool Matches(T entity);
}

Here is a simple example of filtering a query over XML data by supplying a predicate in the form of a specification.

public void employees_from_uk()
{
    var all_employees_on_file =
        XDocument.Load(@"..\..\XML\Employees.xml").Descendants();

    Specification<XElement> aus_emp_spec =
        new Specification<XElement>
            (x => x.Attribute("Country").Value == "Australia");

    var aus_employees = from e in all_employees_on_file.Descendants()
                        .Where(aus_emp_spec.EvalFunc)
                        select e;

    aus_employees.ToList().ForEach(x =>
        { Console.WriteLine(x.ToString()); });
}

And now a more complex specification that uses the AND operator to create a combined set of conditions to be satisfied in a .Where extension method.

public void employees_from_uk_that_are_ceo()
{
    var all_employees_on_file =
        XDocument.Load(@"..\..\XML\Employees.xml").Descendants();

    var aus_emp_spec =
        new Specification<XElement>
            (x => x.Attribute("Country").Value == "UK");

    var ceo_emp_spec =
        new Specification<XElement>
            (x => x.Attribute("Title").Value == "CEO");

    var compound_spec = aus_emp_spec & ceo_emp_spec;

    var aus_employees = from e in all_employees_on_file.Descendants()
                        .Where(compound_spec.EvalFunc)
                        select e;

    aus_employees.ToList().ForEach(x =>
        { Console.WriteLine(x.ToString()); });
}

More than just a ‘Where’ predicate?

Your probably noticing that we are always applying our specifications to the “where” method. As I mentioned, a Specification in it’s current incarnation can only be applied to extension methods that take a function that accepts a generic argument as an input parameter and returns a boolean, therefore there are some other methods that can be specified. Here is example of using the .SkipWhile() extension method.

public void skip_while_employees_from_usa_then_return_the_rest_regardless()
{
    var all_employees_on_file =
        XDocument.Load(@"..\..\XML\Employees.xml").Descendants();

    var usa_empoyee_spec =
        new Specification<XElement>
            (x => x.Attribute("Country").Value == "USA");

    var usa_emps = from e in all_employees_on_file.Descendants()
                       .SkipWhile(usa_empoyee_spec.EvalFunc)
                       select e;

    usa_emps.ToList().ForEach(x =>
        { Console.WriteLine("Skipping from the USA : " +
            x.ToString()); });
}

The final example combines data from two XML sources, each one requiring it’s own specification, where the LINQ query will bring the disparate data together.

public void customer_joined_with_customer_representative()
{
    var cust_rep_spec =
        new Specification<XElement>(x => x.Name == "CustomerRep");
    var emp_id_spec =
        new Specification<XAttribute>(x => x.Name == "EmployeeID");

    var all_employees_on_file =
        XDocument.Load(@"..\..\XML\Employees.xml").Descendants().Attributes();

    var all_customers_on_file =
        XDocument.Load(@"..\..\XML\Customers.xml").Root.Descendants().Elements();

    var customer_with_rep =
        from c in all_customers_on_file.Where(cust_rep_spec.EvalFunc)
        from e in all_employees_on_file.Where(emp_id_spec.EvalFunc)
        where c.Value == e.Value
        select new
        {
            c = c.Parent.Element("FirstName").Value + " " +
                c.Parent.Element("LastName").Value,
            e = e.Value
        };

    customer_with_rep.ToList().ForEach(x =>
    {
        Console.WriteLine(
            string.Format("Customer : {0} is represented by Rep Number {1}",
            x.c, x.e));
    });
}
 
For ease of reading this code without the necessity of downloading the code, I have included the XML directly in the post here.
 

Employee.xml File

 
<?xml version="1.0" encoding="utf-8" ?>
<Employees>
  <Employee EmployeeID="1" FirstName="Nancy"
            LastName="Davolio" Title="Sales Representative"
            HireDate="1992-05-01T00:00:00" Country="USA"
            Extension="5467" />
  <Employee EmployeeID="2" FirstName="Andrew"
            LastName="Fuller" Title="Vice President, Sales"
            HireDate="1992-08-14T00:00:00" Country="AUSTRALIA"
            Extension="3457" />
  <Employee EmployeeID="3" FirstName="Janet"
            LastName="Leverling" Title="Sales Representative"
            HireDate="1992-04-01T00:00:00" Country="USA"
            Extension="3355" />
  <Employee EmployeeID="4" FirstName="Margaret"
            LastName="Peacock" Title="Sales Representative"
            HireDate="1993-05-03T00:00:00" Country="AUSTRALIA"
            Extension="5176" />
  <Employee EmployeeID="5" FirstName="Steven" LastName="Buchanan"
            Title="Sales Manager" HireDate="1993-10-17T00:00:00"
            Country="UK" Extension="3453" />
  <Employee EmployeeID="6" FirstName="Michael"
            LastName="Suyama" Title="Sales Representative"
            HireDate="1993-10-17T00:00:00" Country="UK"
            Extension="428" />
  <Employee EmployeeID="7" FirstName="Robert" LastName="King"
            Title="CEO" HireDate="1994-01-02T00:00:00"
            Country="UK" Extension="465" />
  <Employee EmployeeID="8" FirstName="Laura" LastName="Callahan"
            Title="Inside Sales Coordinator"
            HireDate="1994-03-05T00:00:00" Country="USA"
            Extension="2344" />
  <Employee EmployeeID="9" FirstName="Anne" LastName="Dodsworth"
            Title="Sales Representative" HireDate="1994-11-15T00:00:00"
            Country="UK" Extension="452" />
</Employees>

 

Customers.xml File

<?xml version="1.0" encoding="utf-8" ?>
<Customers>
  <Customer>
    <FirstName>Simon</FirstName>
    <LastName>Segal</LastName>
    <JoinDate>19-10-2008</JoinDate>
    <Country>Australia</Country>
    <Email>simon.segal@techavalanche.com</Email>
    <MobilePhone>0405987367</MobilePhone>
    <CustomerRep>2</CustomerRep>
  </Customer>
  <Customer>
    <FirstName>Bob</FirstName>
    <LastName>Jones</LastName>
    <JoinDate>23-10-2008</JoinDate>
    <Country>Germany</Country>
    <Email>bob.j@bundes.com</Email>
    <MobilePhone>8983478347</MobilePhone>
    <CustomerRep>1</CustomerRep>
  </Customer>
  <Customer>
    <FirstName>Clair</FirstName>
    <LastName>Humgola</LastName>
    <JoinDate>10-10-2008</JoinDate>
    <Country>Australia</Country>
    <Email>chumg@telstra.com.au</Email>
    <MobilePhone>0458193487</MobilePhone>
    <CustomerRep>4</CustomerRep>
  </Customer>
  <Customer>
    <FirstName>Milton</FirstName>
    <LastName>Nomik</LastName>
    <JoinDate>20-12-2008</JoinDate>
    <Country>Australia</Country>
    <Email>milt.n@techavalanche.com</Email>
    <MobilePhone>09072625717</MobilePhone>
    <CustomerRep>6</CustomerRep>
  </Customer>
</Customers>

On a final note: I am going to have a go shortly at putting together some variations of the Specification<T> class to allow for a more complete use with LINQ in General, remembering that the initial requirement was based around testing objects for equality and then creating a more manageable and malleable system of creating dynamic queries in LINQ To SQL and the Entity Framework. The “new” Specification class will need to support more than the just Func<T, bool> and should prove to be in interesting exercise.

Full code download for this post can be found here.

Share/Save/Bookmark

No comments

« Previous PageNext Page »

Creative Commons Attribution-ShareAlike 2.5 Australia
Creative Commons Attribution-ShareAlike 2.5 Australia