OracleClient vs ODP.NET Performance Benchmark

In my previous post I mentioned that I was doing some comparisons on the performance of System.Data.OracleClient (provided by Microsoft) versus the ODP.NET (provided by Oracle). Since we still use a lot of DataSets on our project I decided that the simpler example that could be used to measure the performance would be to fill a DataTable using a DataAdapter.

For the experiment I took a table that would fill the DataTable with about 100.000 records. I then created two classes, one for each provider. The classes accessed the same database using the same SQL. Here is the code for the class using the OracleClient provider: 

class MicrosoftProvider
{
    public static void RunTest()
    {
        var conn = new System.Data.OracleClient.OracleConnection(Params.ConnectionString);
        var cmd = new System.Data.OracleClient.OracleCommand(Params.CommandText, conn);
        var adapter = new System.Data.OracleClient.OracleDataAdapter(cmd);
        var dataTable = new DataTable();
        adapter.Fill(dataTable);
    }
}

And here is the class using the ODP.NET provider:

class OracleProvider
{
    public static void RunTest()
    {
        var conn = new Oracle.DataAccess.Client.OracleConnection(Params.ConnectionString);
        var cmd = new Oracle.DataAccess.Client.OracleCommand(Params.CommandText, conn);
        var adapter = new Oracle.DataAccess.Client.OracleDataAdapter(cmd);
        var dataTable = new DataTable();
        adapter.Fill(dataTable);
    }
}

I ran the test one after the other:

class Program
{
    static void Main(string[] args)
    {
        OracleProvider.RunTest();
        MicrosoftProvider.RunTest();
    }
}

To compare the execution of each provider I ran this code using the VS 2010 Profiler, which by the way is very cool. The visualization of the tests has improved a lot since VS 2008. Here are the results summary:

 Profiler Summary

 As you can see there is a huge difference! The ODP.NET had less than 10% of the samples taken during processing while more than 90% were taken while running the method with the OracleClient provider. The report will also show you the information in more detail:

 Main method details

And the coolest view of them all will even show the percentage used overlapping the code:

Cool, right? I think so! Ok, now back to our tests... Before wrapping the post there is still one test I could do. I wanted to measure the execution time in seconds of each routine. To do this I used the Stopwatch class.

class Program
{
    static void Main(string[] args)
    {
        Time(() => OracleProvider.RunTest());
        Time(() => MicrosoftProvider.RunTest());
    }

    static void Time(Action action)
    {
        Stopwatch stopwatch = new Stopwatch();
        stopwatch.Start();
        action.Invoke();
        stopwatch.Stop();
        Console.WriteLine(stopwatch.Elapsed);
    }
}

When I ran the code I got the following results:

ODP.NET: 20.6756 seconds

OracleClient: 41.7716 seconds

The conclusion for the article is simple. The ODP.NET provider is way faster than the Oracle provider offered by Microsoft. On top of it all, as I mentioned in my previous post, many of the classes in the System.Data.OracleClient namespace are marked as obsolete. Microsoft no longer is going to keep working on them in the future.

ODP.NET OracleParameter

The past weeks I've been doing a lot of work to improve performance at our application at work. One of the things I've done is to replace the Microsoft's OracleClient for the ODP.NET provider. In my tests I've been getting data access times up to 3 times faster than with the OracleClient. I'll post more details on this in a latter article, for now I wanted to focus on the following error I got when switching providers:

Oracle.DataAccess.Client.OracleException: ORA-01008: not all variables bound

 I found this strange since we have a data layer that abstracts the provider and we already have implementations for Oracle and SQLServer and everything was working great. It took me a while but I found out that this is was only happening in queries where I used the same parameter more than once. Here is an example:

SELECT NAME, AGE FROM EMPLOYEE WHERE :AGE > 18 AND :AGE < 40

 What I found out is that the default behavior for the ODP.NET provider is different than the OracleClient provider. The ODP.NET sets the parameters (OracleParameter) on the OracleCommand using the order of the parameters instead of the name. When this happens you'd have to declare the parameter twice with the same value. This behavior can be changed using the BindByName property on the OracleCommand.

var parameter = new OracleCommand();
parameter.BindByName = true;

The good part for us is that since we had an abstraction layer on top of our data layer all we needed to do was make a small change to the Factory class that creates the commands for us. Everything else remains untouched.

Hope this helps.

Oh, and by the way... on .NET 4 many types under the System.Data.OracleClient namespace is marked as obsolete. So you'd better watch out. 

Concurrency in ASP.NET Sessions

Last week some of the guys on my team were running some tests in our application and they noticed a contention problem. When a large report was running any other requests hung until the report was done being generated.

There were no transactions locking the database and no locks on the code either. After testing for a while I noticed that when I used 2 different browsers the problem would happen. Ha! So it must have something to do with the Session. The answer was on the bottom of the Session State documentation page on MSDN. Here is the section that matters:

"Access to ASP.NET session state is exclusive per session, which means that if two different users make concurrent requests, access to each separate session is granted concurrently. However, if two concurrent requests are made for the same session (by using the same SessionID value), the first request gets exclusive access to the session information. The second request executes only after the first request is finished."

 So the problem only happens if you have multiple request from the same session. Still this is very annoying! This is done so that the Session maintains the consistency. If you don't need to write to the session (only read) the session state may be defined as ReadOnly in which case there will be no locking.

Depending on your application you might want to set the sessionState as ReadOnly in the web.config (affects all pages) and then mark each page that needs write access to use sessionState=true. Or you may want to do it the other way around. Set the pages that take a long time to process as sessionState=ReadOnly (so they don't block) and leave all the other pages that process quickly as they are.

 To set up the web.config:

<system.web>
    <pages enableSessionState="ReadOnly"/>
</system.web>

To set up a single page use the Page directive:

<%@ Page ... EnableSessionState="True" %>

Setting the Page directive will override the web.config setting.

Hope this helps.

Getting All Static Fields In a Class Hierarchy

Using reflection is pretty straight forward and that's why I found it weird that I was trying to get all the Dependency Properties for the Silverlight ComboBox but I was only getting the fields defined in the class itself. None of the fields found in the base classes where being retrieved. Only then I learned something new about reflection and static fields. Here is the code I expected to work but doesn't.
FieldInfo[] fields =
     typeof (ComboBox).GetFields(BindingFlags.Static | BindingFlags.Public);
When reflecting over a class to get all it's static fields you will find out that static fields from base classes are really not retrieved by default. And since all Dependency Properties are static fields you can't get the DP's from the base classes. If you want to retrieve all the static fields in a class hierarchy you need a special BindingFlag: BindingFlags.FlattenHierarchy. This will bring all your static fields including the one from the base classes.
 FieldInfo[] fields =
     typeof (ComboBox).GetFields(BindingFlags.Static | BindingFlags.Public |
                                 BindingFlags.FlattenHierarchy);

 Hope this is a useful tip.

Great Results Using SEO Toolkit

When I decided to test the Search Engine Optimization  Toolkit to check my blog health. I wanted to see if I had many broken links, pages missing titles and things like that. For this purpose the tool was really useful because I found a bug in the way I was generating the tags for the posts. I fixed this issue and many other minor ones like post titles being to long.

What really amazed me about the SEO Toolkit was only clear about one month later, after the search engines had the chance to crawl my site a few times. Google Analytics is showing an amazing increase in traffic: 89%! This is a lot. I really didn't expect that much improvement. Congrats to Microsoft once more on the job well done.

Here is a weekly view of the number of visits. I optimized my blog with the IIS Toolkit on the end of the year. Can you notice the improvement?

 Google Analytics Results

I wanted to show the comparison report generated for my site before and after I made the fixes but I formatted my notebook last week and lost all the reports. Shame on me!

Get TextBox Value Before and After TextChanged Event

The other day my team was doing some maintenance on a bunch of dynamically loaded UserControls and something weird started to happen, the TextChanged event of a control was firing all the time. I was sure someone had messed with the EnableViewState of the control but that is not the point, the point is that I wanted to prove it to them by looking at the value of the TextBox that was being loaded from the ViewState and then the value that was being loaded from the Form. As it turns out it is harder to do this than I thought.

My first idea was to debug through the .NET Framework source code. Sadly the version of the assembly System.Web (2.0.50727.4918) has no source code available yet. The Symbols have been published by Microsoft but no source code so far. So this option was out.

I have however the downloaded source code from a previous version of the TextBox class. Looking through it you can see the exact moment when the current value (loaded from ViewState) is replaced by the new value from the form. That is in the LoadPostData method, which is a protected virtual method. The only solution I could come up with was to create a new TextBox derived for the TextBox class and override the LoadPostData method and read the Text value before and after the change. Here is the example:

public class TextBoxExtended : TextBox
{
    protected override bool LoadPostData(string postDataKey, 
System.Collections.Specialized.NameValueCollection postCollection)
    {
        Debug.WriteLine("Before Load:"+this.Text);
        Debug.WriteLine("Loading");
        bool changed = base.LoadPostData(postDataKey, postCollection);
        Debug.WriteLine("After Load:"+this.Text);
        Debug.WriteLine("Changed? "+changed);
        return changed;
    }
}

Now if you put this TextBox in your form instead of the regular TextBox you want to monitor you will get the messages with the values in the Output window. If you want to you can take this further and create a custom event that fires with both values in the event args. If any one has an alternative method of doing this please do leave a comment.

Oh, if you are curious the problem was that the ViewState had been disabled on an outer panel but as I said before this wasn't the point of the exercise :-)

MVVM ProgressBar

There are a lot of options for doing a ProgressBar in WPF using MVVM you can Google it and see for yourself. In this article I'll show a hybrid way of doing MVVM and having a ProgressBar that does not conform to the MVVM premiss (but it is really simple to use).

 The idea is that you can do all the things you are used to do with MVVM but when you get to the ProgressBar you use events and a little code-behind.

Here is the code for the ViewModel:

public class MainWindowViewModel
{
    private BackgroundWorker _backgroundWorker;

    public event EventHandler TaskStarting = (s,e) => { };

    public event ProgressChangedEventHandler ProgressChanged
    {
        add { _backgroundWorker.ProgressChanged += value; }
        remove { _backgroundWorker.ProgressChanged -= value; }
    }

    public event RunWorkerCompletedEventHandler TaskCompleted
    {
        add { _backgroundWorker.RunWorkerCompleted += value; }
        remove { _backgroundWorker.RunWorkerCompleted -= value; }
    }

    private ICommand _executeLongTask;

    public ICommand ExecuteLongTask
    {
        get
        {
            if (_executeLongTask == null)
            {
                _executeLongTask = new RelayCommand(param => _backgroundWorker.RunWorkerAsync());
            }
            return _executeLongTask;
        }
    }

    public MainWindowViewModel()
    {
        _backgroundWorker = new BackgroundWorker();
        _backgroundWorker.WorkerReportsProgress = true;
        _backgroundWorker.DoWork += executeTask;
    }

    private void executeTask(object sender, DoWorkEventArgs e)
    {
        OnTaskStarting();
        for (int i = 0; i < 100; i++)
        {
            Thread.Sleep(100);
            _backgroundWorker.ReportProgress(i + 1);
        }
    }

    private void OnTaskStarting()
    {
        TaskStarting(this, EventArgs.Empty);
    }
}

 This ViewModel class has three events: TaskStartiing, ProgressChanged and TaskCompleted. The last two are just events that I exposed from the BackgroundWorker that will execute my long runing task. The code-behind for the Window will subscribe to these events:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        MainWindowViewModel vm = new MainWindowViewModel();
        vm.TaskStarting += TaskStarted;
        vm.ProgressChanged += ProgressChanged;
        vm.TaskCompleted += TaskCompleted;

        DataContext = vm;
    }

    void TaskStarted(object sender, EventArgs e)
    {
        this.Dispatcher.Invoke(new Action(() => ProgressPopup.IsOpen = true));
    }

    void TaskCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
    {
        this.Dispatcher.Invoke(new Action(() => ProgressPopup.IsOpen = false));
    }

    void ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
    {
        this.Dispatcher.Invoke(new Action(() => ProgressBar.Value = e.ProgressPercentage));
    }
}

Notice that since my long running task is being executed in another thread I need to use the Dispatcher to update any user interface elements.

My Window has a Popup with a ProgressBar inside it. I use the Starting and Completed events to show and hide the Popup. The ProgressBar itself is only updated in the ProgessChanged event. I also added an animation to show a blinking progress message during the execution.

<Window x:Class="MvvmProgressBar.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="300" Width="400">
    <StackPanel>
        <Button Command="{Binding ExecuteLongTask}">Run Long Task</Button>
        <Popup Name="ProgressPopup" 
               Placement="Center" 
               Width="300"
               IsOpen="False">
            <Border BorderThickness="10"
                    BorderBrush="Black"
                    Background="Gray"
                    Padding="30,50">
                <StackPanel>
                    <TextBlock Foreground="White"
                           FontWeight="Bold"
                           FontSize="16"
                           Name="txt"
                           Text="Processing...">
                    <TextBlock.Triggers>
                        <EventTrigger RoutedEvent="TextBlock.Loaded">
               <BeginStoryboard>
                  <Storyboard>
                     <DoubleAnimation
                        AutoReverse="True"
                        Duration="0:0:1"
                        From="1.0"
                        RepeatBehavior="Forever"
                        Storyboard.TargetName="txt"
                        Storyboard.TargetProperty="Opacity"
                        To="0.0"/>
                  </Storyboard>
               </BeginStoryboard>
            </EventTrigger>
                    </TextBlock.Triggers>
                    </TextBlock>
                    <ProgressBar Name="ProgressBar"
                                 Height="30" 
                                 BorderThickness="2" />
                </StackPanel>
            </Border>
        </Popup>
    </StackPanel>
</Window>

This example is really simple but it goes to show you that you may, from time to time, do some non-MVVM code and it won't make your app suck.

 

MVVM Multiselect Listbox

Although MVVM is a great pattern you have to learn to work with it somethings are hard to do until you get the hang of it.

One of these things is doing a Multiselect Listbox. My first idea Google it, of course. The best solution I found was this one by Marlon Grech. Marlon has a lot of good stuff about WPF in his blog and he definitely knows what he is talking about. This solution however became a little slow when I wanted to perform a Select All and Unselect All on the list.

I decided to implement a specialized list for this kind of situation. I call it a SelectionList and it is a list of SelectionItems. The idea is to have a collection of items that have a IsSelected property and a Item property that contains the real value you want. I think the code speaks for itself.

public class SelectionItem<T> : INotifyPropertyChanged
{
    #region Fields

        private bool isSelected;

        private T item;

        #endregion

    #region Properties

        public bool IsSelected
        {
            get { return isSelected; }
            set
            {
                if (value == isSelected) return;
                isSelected = value;
                OnPropertyChanged("IsSelected");
                OnSelectionChanged();
            }
        }

        public T Item
        {
            get { return item; }
            set
            {
                if (value.Equals(item)) return;
                item = value;
                OnPropertyChanged("Item");
            }
        }

        #endregion

    #region Events

        public event PropertyChangedEventHandler PropertyChanged;

        public event EventHandler SelectionChanged;

        #endregion

    #region ctor

        public SelectionItem(T item)
            : this(false, item)
        {
        }

        public SelectionItem(bool selected, T item)
        {
            this.isSelected = selected;
            this.item = item;
        }

        #endregion

    #region Event invokers

        private void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler changed = PropertyChanged;
            if (changed != null) changed(this, new PropertyChangedEventArgs(propertyName));
        }

        private void OnSelectionChanged()
        {
            EventHandler changed = SelectionChanged;
            if (changed != null) changed(this, EventArgs.Empty);
        }

        #endregion
}

 The SelectionItem class is what really makes things happen. It takes an ordinary class like an string and wraps it adding a IsSelected property. This is the class of the objects that will be bound to each ListItem of the ListBox.

public class SelectionList<T> : 
    ObservableCollection<SelectionItem<T>> where T : IComparable<T>
{
    #region Properties

        /// <summary>
        /// Returns the selected items in the list
        /// </summary>
        public IEnumerable<T> SelectedItems
        {
            get { return this.Where(x => x.IsSelected).Select(x => x.Item); }
        }

        /// <summary>
        /// Returns all the items in the SelectionList
        /// </summary>
        public IEnumerable<T> AllItems
        {
            get { return this.Select(x => x.Item); }
        }

        #endregion

    #region ctor

        public SelectionList(IEnumerable<T> col)
            : base(toSelectionItemEnumerable(col))
        {

        }

        #endregion

    #region Public methods

        /// <summary>
        /// Adds the item to the list
        /// </summary>
        /// <param name="item"></param>
        public void Add(T item)
        {
            int i = 0;
            foreach (T existingItem in AllItems)
            {
                if (item.CompareTo(existingItem) < 0) break;
                i++;
            }
            Insert(i, new SelectionItem<T>(item));
        }

        /// <summary>
        /// Checks if the item exists in the list
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public bool Contains(T item)
        {
            return AllItems.Contains(item);
        }

        /// <summary>
        /// Selects all the items in the list
        /// </summary>
        public void SelectAll()
        {
            foreach (SelectionItem<T> selectionItem in this)
            {
                selectionItem.IsSelected = true;
            }
        }

        /// <summary>
        /// Unselects all the items in the list
        /// </summary>
        public void UnselectAll()
        {
            foreach (SelectionItem<T> selectionItem in this)
            {
                selectionItem.IsSelected = false;
            }
        }

        #endregion

    #region Helper methods

        /// <summary>
        /// Creates an SelectionList from any IEnumerable
        /// </summary>
        /// <param name="items"></param>
        /// <returns></returns>
        private static IEnumerable<SelectionItem<T>> toSelectionItemEnumerable(IEnumerable<T> items)
        {
            List<SelectionItem<T>> list = new List<SelectionItem<T>>();
            foreach (T item in items)
            {
                SelectionItem<T> selectionItem = new SelectionItem<T>(item);
                list.Add(selectionItem);
            }
            return list;
        }

        #endregion
}

The SelectionList is basically an ObservableCollection of SelectionItem.

Now that you have a list of items that can be bound to each ListBoxItem I needed to figure out how to bind the IsSelected property of my items to the is IsSelected property of the ListBoxItem. I found the solution in

this post

in the MSDN Forums. You need to use this style:

<ListBox.ItemContainerStyle>
    <Style TargetType="{x:Type ListBoxItem}">
        <Setter Property="IsSelected" 
                Value="{Binding IsSelected}"/>
    </Style>
</ListBox.ItemContainerStyle>

Example:

Imagine you need a window with a list of sports from which you have to select the sports you like. In this window you need to be able to add items to the list and select and unselect all items at once. Here is the code for the window and the ViewModel:

<Window x:Class="MvvmChecklistBox.MultiSelectWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:MvvmChecklistBox"
        Title="MultiSelectWindow" Height="300" Width="300">
    <Window.Resources>
        <local:MainWindowViewModel x:Key="viewModel"/>
    </Window.Resources>
    <StackPanel Margin="5" DataContext="{StaticResource viewModel}">
        <TextBlock>Sport:</TextBlock>
        <TextBox Name="textBoxNewSport"
                 Text="{Binding NewSport}"/>
        <Button Content="Add new sport"
                Command="{Binding AddCommand}"/>
        <ListBox Name="checkboxList"
                 ItemsSource="{Binding Sports}"
                 DisplayMemberPath="Item"
                 Margin="0,5" 
                 SelectionMode="Multiple">
            <ListBox.ItemContainerStyle>
                <Style TargetType="{x:Type ListBoxItem}">
                    <Setter Property="IsSelected" 
                            Value="{Binding IsSelected}"/>
                </Style>
            </ListBox.ItemContainerStyle>
        </ListBox>
        <Button Content="Select All"
                Margin="0,5"
                Command="{Binding SelectAllCommand}"/>
        <Button Content="Unselect All"
                Margin="0,5"
                Command="{Binding UnselectAllCommand}"/>
    </StackPanel>
</Window>
public class MainWindowViewModel : INotifyPropertyChanged
{
    #region Fields

        private ICommand _selectAllCommand;

        private ICommand _unselectAllCommand;

        private ICommand _addCommand;

        private string _newSport;

        #endregion

    #region Properties

        public SelectionList<string> Sports { get; set; }

        public string NewSport
        {
            get { return _newSport; }
            set
            {
                if (value == _newSport) return;
                _newSport = value;
                OnPropertyChanged("NewSport");
            }
        }

        #endregion

    #region Commands

        public ICommand SelectAllCommand
        {
            get
            {
                if (_selectAllCommand == null)
                {
                    _selectAllCommand = new RelayCommand(param => Sports.SelectAll());
                }
                return _selectAllCommand;
            }
        }

        public ICommand UnselectAllCommand
        {
            get
            {
                if (_unselectAllCommand == null)
                {
                    _unselectAllCommand = new RelayCommand(param => Sports.UnselectAll());
                }
                return _unselectAllCommand;
            }
        }

        public ICommand AddCommand
        {
            get
            {
                if (_addCommand == null)
                {
                    _addCommand = new RelayCommand(param =>
                    {
                        Sports.Add(NewSport);
                        NewSport = string.Empty;
                    });
                }
                return _addCommand;
            }
        }

        #endregion

    #region Events

        public event PropertyChangedEventHandler PropertyChanged;

        #endregion

    #region ctor

        public MainWindowViewModel()
        {
            string[] sports = { "Baseball", "Basketball", "Football", "Handball", "Soccer", "Volleyball" };
            Sports = new SelectionList<string>(sports);
        }

        #endregion

    #region Event invokers

        private void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler changed = PropertyChanged;
            if (changed != null) changed(this, new PropertyChangedEventArgs(propertyName));
        }

        #endregion
}

Here is the result:

MultiSelectWindow

The solution was really simple after I though of the SelectionList. I wanted however to do a little bit more. Instead of the simple Listbox I had to build a list of CheckBoxes. To good thing is that as far as the ViewModel is concerned we are all set, there's no need to change anything. All we need to change is the View (which is a Window in our case) using a DataTemple in the ListBox ItemTemplate to place a Checkbox instead of regular item.

<ListBox.ItemTemplate>
    <DataTemplate>
        <CheckBox IsChecked="{Binding IsSelected}" 
                  Content="{Binding Item}"/>
    </DataTemplate>
</ListBox.ItemTemplate>

Did it work? Kind of... It works but something weird happens because you can select all the checkboxes you want and then select the ListItem which gets highlighted. So now you have the checkbox selection and the item highlight selection and the two of them do not match. I don't want the ListBox item to get highlighted. Once again Google helped and I found a style to do just what I wanted in Alex Filo's blog. Here is the code:

<ListBox.ItemContainerStyle>
    <Style>
        <Setter Property="ListBoxItem.Background" Value="Transparent"/>
        <Setter Property="ListBoxItem.Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type ListBoxItem}">
                    <Border x:Name="Bd" 
                    SnapsToDevicePixels="true" 
                    Background="{TemplateBinding Background}" 
                    BorderBrush="{TemplateBinding BorderBrush}" 
                    BorderThickness="{TemplateBinding BorderThickness}" 
                    Padding="{TemplateBinding Padding}">
                        <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" 
                                  VerticalAlignment="{TemplateBinding VerticalContentAlignment}" 
                                  SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsSelected" Value="true">
                            <Setter Property="Background" TargetName="Bd" Value="Transparent" />
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ListBox.ItemContainerStyle>

CheckBoxListError

Now we're done! Here is the final code for the view:

<Window x:Class="MvvmChecklistBox.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="300">
    <StackPanel Margin="5">
        <TextBlock>Sport:</TextBlock>
        <TextBox Name="textBoxNewSport"
                 Text="{Binding NewSport}"/>
        <Button Content="Add new sport"
                Command="{Binding AddCommand}"/>
        <ListBox Name="checkboxList"
                 ItemsSource="{Binding Sports}"
                 Margin="0,5">
            <ListBox.ItemContainerStyle>
                <Style>
                    <Setter Property="ListBoxItem.Background" Value="Transparent"/>
                    <Setter Property="ListBoxItem.Template">
                        <Setter.Value>
                            <ControlTemplate TargetType="{x:Type ListBoxItem}">
                                <Border x:Name="Bd" 
                                SnapsToDevicePixels="true" 
                                Background="{TemplateBinding Background}" 
                                BorderBrush="{TemplateBinding BorderBrush}" 
                                BorderThickness="{TemplateBinding BorderThickness}" 
                                Padding="{TemplateBinding Padding}">
                                    <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" 
                                              VerticalAlignment="{TemplateBinding VerticalContentAlignment}" 
                                              SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
                                </Border>
                                <ControlTemplate.Triggers>
                                    <Trigger Property="IsSelected" Value="true">
                                        <Setter Property="Background" TargetName="Bd" Value="Transparent" />
                                    </Trigger>
                                </ControlTemplate.Triggers>
                            </ControlTemplate>
                        </Setter.Value>
                    </Setter>
                </Style>
            </ListBox.ItemContainerStyle>
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <CheckBox IsChecked="{Binding IsSelected}" 
                              Content="{Binding Item}"/>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
        <Button Content="Select All"
                Margin="0,5"
                Command="{Binding SelectAllCommand}"/>
        <Button Content="Unselect All"
                Margin="0,5"
                Command="{Binding UnselectAllCommand}"/>
    </StackPanel>
</Window>

I'm sure that someone has had this problem and the SelectionList seems like a straight forward solution. I haven't found anything like it but I'm sure I can't be the first to think of it. Well, I hope this helps you and if you find of think of a better solution please leave a comment.

Using StructureMap with ASP.NET WebForms

StrutctureMap is one of the most popular IoC containers in .NET but I had never tried it out. You can learn all about StructureMap from the documentation and the tutorials already available so I won't try to explain what it is and how it works. Instead I'll show you my experience on how to use it with ASP.NET WebForms.

To test StructureMap I decided to use it in my blog which is a simple WebForms application that is now using NHibernate. The objective is use in the code only the interfaces for my Services and DAOs. Their implementation should be injected.

The first step is to create a class that will be responsible for initializing the IoC. I decided to create this class at the WebSite level in the App_Code folder because this class has dependencies on all the other assemblies. Since the WebSite has to reference all these assemblies I figured this would be the best place. Here is the code for the class:

public class IocConfigurator
{
    public static void Configure()
    {
        ObjectFactory.Initialize(x =>
        {
            x.ForRequestedType<IPostDao>().TheDefault.Is.
                OfConcreteType<PostDao>();
            x.ForRequestedType<ICategoryDao>().TheDefault.Is.
                OfConcreteType<CategoryDao>();
            x.ForRequestedType<ICommentDao>().TheDefault.Is.
                OfConcreteType<CommentDao>();
            x.ForRequestedType<IAuthorDao>().TheDefault.Is.
                OfConcreteType<AuthorDao>();
            x.ForRequestedType<ITagDao>().TheDefault.Is.
                OfConcreteType<TagDao>();
            x.ForRequestedType<IFrontEndService>().TheDefault.Is.
                OfConcreteType<FrontEndService>();
            x.ForRequestedType<IAdminService>().TheDefault.Is.
                OfConcreteType<AdminService>();

            x.SetAllProperties(y =>
                                   {
                                       y.OfType<IFrontEndService>();
                                       y.OfType<IAdminService>();
                                   });
        });
    }
}

 Now we have to class this IocConfiguration class in order to make all the initialization. The best place to do this is in the Global.asax in the Application_Start event.

<%@ Application Language="C#" %>
<%@ Import Namespace="StructureMap"%>

<script runat="server">

    void Application_Start(object sender, EventArgs e) 
    {
        IocConfigurator.Configure();
    }
    
...    
</script>

 Top-Down resolution

Ok, now let's deal with how to inject the services in the Pages. Let's continue using the IFrontEndService as our example. We could do something simple like:

IFrontEndService service = ObjectFactory.GetInstance<IFrontEndService>();

But this is not a recommend approach as you can see in the StructureMap Quickstart. You should minimize the GetInstance calls and let auto wiring do the job for you. Unfortunately WebForms doesn't make that easy. For that reason the team created the BuildUp feature that let's you inject the dependencies into an object that was already built.

In order to do the BuildUp into a single place I posted the code into the BasePage constructor. This class derives from the Page class and all the pages in my application derive from it instead of from the Page as would be usual.

namespace SpeakOut.Lib.Web
{
    public class BasePage : Page
    {
        public BasePage()
        {
            ObjectFactory.BuildUp(this);
        }
    }
}

Here is a page using the BasePage:

public partial class _Default : BasePage 
{
    public IFrontEndService Service { get; set; }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            RepeaterPosts.DataSource = Service.GetRecentPosts(10);
            RepeaterPosts.DataBind();
        }
    }
    protected void RepeaterPosts_ItemCreated(object sender, RepeaterItemEventArgs e)
    {
        Post post = (Post) e.Item.DataItem;
        PostDetailsControl control = (PostDetailsControl) e.Item.FindControl("PostDetailsControl1");
        control.Post = post;
    }
}

The BuildUp method will look for properties of the type I have registered in the IoC Configuration and will inject the properties with the correct implementation. The registration of the type of properties that should be injected is a special part of the IoC setup. In our configuration class it is at the very end of the Configure method with this syntax:

x.SetAllProperties(y =>
                       {
                           y.OfType<IFrontEndService>();
                           y.OfType<IAdminService>();
                       });

 With this StructureMap will take care of all the dependency injection for you. Including injecting the DAOs into the Service. In order for the DAOs to be injected all you need to do is to define a constructor that receives all the values you want to have injected. When StructureMap creates the Service it will look for the constructor with most parameters (the greediest). If it sees that it has all the parameters in the configuration it will automatically create the necessary objects and pass them to the constructor.

    public class FrontEndService : IFrontEndService
    {

        private readonly IPostDao _postDao;
        private readonly ICategoryDao _categoryDao;

        public FrontEndService(IPostDao postDao, ICategoryDao categoryDao)
        {
            _postDao = postDao;
            _categoryDao = categoryDao;
        }
...

 That makes the creation of a tree of objects really simple and your code doesn't need to know anything about the interface implementations.

You can get the whole implementation from the SpeakOut Codeplex Project.

From Entity Framework to NHibernate

Recently I decided to change the data access layer in my blog from Entity Framework to NHibernate. In this post I'll tell you Why and How I did it.

The WHY

I still have some issues with the current version of the Entity Framework as I posted in the article MVC Storefront: Migrating to the Entity Framework. Many of the things I wanted to do with the EF like using POCOs or LazyLoading will be possible in version 4. Until then I decided to give NHibernate a shot. I figured it wouldn't be so hard since I already had some knowledge with Hibernate from my Java days.

The HOW

 The migration was not that hard. NHibernate has a great documentation with good examples. I also used the NHibernate in Action book which I highly recommend. It is only 400 pages and very to the point.

How the Project is Structured

I have a Website and 4 assemblies:

SpeakOut.Data: This is where the DAOs live, both their interface and implementation. Also in this assembly are the NHibernate mapping files.

SpeakOut.Model: This assembly has all the domain model entities. I had to make minor changes to these classes to get them to work best with NHibernate. The collections for instance were changed to use IList<T> instead of the IEnumerable<T> I was using with the EF.

SpeakOut.Service: This assembly has services (Interfaces and Implementations) that are used by the presentation layer.

SpeakOut.Lib: Here are all the utility classes, base classes for the pages and control and classes with extension methods.

The Model

This is the class diagram for the classes in the model. NHibernate makes populating the dependencies show in the diagram really easy, actually you don't do anything and you still get the benefit of lazy loading for free. This is something that wasn't easy in the EF.

The Mapping Files

Here are the mapping files for my entities.

Author

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
                   assembly="SpeakOut.Model"
                   namespace="SpeakOut.Model">
  <class name="Author">
    <id name="AuthorId">
      <generator class="guid"/>
    </id>
    <property name="Name"/>
    <property name="Login"/>
    <property name="Password"/>
    <property name="Email"/>
    <property name="IsAdmin"/>
    <bag name="Posts" access="field.camelcase-underscore" inverse="true" cascade="all-delete-orphan">
      <key column="AuthorId"/>
      <one-to-many class="Post"/>
    </bag>
  </class>
</hibernate-mapping>

Post

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
                   assembly="SpeakOut.Model"
                   namespace="SpeakOut.Model">
  <class name="Post">
    <id name="PostId">
      <generator class="guid"/>
    </id>
    <property name="Title"/>
    <property name="Body"/>
    <property name="Permalink"/>
    <property name="Published"/>
    <property name="PublishDate"/>
    <bag name="Comments" access="field.camelcase-underscore" inverse="true" cascade="all-delete-orphan">
      <key column="PostId"/>
      <one-to-many class="Comment"/>
    </bag>
    <bag name="Tags" access="field.camelcase-underscore" inverse="true" cascade="all-delete-orphan">
      <key column="PostId"/>
      <one-to-many class="Tag"/>
    </bag>
    <bag name="Categories" access="field.camelcase-underscore" table="CategoryPost">
      <key>
        <column name="PostId" not-null="true"/>
      </key>
      <many-to-many class="Category">
        <column name="CategoryId" not-null="true"/>
      </many-to-many>
    </bag>
    <many-to-one name="Author" column="AuthorId" not-null="true"/>
  </class>
</hibernate-mapping>

Comment

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
                   assembly="SpeakOut.Model"
                   namespace="SpeakOut.Model">
  <class name="SpeakOut.Model.Comment">
    <id name="CommentId">
      <generator class="guid"/>
    </id>
    <property name="Author"/>
    <property name="Body"/>
    <property name="Email"/>
    <property name="Website"/>
    <property name="Country"/>
    <property name="Ip"/>
    <property name="IsApproved"/>
    <property name="CreatedAt"/>
    <many-to-one name="Post" column="PostId" not-null="true"/>
  </class>
</hibernate-mapping>

Tag

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
                   assembly="SpeakOut.Model"
                   namespace="SpeakOut.Model">
  <class name="Tag">
    <id name="TagId">
      <generator class="guid"/>
    </id>
    <property name="Name"/>
    <many-to-one name="Post" column="PostId" not-null="true"/>
  </class>
</hibernate-mapping>

Category

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
                   assembly="SpeakOut.Model"
                   namespace="SpeakOut.Model">
  <class name="Category">
    <id name="CategoryId">
      <generator class="guid"/>
    </id>
    <property name="Name"/>
    <bag name="Posts" table="CategoryPost">
      <key>
        <column name="CategoryId" not-null="true"/>
      </key>
      <many-to-many class="Post">
        <column name="PostId" not-null="true"/>
      </many-to-many>
    </bag>
  </class>
</hibernate-mapping>

 The Data Access

 In the data access layer I decided to drop the Repository I was using to go with simple DAOs. The main reason I did it was to test NHibernate as recommended by it's more experienced users. I really think I wouldn't get a lot from the Repository.

Here is the class diagram for the DAOs interfaces:



One of the approaches suggested in the NHibernate in Action book is to use a base DAO that encapsulate the common behavior in all NHibernate DAOs. Here is the code for the this class:
 

namespace SpeakOut.Data.NHibernate.Daos
{
    public class BaseDao<T> : IBaseDao<T>
    {
        private ISession _session;

        protected ISession Session
        {
            get
            {
                if (_session == null)
                {
                    _session = NHibernateHelper.GetCurrentSession();
                }
                return _session;
            }
        }

        public T FindById(Guid id)
        {
            return Session.Load<T>(id);
        }

        public T FindByIdAndLock(Guid id)
        {
            return Session.Load<T>(id, LockMode.Upgrade);
        }

        public IList<T> FindAll()
        {
            return Session.CreateCriteria(typeof (T)).List<T>();
        }

        public T MakePersistent(T entity)
        {
            Session.SaveOrUpdate(entity);
            return entity;
        }

        public void MakeTransient(T entity)
        {
            Session.Delete(entity);
        }
    }
}

 All the DAOs derive from this BaseDao and get all the basic functionality. The specialized DAOs are left to implement the functionality that is directly related to them. Look at how simple the implementation of the AuthorDao is:

namespace SpeakOut.Data.NHibernate.Daos
{
    public class AuthorDao : BaseDao<Author>, IAuthorDao
    {
        public Author FindByLogin(string login)
        {
            return Session.CreateCriteria<Author>()
                .Add(Expression.Eq("Login", login).IgnoreCase())
                .UniqueResult<Author>();
        }
    }
}

 One aspect to pay attention to is how the NHibernate Session works when you have an ASP.NET application. The easiest way to deal with this is to create an HTTP Module that creates a session that will live as long as the duration of the Request. When the Request ends the Transaction is committed and the Session is released. A similar strategy is described in this post.

 Here is the implementation of the HTTP Module.

public class NHibernateCurrentSessionWebModule : IHttpModule
{
    public void Init(HttpApplication context)
    {
        context.BeginRequest += Application_BeginRequest;
        context.EndRequest += Application_EndRequest;
    }

    public void Dispose()
    {
    }

    private void Application_BeginRequest(object sender, EventArgs e)
    {
        ISession session = NHibernateHelper.OpenSession();
        session.BeginTransaction();
        CurrentSessionContext.Bind(session);
    }

    private void Application_EndRequest(object sender, EventArgs e)
    {
        ISession session = CurrentSessionContext.Unbind(NHibernateHelper.SessionFactory);

        if (session == null) return;

        try
        {
            session.Transaction.Commit();
        }
        catch (Exception)
        {
            session.Transaction.Rollback();
        }
        finally
        {
            session.Close();
        }
    }
}

Since this module creates the Session and the Transaction we need a way to access these resources. This is done by a helper class like this:

namespace SpeakOut.Data.NHibernate
{
    public static class NHibernateHelper
    {
        public static readonly ISessionFactory SessionFactory;

        static NHibernateHelper()
        {
            try
            {
                Configuration configuration = new Configuration();
                configuration.AddAssembly("SpeakOut.Data");
                SessionFactory = configuration.Configure().BuildSessionFactory();
            }
            catch (Exception ex)
            {
                throw new Exception("NHibernate initialization failed", ex);
            }
        }

        public static ISession OpenSession()
        {
            return SessionFactory.OpenSession();
        }

        public static ISession GetCurrentSession()
        {
            return SessionFactory.GetCurrentSession();
        }
    }
}

There are two important things about this class. The first is AddAssembly method being called in the static constructor. I have to pass the name of the assembly that contains the NHibernate Mappings. In this project all the mappings are in the Speakout.Data assembly. The second important point is the GetCurrentSession which is the method that will be used in all the DAOs to get the Session already created in the HTTP Module.

More info about configuring NHibernate when using several assemblies can be found here.

The Configuration

Since I'm using a WebSite all the NHibernate configuration is done in the Web.Config. First a section is defined in the ConfigSections node:

<section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler,NHibernate"/>

And the create the configuration node:

<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
  <session-factory>
    <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
    <property name="connection.connection_string">
      Server=(local);initial catalog=your_catalog;user id=your_user;password=your_pass
    </property>
    <property name="adonet.batch_size">10</property>
    <property name="show_sql">true</property>
    <property name="dialect">NHibernate.Dialect.MsSql2005Dialect</property>
    <property name="use_outer_join">true</property>
    <property name="command_timeout">60</property>
    <property name="query.substitutions">true 1, false 0, yes 'Y', no 'N'</property>
    <property name="proxyfactory.factory_class">NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu</property>
    <property name="current_session_context_class">web</property >
  </session-factory>
</hibernate-configuration>

 Final Words

I hope my implementation may help you. It simple and small enough that you can go through it very quickly and get a base understanding of what you need to get NHibernate going.

I'll probably give the Entity Framework another chance once my hosting starts to support EF 4. After all changing and trying, and failing and learning is exactly what this blog is all about.

You can get all the source code for this project at Codeplex.