Posted by: rhwilburn | July 5, 2009

C# Action’s

When playing around with UI events it is sometimes handy to use lambda notations of actions to do a tidy inline event-action handler definition such as:

Button1.Click += (sender, args) => Debug.WriteLine("Button Click");
 

If we delve a little deeper into Actions, we can use them to pass around code snippets/functions.

Action<String> action = (input) => Debug.WriteLine("Testing" + input); 
 

I have heard many arguments against functional features such as actions in C# however I do feel that they are very useful in edge cases. One such case could be the mass adding of items to a dictionary, such as:

var namesDictionary = new Dictionary<int, string>();
 
namesDictionary.Add(1,"One");
namesDictionary.Add(2,"Two");
namesDictionary.Add(3,"Three");
 

If we wanted to keep our code maintainable we might want to reduce our dependency to the Add method (especially if we had lots of dictionary add statements).

Action<int,string> addAction = (key,value) => namesDictionary.Add(key,value);
//Action<int,string> addAction = namesDictionary.Add; //short syntax

addAction(1, "One");  //etc
 

Note that this dictionary example is a bad example as the collection initialization could be used here which is likely the most optimal solution. The following shows how the collection initialization could have been used:

var namesDictionary = new Dictionary<int, string> {{1, "One"}, {2, "Two"}, {3, "Three"}};
 

This example also could have been solved more optimally using extension method(s), by extending the dictionary, dependency injection, lambda foreach statement, foreach loop etc. With that said, Actions are important in allowing for lazy evaluation/delayed invocation. I am not going to get into lazy evaluation in this post, but I recommend checking out the Haskell language community for lazy evaluation ideas. I highly recommend the following link for understanding how evaluation/manipulation of lambda expressions work.

http://msdn.microsoft.com/en-us/library/bb397951.aspx

Posted by: rhwilburn | March 6, 2009

Boosting Visual Studio Performance

Visual Studio has always worked fairly well for me at home, but at work where many of our projects/solutions are very large Visual Studio struggles. At home I still find that my Visual Studio is better than the one I use at work and I believe this is because at home I have my hard-drives in a performance RAID (Raid 0) and my OS is Vista x64 rather than XP x86.

Two things I suspect are:

Vista manages memory much better and doesn’t struggle with the out of memory exceptions that I frequently get at work. Note: Out of memory exceptions are actually to do with the .NET runtime not being able to garbage collect all of its generations properly. But the size of Visual Studio and the number of objects it is using is the cause of this.

Hard-drive speed affects Visual Studio more greatly than CPU and potentially even RAM. When I get out of memory exceptions at work (we all get this too btw) my PC is not using all of its 2 gigs of ram. Visual Studio is limited by default to 2 gigs, but this can be overcome.

Remedies:

 

Faster harddrives, lowerlatency hard drives:

On Vista with my RAID 0 my experience is better but is still latent. My IDE can load lots of data fast but often takes a while to do so. This means waits are still a small amount of time due to latency issues but large amounts of data are not really an issue.

I am starting to think that the ideal solution is a performance raid of Solid State Drives (SSD).  A link on performance improvements for a Java IDE are available here: http://jexp.de/blog/archives/18-On-Boosting-My-IDEA-Jetbrains-IntelliJ-IDEA-is-fast-again.html

If you have an infinite money pool, a RAID card would be recommended too. These can have RAM on them to cache disk access which would further reduce latency.

Upgrade OS:

Upgrade to Vista and make sure you upgrade to the 64 bit version. It is silly not to take advantage of your CPU being x64.

Myths:

 

Resharper:

Myth: Reshaper significantly degrades performance, and causes out of memory exceptions.

Interestingly resharper shows the out of memory exceptions (which can be a pain) where as Visual Studio virtually hides it from the user. Resharper is not causing these issues, and from what I have seen there is no significant performance difference apart from when the project is being loaded. That is because resharper loads its cache then by analysing assemblies.

RAM:

Myth: Increasing RAM will increase Visual Studio’s performance

I think that if Visual Studio is running out of memory then a RAM increase will help, but for us at work our RAM is not being fully utilized so on XP increasing our RAM won’t help us as the OS will not use it. On Vista however the OS endeavours to use as much free RAM as it can to cache and pre-allocate so it is possible this will help a little bit. I think the biggest myth about personal computing is that upgarding CPU and RAM makes the biggest difference. My computer at home is 4 years old and my computer at work is 6 months old. My computer at home that is 4 years old is faster in practical usage. If it came down to a number crunching war then the new computer would win but there is virtually no use case for that in personal computing.

Posted by: rhwilburn | February 15, 2009

Updating an item in a list without a reference with lambdas

I have to confess I am enjoying lambdas a bit much. I am making this post to show a cool way of avoiding code loops (there are still loops in CLR of course).

private void UpdatePerson(Person updatedPersonObject)
{
    var outOfDatePerson = _people
            .First(person => person.Id == updatedPersonObject.Id);
    int index = _people.IndexOf(outOfDatePersonObject);
    _people[index] = updatedPersonObject;
}
 
private void UpdatePerson_OldCSharp(Person updatedPersonObject)
{
    int outOfDatePersonIndex = 0;
    for (int i = 0; i < _people.Count ; i++ )
    {
        if (_people[i].Id == updatedPersonObject.Id)
        {
            outOfDatePersonIndex = i;
            break;
        }
    }
    _people[outOfDatePersonIndex] = updatedPersonObject;
}

 

From the two code samples it is worth noticing the difference in the number of lines and in the hierarchical nature of the code. The traditional C# for loop approach (the second method) leads me to cringe from a maintenance point of view. Each line of code is highly contextual and relies heavily on multiple levels of language constructs.

The first method (the lambda way) to me is much more readable and also maintainable. There is a flat hierarchy which is much easier to read as it doesn’t involve following the loop through code. I argue it is easier to maintain as the lines can change order more and will still be doing the same thing. It is also easier to update as there is less code.

Posted by: rhwilburn | February 15, 2009

Databinding to Collections

If you use WPF then you will be using databinding extensively. This post looks at databinding with respect to collections.

Databinding basics (Background Info):

To databind in .NET currently you are required to provide notification of when the variables you databind to change. This can be done by implementing the INotifyPropertyChanged interface or by implementing the property as a dependency property. For more information on databinding basics, see here.

Collections are slightly different

In the case of collections it is often not important when a collection object changes but rather when the items within that collection change. With that said you will likely need both approaches implemented because if an entire collection is reassigned the binding to the observable collection will be lost as it has been replaced with a new observable collection. It is also possible that others in your team will re-assign the list at some point, so that is why I like to plan for that situation.

private ObservableCollection<String> _names;
internal ObservableCollection<String> Names
{
    get { return _names; }
    set
    {
        _names = value;
        PropertyChanged(this, new PropertyChangedEventArgs("Names"));
    }
}

 

ObservableCollection<T> notifies bindings an item has changed from its CollectionChanged event. The previous code sample shows the INotifyPropertyChanged interface implementation which is required to see if the ObservableCollection assigned to “Names” has been changed. 

In conclusion all Lists that are going to be used for databinding should be ObservableCollections. All properties that are databinded to should implement the INotifyPropertyChanged interface or be dependency properties.

Posted by: rhwilburn | February 14, 2009

Beyond Relational Databases

I am no expert with databases, however I can definitely see scalability issues that relational databases provide when needed to grow beyond one database. Relational databases also are strongly typed and explicit relationships exist between entities. This explicit relationship specification and strong typing often requires developers to write migration scripts which can be a pain and could potentially be avoided or minimized.

There is an interesting article: http://www.readwriteweb.com/archives/is_the_relational_database_doomed.php which discusses the benefits of key-value databases or cloud oriented databases.

Unfortunately most of these databases are in beta and the standards between them are lacking, but I can definitely see from my experience developing payroll software that a key-value database would help us in many areas.

The down sides to key-value databases are that they are weakly typed and hence there is no schema which means you can get bad data in the database, meaning that code has to deal with that possibility, which could lead to more mistakes. I do feel however that weaker typing and not specifying relationships between entities is the way of the future because if we look at C# and other modern languages we can notice a trend of moving towards more weakly typed languages.

I do prefer a strongly typed language currently however as technology progresses I can see that dynamic typing will lead to more general code that will be more flexible to change. Currently my biggest concern is that dynamically typed languages are prone to catching errors at runtime rather than compile time which is a blow for software reliability. I am confident that this can be overcome.

It is important to state that there is an overhead in specifying types/schemas and converting between types. I also think that currently developers can make assumptions in strongly typed languages that objects will be populated in a way that they expect which sometimes is not the case. With dynamically typed objects this assumption would not be exercised as it would soon become clear that less can be assumed. The immediate development areas of .NET CLR 3.5 and 4.0 show that functional programming and dynamic objects are the current direction. I also like the hybrid approach that .NET is creating by using the power of strong typing and providing facilities towards gradual introduction of dynamic typing. This will hopefully allow for existing functionality that applies to strongly typed objects to be used against dynamically typed objects.

Posted by: rhwilburn | February 13, 2009

Event Handling Techniques

As .NET grows so do the number of ways of tackling the same or similar problems. Event Handling is no exception.

//1
button1.Click += new RoutedEventHandler(button1_Click);
 
//2
button1.Click += button1_Click;
 
//3
button1.Click += delegate(System.Object o, RoutedEventArgs e)
                     {
                         System.Windows.MessageBox.Show("Click!");
                     };
 
//4
button1.Click += delegate
{
    MessageBox.Show("Click!");
};
 
//5
button1.Click += (o, e) => MessageBox.Show("Click!");

 

Personally I use approach 2 and 5 depending on the situation. Approaches 3, 4 & 5 are anonymous handlers which means that their name is determined at creation (so we don’t know what it is). This can sometimes be an issue if you want to unsubscribe from an event, see here. Again with this post Resharper will make suggestions to use approach 2 and 5.

I feel there is an important difference between approach 1 and 2 that should be elaborated on. Approach 1 delcares the delegate of RoutedEventHandler twice because the delegate is already specified in, and hence inferred from, the event declaration. This is shown below:

internal event RoutedEventHandler Click;

 

Inferring types rather than having duplicate definitions is important as it means that you don’t have to repeat yourself and when you refactor your code you will have an easier job updating it when it is specified once.

For those unfamiliar with delegates, delegates are method parameter contracts which in the case of RoutedEventHandler specifies that an implementer of its contract will have the parameters of (Object, RoutedEventArgs).

Posted by: rhwilburn | February 13, 2009

Implicit parameter specification with Lambdas

On the last line of code in the following code listing you will notice that the method of IList<T>.Add(T item) is called but with no parameter.

//our resulting output
IList<Person> lecturersEnrolledForStudy = new List<Person>();
 
//students and lecturers can enrol for study.
var newStudentEnrolementList = new List<Person>();
 
//filter the students out
var lecturersEnrollingInAClass = newStudentEnrolementList
                                    .Where(person => person.isLecturer)
                                    .ToList();
 
//add lecturers that are enrolling to the enrolled list.
lecturersEnrollingInAClass.ForEach(lecturersEnrolledForStudy.Add);

 

The parameter is still being populated like as if the following code was written:

lecturersEnrollingInAClass
            .ForEach(item => lecturersEnrolledForStudy.Add(item));

 

The parameter is inferred by the compiler just as the type of the “item” variable is by the lambda expression/list type. For those of us who are being weaned off traditional loops for these sorts of list interactions might find that it is more natural to think of the list that we are adding too first, and the list that the information is coming from second. This has reversed with lambdas.

A point worth making is that while this example I have provided is simple and could be done using an AddRange method, it is not as extensible and hence I suggest not using it. An example of the .ForEach extention methods extensibility would be that it can ‘addrange’s across different types and at different depths of objects. An example of this could be:

lecturersEnrollingInAClass
            .ForEach(item => lecturesNamesList.Add(item.Name));
 

In conclusion this is a handy shorthand to use with lambdas. If you already use the Resharper plug-in, this shorthand will have been suggested to you.

Posted by: rhwilburn | February 13, 2009

LINQ for show, Lambda for pro

When first utilizing the new query techniques of .NET 3.5 such as LINQ and Lambda expressions I would always choose LINQ over lambda expressions. This was for two reasons:

1. LINQ looked more natural

2. Lambda expressions or the LINQ extension methods to be more accurate are often hidden away because either you are not using the correct type to access them, or don’t have the System.LINQ library in the using section.

As time has progressed I have realised that I now use lambda expressions almost exclusively. I feel that looking deeper into LINQ has facilitated this, specifically understanding the typing behind LINQ. Ultimately it comes down to preference as the compiler changes LINQ to use extension methods, see: here

An example of the difference in sytnax is:

var d = (from mp in MyProducts

         where mp.Price < 50d

         select mp);

 

var f = MyProducts.Where(mp => mp.Price < 50d)

 

I think that when your queries are smaller, that lambda expressions are quicker to write and more natural to the rest of C#. When a query becomes very large LINQ could be more concise but I haven’t yet come across such a situation. Also I am not a fan of single huge queries as it is an inconvenience for other developers if they need to modify a query. Its bigger, so takes longer to read, and multiple smaller queries means that code be executed in between queries. With PLINQ however there could be an advantage in have a single larger query, however I am not taking PLINQ into consideration today.

Posted by: rhwilburn | February 5, 2009

Why we Blend & Custom combo boxes

I have been sceptical of Expression Blend for a while now. I have found that it is was a marginally better designer than Visual Studio and I didn’t see what the fuss was about. Yesterday I found out a massively powerful feature that now I wouldn’t develop WPF without. The feature I am talking about is the ability to copy existing styles from framework controls such as  a combo-box and change them. This is best demonstrated at the following blog: http://www.designerwpf.com/2008/10/01/how-to-use-a-listview-or-datagrid-in-a-combobox-drop-down-without-a-line-of-code/. For that blog tutorial you don’t need to add a reference like the tutorial asks if you aren’t going to use a datagrid control.

One thing to be careful of is that there will be two item presenters in the template. If you are like me and wanted to make a customizable combo-box drop down but also have the selected item area update then you will need to make your control isEditable=true and isReadOnly=false. This will use the opposite ItemPresenter once isEditable is changed to true. This initially gave me a fright thinking that I would not be able to use isEditable.

If multiple selection is wanted in your custom combo box you can try: http://jobijoy.blogspot.com/2009/02/simple-multiselect-combobox-using.html

Posted by: rhwilburn | January 28, 2009

Docking WPF controls to right or bottom of a Canvas

When first learning WPF one thing that stumped me was docking controls to the right hand side of a canvas. As I understand WPF layouts, the only default WPF control that allows controls to overlap is the canvas layout control (See comments about a correction here. The canvas control is not the only control that allows items to overlap). This is why I was forced to use the canvas layout (as I wanted the ability to place controls over the top of each other).

The way to solve this issue was to use a multibinding and a multibinding converter. I have provided a code sample below showing a treeview control that is docked to bottom right side of a wpf window.

<TreeView x:Name="Menu" DataContext="MenuData" Height="350" Width="220">
  <Canvas.Left>
    <MultiBinding Converter="{StaticResource RelativePlacementConverter}">
      <Binding ElementName="MainCanvas" Path="ActualWidth" />
      <Binding ElementName="Menu" Path="ActualWidth" />
    </MultiBinding>
  </Canvas.Left>
  <Canvas.Top>
    <MultiBinding Converter="{StaticResource RelativePlacementConverter}">
      <Binding ElementName="MainCanvas" Path="ActualHeight" />
      <Binding ElementName="Menu" Path="ActualHeight" />
    </MultiBinding>
  </Canvas.Top>
</TreeView>

public class RelativePlacementConverter : IMultiValueConverter

{

#region IMultiValueConverter Members

public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)

{

double? screenWidth = values[0] as double?; //parent width

double? menuWidth = values[1] as double?; //own width

if (screenWidth != null && menuWidth != null)

{

return (screenWidth – menuWidth);

}

return 0.0;

}

public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)

{

throw new NotImplementedException();

}

#endregion

}


The previous code uses the width and height of the treeview control called Menu and subtracts that from the width and height of the canvas called MainCanvas. For more usecases or more depth on how to implement a multibinding I recommend the following: wpf-tutorial-using-multibindings.

I would recommed using multibindings when a value needs to be result of a combination of other values. There are other ways around this issue without using a multibinding. Links to APIs to avoid multibindings are avalible at: http://marlongrech.wordpress.com/2008/02/10/embed-code-in-xaml/. I like the idea of avoiding multibindings as they take a bit more effort that should be required for simple scenarios like this blog post, however I am also sceptical of alternatives because they don’t yet seem to leverage the power of code behind the way that the multivalueconverter allows.

Older Posts »

Categories