Feeds:
Posts
Comments

Archive for January, 2011

Have you ever wanted to add a method to an existing type without recompiling? Well in C# 3.0 you were given that ability with extension methods. On the MSDN it states that “extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type.” I am going to give you a very simple example. Lets say you are creating a music management application and you have a class called Artist that looks like the following:

namespace MusicApp
{
     public class Artist
     {
          #region Properties

          public DateTime BirthDate { get; set; }
          public string FirstName { get; set; }
          public string LastName { get; set; }

          #endregion

          #region Constructor(s)

          public Artist(string lastName, string firstName, DateTime birthDate)
          {
               this.BirthDate = birthDate;
               this.LastName = lastName;
               this.FirstName = firstName;
          }

          #endregion
     }
}

As you can see the artist class has a birth date. What if we wanted to find the age of the artist? We could easily add a method to the class to do so, but lets use an extension method instead. We’ll be placing the code for our extension method inside a new public static class conveniently called ExtensionMethods. Here is the code:

static class ExtensionMethods
{
     public static int Age(this Artist artist)
     {
          DateTime now = DateTime.Now;
          int yearsPassed = DateTime.Now.Year - artist.BirthDate.Year;

          if (now.Month < artist.BirthDate.Month || (now.Month == artist.BirthDate.Month && now.Day < artist.BirthDate.Day))
          {
               yearsPassed--;
          }

          return yearsPassed;
     }
}

Please note that the first parameter to the extension method specifies the type the method operates on and is preceded by the this modifier. In order to use the new extension method we must import the namespace it was defined in. We are then able to determine an artist’s age like so. Enjoy!

Artist tomPetty = new Artist("Petty", "Tom", new System.DateTime(1950, 10, 20));
int age = tomPetty.Age();

Read Full Post »

Most of us have used ObjectDataProvider to create an object to use as a binding source in Xaml. However, many of you may have never used the XmlDataProvider to do the same. In this post I am going to explain how to use an external XML file to populate a list of ComboBox options. I will then bind a property to the currently selected item of the ComboBox.

The reason I find this so useful is when your application’s end user may need things to frequently change in the future, but has no clue as to how in the present. For example, lets say they have a list of colors that need to be available for their automobile paint. Well next week maroon is the new thing. Do you really want to update your app and re-publish? Wouldn’t you rather give them the ability to just add a new node in an XML file that is sitting on a network drive (or the web) that they have access to? Well now I’m going to show you how.

First we must make an XML file to contain our list of color options. We’ll call the file PaintColors.xml and place it on the root C:\ drive for now (it could be on a network drive, the web, etc.). Here are the contents of the file.


<?xml version="1.0" encoding="utf-8"?>
<PaintColors>
   <Color Name="None"/>
   <Color Name="Red"/>
   <Color Name="White"/>
   <Color Name="Blue"/>
   <Color Name="Maroon"/>
</PaintColors>

Next we must create a new WPF Application. For now we’ll call it XmlDataProviderTest. Once the application is created, we’ll add some code to the MainWindow.xaml.cs file. We need to create a CurrentColor property and give it property change notification by implementing the INotifyPropertyChanged interface. We are going to assign the DataContext as well as the initial CurrentColor value inside the MainWindow constructor. Here is all of the code for the aforementioned.


using System.Windows;
using System.ComponentModel;

namespace XmlDataProviderTest
{
    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = this;
            CurrentColor = "Blue";
        }

        public string CurrentColor
        {
            get {  return _currentColor; }
            set
            {
                if (value != _currentColor)
                {
                    _currentColor = value;
                    OnPropertyChanged("CurrentColor");
                }
            }
        }private string _currentColor;

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        void OnPropertyChanged(string propName)
        {
            if (this.PropertyChanged != null)
                this.PropertyChanged(
                    this, new PropertyChangedEventArgs(propName));
        }

        #endregion

   }
}

Finally we must place a ComboBox and TextBox on our MainWindow.xaml file. This is also where the XmlDataProvider will be declared. In the following code you’ll notice the Source property of the XmlDataProvider points to the location of the PaintColors.xml file on the C:\ drive. As mentioned before, this could point to a network drive, URL, embedded XML file, etc. The XPath property is set here as well. Please note that the XmlDataProvider’s default value for IsAsynchronous is True. This is because when retrieving XML data from RSS feeds or external XML files it is expected to take a while. This is the opposite of an ObjectDataProvider whose default IsAsynchronous value is set to false. The reason for this default is when retrieving data for an ObjectDataProvider we expect retrieval of the source to be very quick. I am setting IsAsynchronous here to false because our XML file is on a network share and contains very little information and thus should be quick to access.

Please note the binding in the ComboBox. The ItemsSource is bound to our PaintColors XmlData. We have chosen to display the Name attribute in the ComboBox and make it the selected value. Finally we are binding our SelectedValue to the CurrentColor string property we previously created in the MainWindow.xaml.cs file. To show everything is working well, I have bound the CurrentColor to a TextBox so we can see it update on the fly.


<Window x:Class="XmlDataProviderTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">

    <Window.Resources>
        <XmlDataProvider x:Key="PaintColors" Source="C:\PaintColors.xml" XPath="PaintColors" IsAsynchronous="False" />
    </Window.Resources>

    <StackPanel HorizontalAlignment="Center">
        <ComboBox Grid.Column="4" Grid.Row="2" Width="200" Height="25" Margin="5"
                  ItemsSource="{Binding Source={StaticResource PaintColors}, XPath=./Color}"
                  DisplayMemberPath="@Name"
                  SelectedValuePath="@Name"
                  SelectedValue="{Binding CurrentColor}"/>
        <StackPanel Orientation="Horizontal">
            <Label Content="Current Color:"/>
            <TextBox Text="{Binding CurrentColor, UpdateSourceTrigger=PropertyChanged}" Width="120"/>
        </StackPanel>
    </StackPanel>
</Window>

I hope this provides you all with a clean and simple introduction to XmlDataProviders. For more on synchronous and asynchronous binding have a look at Bea Stollnitz’s blog post here. Enjoy!!

Read Full Post »