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.

How to Match Date without Time in NHibernate

I'm changing my blog to use an NHibernate data layer. I'll post about this experience soon.

One thing I think is worth mentioning is how to write a query to filter by date only. Yes, I want to ignore the time part of the date class. I new to NHibernate and I thought that there would be a function to do this. Well there isn't. There is nothing bad about this I just wanted to write about it to let others find the recommended solution to solve this problem.

The way to do it is by using BETWEEN and comparing the hour zero (00:00:00) of the day and the last second of the day (23:59:59).

Here is an example where I need to find all posts published in a given date:

public IList<Post> FindByDate(DateTime datePublished)
{
    DateTime initDate = datePublished.Date;
    DateTime endDate = datePublished.Date.AddDays(1).AddSeconds(-1);
    return Session.CreateCriteria<Post>()
        .Add(Expression.Between("PublishDate", initDate, endDate))
        .List<Post>();
}

 And here is the same example using HQL:


public IList<Post> FindByDate(DateTime datePublished)
{
    DateTime initDate = datePublished.Date;
    DateTime endDate = datePublished.Date.AddDays(1).AddSeconds(-1);
    string hql = "from Post where PublishDate between :initDate and :endDate";
    return Session.CreateQuery(hql)
        .SetDateTime("initDate", initDate)
        .SetDateTime("endDate", endDate)
        .List<Post>();
}

Very simple. My only doubt was if there were any other way to do this. I found a discussion on the NHibernate group where Ayende says that this is the way to do it. Case closed :-)

 

Compressing Files and Folders with SharpZipLib

I have found a lot of examples on how to compress files using C# but only a few that would compress all files and folders (including subfolders). I found an example in this forum that show how to do it using SharpZipLib.

Here is what I did with it:

static void Main(string[] args)
{
    ZipOutputStream zip = new ZipOutputStream(File.Create(@"d:\my.zip"));
    zip.SetLevel(9);
    string folder = @"D:\Work\AnyDirectory\";
    ZipFolder(folder, folder, zip);
    zip.Finish();
    zip.Close();
}

public static void ZipFolder(string RootFolder, string CurrentFolder, 
    ZipOutputStream zStream)
{
    string[] SubFolders = Directory.GetDirectories(CurrentFolder);

    //calls the method recursively for each subfolder
    foreach (string Folder in SubFolders)
    {
        ZipFolder(RootFolder, Folder, zStream);
    }

    string relativePath = CurrentFolder.Substring(RootFolder.Length) + "/";

    //the path "/" is not added or a folder will be created
    //at the root of the file
    if (relativePath.Length > 1)
    {
        ZipEntry dirEntry;
        dirEntry = new ZipEntry(relativePath);
        dirEntry.DateTime = DateTime.Now;
    }

    //adds all the files in the folder to the zip
    foreach (string file in Directory.GetFiles(CurrentFolder))
    {
        AddFileToZip(zStream, relativePath, file);
    }
}

private static void AddFileToZip(ZipOutputStream zStream, string relativePath, string file)
{
    byte[] buffer = new byte[4096];

    //the relative path is added to the file in order to place the file within
    //this directory in the zip
    string fileRelativePath = (relativePath.Length > 1 ? relativePath : string.Empty) 
                              + Path.GetFileName(file);

    ZipEntry entry = new ZipEntry(fileRelativePath);
    entry.DateTime = DateTime.Now;
    zStream.PutNextEntry(entry);

    using (FileStream fs = File.OpenRead(file))
    {
        int sourceBytes;
        do
        {
            sourceBytes = fs.Read(buffer, 0, buffer.Length);
            zStream.Write(buffer, 0, sourceBytes);
        } while (sourceBytes > 0);
    }
}

This is not hard but I had to figure out that the file names needed to have the relative path before it in order to correctly place them in the same folders within the compressed zip file.

I hope this helps!

Dependency Properties

Dependency Properties are quite different from regular CLR properties. Let's take an Age property as a simple example of a normal property. We usually define a private field of type int and then define a Age property wrapping this field with get and set accessors. The code should be something like this:

public class Person
{
    private int _age;
    public int Age
    {
        get { return _age; }
        set { _age = value; }
    }
}

If instead we wanted to create age as a dependency property instead the code would look like this:

public class Person : DependencyObject
{
    public static readonly DependencyProperty AgeProperty = DependencyProperty.Register("Age", typeof (int),
                                                                                        typeof (Person));
    public int Age
    {
        get { return (int)GetValue(Person.AgeProperty); }
        set { SetValue(Person.AgeProperty, value); }
    }
}

 

Wow, that is really different isn't it? Actually it is so different that I rather take it apart so that we can understand each piece of this code.

Part 1: The class

Dependency properties can only be used in classes that derive from DependencyObject. As you can see in the first example the Person class is a simple class derived from the Object class. In the second example Person is derived from DependencyObject.

DependencyObject is the class that has all the necessary infrastructure that make DP's work. As we go through this article I'll mention more about this class but for now just keep in mind that if you want or need to use DP's your class must derive from DependencyObject.

Part 2: Declaring the Property

As you may have noticed the two examples are totally different. By convention the DP is a public static readonly field of the type DependencyProperty. So the field that will store the actual value of age is not an int? Yep, that is it. As you can see the field if of type DependecyProperty. This is all part of the DP way of life. The actual type of the age (which we know is int) will only be know when instantiating the DP.

Another thing that you may be wondering about is that the filed was named AgeProperty instead of just Age. The suffix Property is included as a convention to denote that this is the static field to the DP.

Part 3: Instantiation

The DependencyProperty class doesn't have a public constructor. To create an instance of this class we need to use the use the Register static method.

 

The simpler overload of this method takes three parameters, the first is a string that sets the name of the DP (Age in our case), the second expects the type of the property, which is int, and the last one represents the type of the class to which the DP is associated (in our example is the class Person).

 

The creation of the DP may be done inline as we've done in our example or it may be move in the static constructor like this:

public static readonly DependencyProperty AgeProperty;
static Person()
{
    AgeProperty = DependencyProperty.Register("Age", typeof(int), typeof(Person));
}

This code is more than a Factory to instantiate the DependencyProperty object, it also (as the name very well describes) registers the new property within the DP infrastructure. If you are interested in low level details, the actual registration occurs a private method called RegisterCommon of the DependencyProperty class. Download the framework source code or use Reflector to look inside.

Part 4: Wrapping the DP

Now that you saw what is really behind a DP you may be asking yourself. Ok, so my property is age of type int, but the DP is actually of type DependencyProperty, so how do I assign a value of 30 to the object that is not really an int? Cool, you are on the right track then!
The work of getting and setting the values of DPs goes through the DependencyObject class. It has a SetValue method for setting the value of the property and a GetValue method to retrieve the value. These methods are public you may use them directly like in the example below:

Person person = new Person();
person.SetValue(Person.AgeProperty, 31);
int myAge = (int)person.GetValue(Person.AgeProperty);

Since these methods are part of the DependencyObject class is clear that they are general purpose methods to retrieve or set values of properties. It is pretty straight forward then that you have to tell which property you want to get the value from. That is when you use your static DependencyProperty field that was already registered. Also the GetValue returns an instance of the class Object so you need to cast it to your type.
This is all good but I bet you are saying that this syntax is too verbose, right? Don't worry I think so too and the WPF team as well. In order to provide easy access to the DPs you may use property wrappers, like in our example. Using this strategy you code will become easier to work with and people don't even have to know if the property is a DP or not.

Person person = new Person();
person.Age = 31;
int myAge = person.Age;

IMPORTANT
When using properties you should be advised that you should not use any other code within the get or set accessors. This warning is documented in every book or piece of documentation I've read so far! Doing anything but using GetValue or SetValue in the accessors may really mess up your program. The thing is that WPF will use in many parts of it's code the GetValue and SetValue methods instead of your property wrapper. If your wrapper adds any thing to the mix you may have inconsistent results through your application, so watch out for this.

But wait, there's more

Now that we have the base idea of DP, let's keep going and try to understand few more concepts.

LocalValue vs EffectiveValue

Understanding this distinction really important in the process of learning WPF. The actual distinction is not even visible at first, but as soon as you begin to study coercion you notice that there is something more than just a value to the property.
The LocalValue is the "real" value, or the value that you set to the property. This value is stored but it may not be the one displayed if you try to use the GetValue method. But why would the property show a value other than the one you set? Let's imagine that in our example we could have a MinAge and a MaxAge properties and we set the values as in the following code:

person.MinAge = 21;
person.MaxAge = 150;
person.Age = 15;
int age = person.Age;

Setting the Age to 15 would not be allowed since the minimum value is 21. The DP infrastructure code has was to enforce these constraints (I'll show it a bit latter). When the code reads the property reads the Age it will return 21 which is the EffectiveValue. Does this implies that the 15 is gone? Nope! The 15 is still stored as the LocalValue (or real value if you will), if you don't believe me just use the ReadLocalValue method to read the Age property.
So the EffectiveValue is the result of applying constraints (or corrections) over the LocalValue. More often than not these values will actually be different.
One last thing about Local vs Effective is how the default value of the property is set. Age is an int, right? What is the default value for an int? Yep, 0 (zero) is the correct answer! So if you do person.Age you expect it to return 0 if you have not done any other initialization to this property. By now you probably figured out that the EffectiveValue has to be initialized to the default value of the property type. So EffectiveValue stores 0. The LocalValue on the other hand only gets a value when it set explicitly. But what is it's value mean while? Null? No, when the LocalValue is not set, the ReadLocalValue will return DependencyProperty.UnsetValue which is a public static field on the DependecyProperty class.

FrameworkPropertyMetadata

This class provides way to pass more parameters for the DependencyProperty. So far our property works fine, but we could do a little more with the FrameworkPropertyMetadata. Let's see some of the important properties that you can pass to the DP through the metadata:

  • DefaultValue: Using this property you can set the default value for the DP
  • CoerceValueCallback: This callback will try to make adjustments (or correct) to the value of the property. Coercion is a concept that we'll discuss a little latter.
  • PropertyChangedCallback: This callback will be fired when the value of the property is changed.
DefaultValue

Let's you pass in a default value for the DP. When you create an instance of the class Person the Age will be equals to 0 (zero). Now a challenge: When the DefaultValue is set where is this value stored, in the LocalValue or EffectiveValue? If you said EffectiveValue you are right. Try to use the ReadLocalValue and you'll see that the value is defined as DependecyProperty.UnsetValue.

Person person = new Person();
object o1 = person.Age; //returns 0
object o2 = person.GetValue(Person.AgeProperty); //is the same thing as the line above
object o3 = person.ReadLocalValue(Person.AgeProperty); // returns DependencyProperty.UnsetValue
CoerceValueCallback

This callback is set to a method that is going to take the value that is attributed to the property and apply some kind of correction to it. Setting a value to the property will change the value of the LocalValue and the EffectiveValue but if the CoerceValueCallback makes some change to the value this modified value is stored in the EffectiveValue while the original, unchanged attributed value is stored in the LocalValue. Let's say that any Age greater than 100 needs to be set as 100. The method to this is really simple:

 

private static object CoerceAgeValue(DependencyObject d, object baseValue)
{
    int age = (int)baseValue;
    return Math.Min(100, age);
} 

Now let's see how an instance of the class Person would behave when having it's value set:

Person person = new Person();
person.Age = 105; //will cause the value to be coerced
object o2 = person.GetValue(Person.AgeProperty); //returns 100 (this is the coerced value)
object o3 = person.ReadLocalValue(Person.AgeProperty); //returns 105 (this is the original value)

Another great example of the power given by this resource is the use of a ScrollBar:

ScrollBar bar = new ScrollBar();
//value = 0 (LV=Unset, EV=0), min = 0, max = 1


The ScrollBar has just been created and it's values are still the default values. Now let's change the Value to 100.

bar.Value = 100;
//value = 1 (LV=100, EV=1), min = 0, max = 1


The LocalValue is now 100 but the EffectiveValue was coerced to respect the Min and Max values. Though the Value shows 1 the actual value is still stored and was not lost.

bar.Minimum = 1;
//value = 1 (LV=100, EV=1), min = 1, max = 1


The Min value is set but it doesn't change the outcome for us.

bar.Maximum = 200;
//value = 100 (LV=100, EV=100), min = 1, max = 200


Now that the Max was set to 200 the coercion will not need to change the value stored in the Value property. Now it finally shows as 100 as we had originally defined. This means that the order in which you set the properties will not affect the final result. If it was not for the was DPs work you would need to first define the Min and Max and only then you could the set Value. This is awesome!!

PropertyChangedCallback

This has one simple mission: Notify that a change was made to the property. In the ScrollBar whenever the Minimum or Maximum are changed a callback is fired, this callback is responsible for coercing the Value of the control using the new Maximum or Minimum.

ValidateValueCallback

The ValidateValueCallback is the last parameter of the DepenencyProperty.Register method. This callback points to a method that will validate the value being attributed to the property. Here is an example of a validation of the Age property:

private static bool ValidateAgePropertyValue(object value)
{
    int age = (int)value;
    return age >= 0;
}

In this method we validate that the Age is greater than zero after all there is no negative ages. I know that you are thinking that this is very similar to the coercion concept, right? They way I perceive the difference is that the Validation is trying to identify an incorrect value while the the Coercion takes a valid value and makes some adjustments according to other properties in the object like the Minimum or Maximum in the ScrollBar example.

Another difference between the two is that the Validate method has one single parameter which is the new value that is being set. Since the method is a static method you do not have access to any other properties in the object which imposes a limitation on the kind of validation that could be made. The Coercion callback has two parameters: the dependency object that has the value and the new value for the property. Since this callback has access to the dependency object it is the ideal place to make the kind of tests that will try to limit the value between a minimum and a maximum.

Putting it all together

I know this is a lot to digest so the best way to really understand it all is to see a full example.

The following code is for a Car class with 3 Dependency Properties: Speed, MaxSpeed and MinSpeed. The speed has to be between the minimum and maximum. Every time the one of these properties is changed the others must me adjusted in order to keep the constraints we imposed.

public class Car : DependencyObject
    {
        #region Dependency Properties

        public static readonly DependencyProperty SpeedProperty;

        public static readonly DependencyProperty MinSpeedProperty;

        public static readonly DependencyProperty MaxSpeedProperty;

        #endregion


        #region Dependency Properties Wrappers

        /// <summary>
        /// Wrapper for the Speed dependency property
        /// </summary>
        public int Speed
        {
            get { return (int)GetValue(SpeedProperty); }
            set { SetValue(SpeedProperty, value); }
        }

        /// <summary>
        /// Wrapper for the MinSpeed dependency property
        /// </summary>
        public int MinSpeed
        {
            get { return (int)GetValue(MinSpeedProperty); }
            set { SetValue(MinSpeedProperty, value); }
        }

        /// <summary>
        /// Wrapper for the MaxSpeed dependency property
        /// </summary>
        public int MaxSpeed
        {
            get { return (int)GetValue(MaxSpeedProperty); }
            set { SetValue(MaxSpeedProperty, value); }
        }

        #endregion

        /// <summary>
        /// Static constructor where all dependecy properties are being initialized
        /// </summary>
        static Car()
        {
            Trace.WriteLine("Static Constructor");
            //configure and register speed property
            FrameworkPropertyMetadata speedMetadata = new FrameworkPropertyMetadata(0, null, CoerceSpeed);
            SpeedProperty = DependencyProperty.Register("Speed", typeof (int), typeof (Car), speedMetadata,
                                                        ValidateSpeed);

            //configure and register min speed property
            FrameworkPropertyMetadata minMetadata = new FrameworkPropertyMetadata(0, OnMinSpeedChanged);
            MinSpeedProperty = DependencyProperty.Register("MinSpeed", typeof (int), typeof (Car), minMetadata,
                                                           ValidateSpeed);

            //configure and register max speed property
            FrameworkPropertyMetadata maxMetadata = new FrameworkPropertyMetadata(1,OnMaxSpeedChanged, CoerceMaxSpeed);
            MaxSpeedProperty = DependencyProperty.Register("MaxSpeed", typeof (int), typeof (Car), maxMetadata,
                                                           ValidateSpeed);
        }

        #region Validate methods

        public static bool ValidateSpeed(object value)
        {
            Trace.WriteLine("ValidateSpeed");
            int speed = (int)value;
            return speed >= 0;
        }

        #endregion

        #region Coerce methods

        /// <summary>
        /// method for adjusting the speed according to the min and max
        /// </summary>
        /// <param name="d"></param>
        /// <param name="baseValue"></param>
        /// <returns></returns>
        public static object CoerceSpeed(DependencyObject d, object baseValue)
        {
            Trace.WriteLine("CoerceSpeed");
            Car car = (Car)d;
            int speed = (int)baseValue;
            //the speed can't be lower than the min speed
            speed = Math.Max(car.MinSpeed, speed);
            //the speed can't be greater than the max speed
            speed = Math.Min(car.MaxSpeed, speed);
            return speed;
        }

        /// <summary>
        /// method for adjusting the max speed according to me min speed.
        /// </summary>
        /// <param name="d"></param>
        /// <param name="baseValue"></param>
        /// <returns></returns>
        public static object CoerceMaxSpeed(DependencyObject d, object baseValue)
        {
            Trace.WriteLine("CoerceMaxSpeed");
            Car car = (Car)d;
            int maxSpeed = (int) baseValue;
            //the max speed can't be lower than the main speed
            return Math.Max(car.MinSpeed, maxSpeed);
        }

        #endregion

        #region Property changed methods

        /// <summary>
        /// this method is fired when the MaxSpeedProperty is changed
        /// </summary>
        /// <param name="d"></param>
        /// <param name="e"></param>
        private static void OnMaxSpeedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            Trace.WriteLine("OnMaxSpeedChanged");
            Car car = (Car)d;
            car.CoerceValue(SpeedProperty);
        }

        /// <summary>
        /// this method is fired when the MinSpeedProperty is changed
        /// </summary>
        /// <param name="d"></param>
        /// <param name="e"></param>
        private static void OnMinSpeedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            Trace.WriteLine("OnMinSpeedChanged");
            Car car = (Car)d;
            //coerce the max speed to ajdust to the new min speed
            car.CoerceValue(MaxSpeedProperty);
            //coerce the speed to adjust to the new min speed
            car.CoerceValue(SpeedProperty);
        }

        #endregion

    }

We can create an instance of the Car class in the initialization method of any window you like. Here is the my test code:

Car car = new Car();
Trace.WriteLine(string.Format("Speed:{0} Min:{1} Max:{2}",car.Speed,car.MinSpeed,car.MaxSpeed));
Trace.WriteLine(string.Format("Speed LocalValue:{0} EffectiveValue:{1}", car.ReadLocalValue(Car.SpeedProperty),
                car.GetValue(Car.SpeedProperty)));
car.Speed = 60;
Trace.WriteLine(string.Format("Speed: {0} Min:{1} Max:{2}",car.Speed,car.MinSpeed,car.MaxSpeed));
Trace.WriteLine(string.Format("Speed LocalValue:{0} EffectiveValue:{1}", car.ReadLocalValue(Car.SpeedProperty),
                car.GetValue(Car.SpeedProperty))); 
car.MinSpeed = 40;
Trace.WriteLine(string.Format("Speed: {0} Min:{1} Max:{2}",car.Speed,car.MinSpeed,car.MaxSpeed));
Trace.WriteLine(string.Format("Speed LocalValue:{0} EffectiveValue:{1}", car.ReadLocalValue(Car.SpeedProperty),
                car.GetValue(Car.SpeedProperty))); 
car.MaxSpeed = 80;
Trace.WriteLine(string.Format("Speed: {0} Min:{1} Max:{2}",car.Speed,car.MinSpeed,car.MaxSpeed));
Trace.WriteLine(string.Format("Speed LocalValue:{0} EffectiveValue:{1}", car.ReadLocalValue(Car.SpeedProperty),
                car.GetValue(Car.SpeedProperty)));

When you run this code you get the following output showing the order in which the methods were called:

Static Constructor
ValidateSpeed
ValidateSpeed
ValidateSpeed
ValidateSpeed
ValidateSpeed
ValidateSpeed
Speed:0 Min:0 Max:1
Speed LocalValue:{DependencyProperty.UnsetValue} EffectiveValue:0
ValidateSpeed
CoerceSpeed
ValidateSpeed
Speed: 1 Min:0 Max:1
Speed LocalValue:60 EffectiveValue:1
ValidateSpeed
OnMinSpeedChanged
CoerceMaxSpeed
ValidateSpeed
OnMaxSpeedChanged
CoerceSpeed
ValidateSpeed
CoerceSpeed
ValidateSpeed
Speed: 40 Min:40 Max:40
Speed LocalValue:60 EffectiveValue:40
ValidateSpeed
CoerceMaxSpeed
OnMaxSpeedChanged
CoerceSpeed
Speed: 60 Min:40 Max:80
Speed LocalValue:60 EffectiveValue:60

I hope this was usefull.

How to Learn WPF

I have been studying WPF more seriously for about two months. It is an amazing technology with a lot of new concepts that may be hard to grasp at first. In order to help others that may be trying to learnWPF and don't know where to start here is my take on it.

Although there is a lot of good material on the Internet the best way to learn (in my opinion) is still a good book. I have browsed through few books:

I found that the best one to get started with WPF and to read from cover to cover is Essential Windows Presentation Foundation by Chris Anderson. It is a relatively short book with about 500 pages. You will find that it is really easy to read with good examples and direct explanations. I have to say though that this book is not a good reference book. Don't let the fact that this is a 2007 book scare you away, this one is all about concepts and those didn't change since version 3.0 of the framework.

The other book I really liked was Pro WPF in C# 2008. This one is a in depth dive into WPF and maybe is not the book you would want to get started with. On the other hand this is the best reference book. It is really easy to browse since it has a dedicated chapter for each topic. Actually, this is the only book among the ones I looked at that has this format. The other books try to group related topics in the same chapter, which makes a good read but harder tolookup a specific thing.

The other book I would recommend is Windows Presentation Unleashed. It has an in depth coverage of all topics and is really easy to understand. The only thing I have against it is that it is a bit outdated since it was written for the framework 3.o. I wouldn't by this one but if you have someone you can borough from then I guess it isok.

There is also really good material on the MSDN site. Many of the books I mentioned before are heavily based on this documentation. The books are still more friendly to read but if you are looking any one topic in special the MSDN documentation is a really good place to search. Here is the link.

After you have a clear understanding on concepts such as Dependency Properties, Routed Events, Commands and Binding you have to look atMVVM concepts. This makes WPF even more amazing. I recommend getting started with Josh Smith's article on the MSDN Magazine called WPF Apps with The Model-View-ViewModel Design Pattern. Also make sure you follow the WPF Disciples.

If you are the screencast type of guy (or gal) you can checkout a lot of great videos on the WindowsClient.net site. Make sure you go to the Learn section.

Well, I think that is it. I'll update this post if I remember anything else but for now I think that this is plenty of material for you to get on your way to becoming aWPF master :-).

OCIEnvNlsCreate failed with return code -1

"OCIEnvNlsCreate failed with return code -1 but error message text was not available". This was the error that was really anoying my last week. I've had this problem before on one of our servers and this time it showed up in one of my co-workers machine.

Once again Sysinternals came to the rescue. When I used ProcessMonitor to watch the application running I noticed that it couldn't load some of Oracles dlls. The really strange part was that the dlls it was complaining about were from Oracle 10 and the client we were using were from version 11. I then decide to use ProcessExplorer to checkout out application process in order to find out what dlls were really loaded. Imagine my surprise when I saw that the application had the oci.dll from version oracle client 10 running. At some point someone had put a copy of this dll on the windows/system32 folder, and that was the dll that was being loaded instead of the correct one that was in the Oracle install directory.

After we deleted the incorrect dll our program still had the same error. Turns out that the ORACLE_HOME environment variable was not set either. Once we set the variable and restared IIS it was all fine! So, to sum up:

Error:

OCIEnvNlsCreate failed with return code -1 but error message text was not available

Solution:

 1 - Check if the ORACLE_HOME environment variable is set correctly. Here is how to do it.

 2 - Use Process Explorer to check out what versions of Oracle's dlls are loaded. If it's a different version from the version of the client you have installed, remove these incorrect versions from your machine. They may have been there from a previous client installation.

I hope this will help someone else!

How to Download NDC 2009 Videos

The NDC (Norwegian Developers Conference) 2009 had a lot of interesting talks which I was really looking forward to watch. The links I found in the net weren't right and I wasn't able to watch any of the videos. After snopping around for a while I bumped into a tweet from Scott Hanselman saying that the videos were there but they had  problem in the url. After been able to see the viedeos I used I sniffer to get the real url. The links were pretty close to the addresses I saw in the MSDN Up North blog post. The difference is that in this post the urls were: www.smartcom.no/download/video_file.wmv and the actual address is od01.smartcom.no/ndc/video_file.wmv.

The videos are still streams but if you want you can use RealPlayer to save the ones you want.

To make it easier for everyone here are the correct links (I corrected the links from the MSDN Up North blog post):

Ayende Rahien
Building Scalable Systems
Inversion of Control & Dependency Injection: Breaking out from the Dependency Hell
Object Relational Mapping + = 2: More than just Data <--> Object
Producing Production Quality Software
Writing Domain Specific Languages in Boo 
Craig Larman
Agile Architecting 
The "Toyota Way House" for Large-Scale Lean Development 
Ian Griffiths
Writing Custom Windows Presentation Foundation Pixel Shader Effects 
Jeremy D. Miller
Convention over Configuration applied to .NET 
Lessons Learned from a Long Lived Codebase 
Presentation Patterns for Composite Applications
Software Design and Testability 
Jimmy Nilsson
Is Domain-Driven Design more than Entities and Repositories? 
Jonas Follesø
Building Business Applications in Silverlight 3 
MVVM Patterns for Silverlight and WPF applications 
MVVM Patterns for Silverlight and WPF applications 
Kevlin Henney
A Decent Proposal
Lean Code
Slicing Design over Time
Modelling in the Age of Agility 
Sustainable Software Architecture
The Uncertainty Principle
Michael Feathers
Design Sense Deep Lessons in Software Design 
Functional Thinking for Object-Oriented Designers 
Seven Blind Alleys in Software Design 
Working Effectively with the Legacy Code: Taming the Wild Code Base 
Michele Bustamante
A Lap Around Geneva Framework 
Access Control Service: Federated Security in the Cloud 
Building a Windows Communication Foundation Router - Today and Tomorrow 
Windows Azure - Your Operating System in the Cloud 
Mike Cohn
Agile Estimating 
Agile Planning 
Getting Agile with Scrum 
Leading a Self-Organizing Team 
Prioritizing Your Product Backlog 
User Stories 
Peter Provost
Code First Analysis and Design with Visual Studio Team System 2010 Arch Ed 
Extending VSTS 2010 Architect Edition 
The Butterfly Effect 
Phil Haack
ASP.NET MVC + AJAX = meant for each other
Black Belt Ninja Tips ASP.NET MVC 
Phil Haack & Scott Hanselman The Haacked and Hanselman Show 
Rafal Lukawiecki
Architectual use of Business Intelligence in Application Design 
Automatic Recommendation Engine Based on Data Mining 
Finding Hidden Intelligence with Predictive Analytics of Data Mining 
Microsoft Solutions Framework 4.0 Core for Solution Delivery Projects 
Richard Campbell
Richard Campbell & Carl Franklin .NET Rocks! Live 
The Scaling IQ Test: When Development and IT Pros Collide 
Robert C. Martin
Clean Code: Functions 
Clean Design: Components Principles 
Clean Design: SOLID Principles I and II 
Clean Practice: Agility and Craftsmanship 
Roy Osherove
Unit Testing in Silverlight
Test Driven Development: Using Mock Objects 
Understanding Test Driven Development
Unit Testing Best Practices
Scott Hanselman
Deep Tour of .NET 4
Making Your Blog Suck Less: Social Networking and Your Personal Brand Online 
The magic of 'Astoria' - ADO.NET Data Services 
Ted Neward
Core Windows Communication Foundation Patterns 
Rethinking "Enterprise" 
Ted Neward The Busy Developer's Guide to ECMA(Java)Script 
Why the Next Five Years Will Be About Languages 
XML Messaging in .NET using Windows Communication Foundation 
Tim Huckaby
Building Data Visualization Applications with the Windows Presentation Foundation
Integrating Windows Presentation Foundation and Windows Communications Foundation into Your Office Business Applications 
Jump into Windows Presentation Foundation! ...and Become Immediately Effective 
Udi Dahan
Asynchronous Systems Architecture for the Web 
Avoid Failed SOA-business & Autonomous Components to the Rescue 
Intentions and Interfaces - Making Patterns Complete 
Reliability, Availability, and Scalability - How to have your cake, and eat it too 

Hope this will help.

How to keep two ScrollViewers in Sync in WPF

As I got to know WPF, one of the features that I really like was the ability to bind the value of one control to the value of another one. Well, the other day I had a situation where I had 2 ScrollViewers side by side and I wanted to the two of them to be in sync. So, if I used the scrollbar one the left one I'd like the one on the right to scroll by the same increment. My first thought was then to bind the value of the offset of the scrollbars, that would be simple right? Not. The offset property is readonly. The way around this is really simple, you need you use the ScrollChanged event and in that event you use the method ScrollToVerticalOffset to move the ScrollBar of the other ScrollViewer.

Here is an example where I have a window with two ScrollViewers, each one has a ListBox with 7 items inside. As you scroll on the left side scroll viewer to see all the items in the ListBox you will notice that the ScrollViewer on the right will follow.

<Window x:Class="WpfScrollbarSync.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="100" Width="300">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="1*" />
            <ColumnDefinition Width="1*" />
        </Grid.ColumnDefinitions>
        <ScrollViewer Grid.Column="0" Name="scrollViewerLeft" ScrollChanged="scrollViewerLeft_ScrollChanged">
            <ListBox>
                <ListBoxItem>1</ListBoxItem>
                <ListBoxItem>2</ListBoxItem>
                <ListBoxItem>3</ListBoxItem>
                <ListBoxItem>4</ListBoxItem>
                <ListBoxItem>5</ListBoxItem>
                <ListBoxItem>6</ListBoxItem>
                <ListBoxItem>7</ListBoxItem>
            </ListBox>
        </ScrollViewer>
        <ScrollViewer Grid.Column="1" Name="scrollViewerRight">
            <ListBox>
                <ListBoxItem>1</ListBoxItem>
                <ListBoxItem>2</ListBoxItem>
                <ListBoxItem>3</ListBoxItem>
                <ListBoxItem>4</ListBoxItem>
                <ListBoxItem>5</ListBoxItem>
                <ListBoxItem>6</ListBoxItem>
                <ListBoxItem>7</ListBoxItem>
            </ListBox>
        </ScrollViewer>
    </Grid>
</Window>

And here is the codebehind:

public partial class Window1 : Window
{
    public Window1()
    {
        InitializeComponent();
    }

    private void scrollViewerLeft_ScrollChanged(object sender, ScrollChangedEventArgs e)
    {
        scrollViewerRight.ScrollToVerticalOffset((sender as ScrollViewer).VerticalOffset);
    }
}

I hope this can save someone one minute or two. :-)

Windows 7 x64 and Oracle Client

I installed my Windows 7 x64 this weekend and so far everything is great. Much better than when I was running on Vista.

I thought I had run into my first problem with 7 when was setting up my Oracle connection. I installed the Oracle Client 11g x64 successfully, I could even connect to the database using SqlPlus. My Visual Studio on the other hand disagreed. When I tried to configure a connection to my Oracle server I got the following error:

Exception: Attempt to load Oracle client libraries threw
BadImageFormatException. This problem will occur when running in 64
bit mode with the 32 bit Oracle client components installed

This was weird, after all I could connect to the database through SqlPlus, right? The problem is that VS2008 is 32 bit and as such it needs a 32 Oracle Client in order to connect to the db. When I installed the 32 bit client VS was able to connect to the db on the spot. So the only problem I had with Windows 7 so far had nothing to do with Windows 7, in fact you would run into the same situation in any other 64 bit version of Windows.

 

Converting Base10 to Base26

There is a post I answered on the asp.net forums I thought was really interesting because it reminded me of my college times. Actually I'm pretty sure that the guy who posted the question was trying to get an answer to his homework, but it doesn't matter, I had fun doing it :-). The problem was to do an ascending sequence using the alphabet (which is a Base26). Something like: A,B,C...Z,AA,AB,AC...AZ,BA,BB,BC...BZ and so on. Well the easiest way to do this is to convert our regular Base10 numbers to Base26 because using Base10 we can do a plain for loop and cout up to the number we want and while doing the loop we can convert the Base10 to Base26. Here is the algorithm: 

        public static string NumberToString(int value)
        {
            StringBuilder sb = new StringBuilder();
            
            do
            {
                value--;
                int remainder = 0;
                value = Math.DivRem(value, 26, out remainder);
                sb.Insert(0, Convert.ToChar('A' + remainder));
                
            } while (value > 0);

            return sb.ToString();
        }

I know this isn't very useful for everyday programming but it was fun to remember the time I was still in college solving this kind of problem. It was a really fun exercise.

Typed Convert using Generics

Last night I answerd a interesting question on the Asp.Net Forums that I thought is worth a post. The objective was to create a method using Generics that could get a value from the Session only instead of returning a Object it would return the value in the type defined in the generic method. Just to make the demonstration easier I'll use a Dictionary instead of the Session but it works just the same:

class TypeTest
{
    private static Dictionary<string, object> PretendSession = new Dictionary<string, object>();

    public static void Test()
    {
        PretendSession.Add("int", 10M);
        Console.Out.WriteLine(Get<int>("int"));
    }

    public static T Get<T>(string theKey)
    {
        object aSessionObject = PretendSession[theKey];

        if (aSessionObject == null)
        {
            return default(T);
        }

        return (T) aSessionObject;
    }
}

This code works well for most cases but you can get in trouble when you work with Value Types. Look at code that follows and to undestand the problems with boxing and unboxing value types:

 //doesn't work, need explicit cast 
int i = 10M; 

//now it's fine 
int i = (int)10M; 

//boxing and unboxing work fine 
object o = 10; 
int i = (int)o; 

//doesn't work 
object o = 10M; 
int i = (int)o;

When you know exactaly what is the type of you are putting inside the Session it all goes fine. When you don't know what type you are working with you need the help of the Convert class to convert the type before casting it. To do this we test if the object is of type ValueType and if it is, before casting it we use the ChangeType method of the Convert class to make sure that the object really contains the type we will try to cast it to.

 

class TypeTest
{
    static Dictionary<string, object> PretendSession = new Dictionary<string, object>();

    public static void Test()
    {
        PretendSession.Add("int", 10M);
        Console.Out.WriteLine(Get<int>("int"));
    }

    public static T Get<T>(string theKey)
    {
        object aSessionObject = PretendSession[theKey];

        if (aSessionObject == null)
        {
            return default(T);
        }

        if (aSessionObject is ValueType)
        {
            return (T)Convert.ChangeType(aSessionObject, typeof(T));
        }

        return (T)aSessionObject;
    }
}

Now you should be safe to use your Get<T> method. Hope this can help other people that face this same issue.

ELMAH: Error logging doesn't get any simpler

ELMAH stands for Error Logging Modules and Handlers. I don't love the name but everything else about it is great!! In it's site it is described as:

"ELMAH (Error Logging Modules and Handlers) is an application-wide error logging facility that is completely pluggable. It can be dynamically added to a running ASP.NET web application, or even all ASP.NET web applications on a machine, without any need for re-compilation or re-deployment."

I'm using this blog as I write it and if I had to classify it I'd say it is a pre pre alpha release not suitable for anyone else but me. The only use I see for other people right now is to look around the code (what should be quick). Given my choice to put the application online in this early stage it seamed pretty obvious that that I needed to start logging the errors my users are getting so that I can work on them as soon as possible. As usual I was deciding between using NLog or Log4Net when I saw a new post by Scott Hanselman talking about ELMAH.

As usual Scott's post saved me a lot of time! Setting up ELMAH was really as simple as he said. In a matter of minutes I was logging all errors in my application. Now I can sleep well knowing that every weekend I'll have a list of errors to work on :-)

I highly recommend you use this in your application even if you are already using another logging framework. The cool thing about ELMAH is that if you missed something forgot to place logging on some part of your app, ELMAH won't. It will log every error you have and store it in XML, SQLServer, Oracle...

Lessons Learned in Url Rewriting

When I decided to write my own blog and leave Mephisto one of the few requirements I felt were really important was to maintain the url pattern I was already using. My articles had url's like this:

www.gbogea.com/year/month/day/permalink

When I first looked up url rewriting in google I found a great article by ScottGu that really suited my needs. I'm using IIS7 on my develpment machine and I thought I was also using it on the hosting service I contracted. ScottGu's post shows a really simple way to do rewriting when using IIS7. All you need is the UrlRewriter.Net module and a few configurations to your web.config.
Checkout SocottGu's post for the whole config, here I'll only show you the pattern I needed to be compatible with the articles url in Mephisto. Here it is:

<rewrite url="~/((19|20)\d\d)/(0?[1-9]|1[012])/(0?[1-9]|[12][0-9]|3[01])/(.+)" to="~/PostDetail.aspx?year=$1&amp;month=$3&amp;day=$4&amp;permalink=$5"/>

Once I did this everything worked fine. I had achieved my objective, or so I thought. The problem is that I found out later on that my hosting service was actually using IIS6 and to my sadness IIS6 doesn't do well with url's that do not have an extension.

When I contacted my hosting they informed me that they had support for ISAPI Rewrite, which is alson discussed in Scott's post but sadly not in engough depth for my case. The configuration is also a lot more anoying then with UrlRewrite.Net. If you have to use ISAPI Rewrite my first recomendation is to get in touch with your hosting and find out if they have version 2 or 3 installed. It makes a great difference. In my case I had version 3 installed. Here are the steps I took to configure it:

1 - Create a ".htaccess" file in the root or your web application.

2 - In the file I've written the following code:

RewriteEngine on
RewriteBase /
RewriteRule ((19|20)\d\d)/(0?[1-9]|1[012])/(0?[1-9]|[12][0-9]|3[01])/(.+)$ /PostDetail.aspx?year=$1&month=$3&day=$4&permalink=$5 [NC,L]


The rewrite rule is basically translating the pattern I'm using (www.gbogea.com/year/month/day/permalink) to the real pattern that the ASP.NET applcation understands (PostDetail.aspx?year=YYYY&month=MM&day=DD&permalink=WHATERVER).

The options and the end are also very important. NC means Case Insensitive. L means that no other subsquent rule should be processed, it stops here. You will find a lot of examples that use an R (which means Redirect) however this was not suited to my case. The redirect would be done to the new URL and then the url shown in the browser would be the ASP.NET url and not mine.

This usage was not easy to figure out. If you need any assistance on using ISAPIRewrite I can recomend this two links:

Documentation: http://www.helicontech.com/isapi_rewrite/doc/
Blog: http://helicontech.blogspot.com/search/label/isapi_rewrite

Helicon's blog was the one that helped me the most. The have a post about common issues people have which is really to the point.

Looking back at all the work I had it would probably be cheaper just to have my hosting plan upgraded to IIS7 but where would be the fun in that right? Joking aside, it's this kind of thing that make you learn, perhaps your client doesn't have the option to migrate to IIS7, then what would you do? Having said that, if you have the choice between using IIS 6 and 7 I would definitely go with 7 and avoid using ISAPI Rewrite altogether.

If you want to have a closer look at my web.config or the .htaccess file you can look at the source code for this blog at speakoutblog.codeplex.com. At this time there is no realease version yet but you can go to the source code and download any commit you want.

MVC Storefront: Migrating to the Entity Framework

The title of the post is actually misleading. A better title (although too long) would be: Migrating the Repository concept used in the MVC Storefront to the Entity Framework.

Lately I’ve been playing more with the Entity Framework. The other day I was trying to replicate the way Rob Conery used the Repository Pattern in the MVC Storefront sample application and I was surprised to learn that the Entity Framework has some differences from LINQ to SQL that I did not expect.

My first test was very simple. I wanted to get an IQueryable of Posts with it’s respective Comments attached. The StoreFront did this in a really clever and simple manner. The following code was supposed to work:

class BlogRepository
{
    SOEntities ctx = new SOEntities();

    public IQueryable<Comment> GetComments()
    {
        return from comment in ctx.Comments.Include("Post")
               select new Comment()
               {
                   CommentId = comment.CommentId,
                   Author = comment.Author,
                   Body = comment.Body,
                   PostId = comment.Post.PostId
               };
    }

    public IQueryable<Post> GetPosts()
    {
        var posts = from post in ctx.Posts
                    let comments = GetComments()
                    select new Post()
                           {
                               PostId = post.PostId,
                               Title = post.Title,
                               Body = post.Body,
                               Comments = comments.Where(x => x.PostId == post.PostId)
                           };
        return posts;
    }
}

class Post
{
    public Guid PostId { get; set; }

    public string Title { get; set; }

    public string Body { get; set; }

    public IList<Comment> Comments { get; set; }
}

class Comment
{
    public Guid CommentId { get; set; }

    public Guid PostId { get; set; }

    public string Author { get; set; }

    public string Body { get; set; }

}

class Program 
{
static void Main(string[] args)
{
    BlogRepository rep = new BlogRepository();
    var posts = rep.GetPosts();
    posts = posts.Where(x => x.Title.Contains("MVC"));
    List<Post> postList = posts.ToList();
}
}

I get an error saying that Linq to Entities does not recognize the method GetComments().

It’s not a bug, it’s is just the way the EF works. The method GetComments can’t be translated to anything in the provider. But why does it work with Linq to Sql you ask? Because it converts the Linq expression in a different way. Sorry but the post would be too long if I got into this subject.

The way recommended by the EF team is you use the AsEnumerable() extension method, forcing the initial query to be executed and then you would be working with objects. Here is how I needed to change my code for this to work:

public IQueryable<Post> GetPosts()
{
    var posts = from post in ctx.Posts.AsEnumerable()
                let comments = GetComments()
                select new Post()
                       {
                           PostId = post.PostId,
                           Title = post.Title,
                           Body = post.Body,
                           Comments = comments.Where(x => x.PostId == post.PostId)
                       };
    return posts.AsQueryable();
}

This does work, but when ToList() method is called in the posts object, instead of filtering the posts in the sql code, all the posts are brought from the database and then they are filtered as objects. This is a work around but it’s not ideal.

I have another work around, it also isn’t the ideal but it does work in the sense that it will apply the filter in the database.

public IQueryable<Post> GetPosts()
{
    var comments = GetComments();
    var posts = from post in ctx.Posts
                select new Post()
                       {
                           PostId = post.PostId,
                           Title = post.Title,
                           Body = post.Body,
                           CommentsQry = comments.Where(x => x.PostId == post.PostId)
                       };
    return posts;
}

class Post
{
    public Guid PostId { get; set; }

    public string Title { get; set; }

    public string Body { get; set; }

    public IList<Comment> Comments { get; set; }

    public IQueryable<Comment> CommentsQry
    {
        set { Comments = new LazyList<Comment>(value); }
    }
}

The trick is that I introduced a IQueryable property in the Post class. This property receives an IQueryable and under the hood converts it to a LazyList and sets the Comments property. Doing this overcomes the limitation that the EF has in not letting you use constructors that take parameters in the EF code. It only allows parameterless constructors on the select projection.

If you run this code you will see that the records are filtered in the database. The reason I still don’t consider this solution ideal is that I had to make a change to my model class and created a property that is not related to the business but rather to a limitation imposed by the framework. I still don’t see a way around this. If anyone has any suggestions please do leave them as comments.

A very interesting post was written by Muhammad Mosa a while ago. It’s worth visiting his blog to checkout his idea.

Find and Replace using Regular Expressions within Visual Studio

Regular expressions can be a great addition to the Find and Replace functionality within Visual Studio, specially when you want do do some transformation on the text you are looking up. Lately I’m working on a simple conversion class to transform some HTML into RTF. I got a list of special characters in HTML that I had to convert to the RTF equivalent and for that I needed to create a dictionary. The values where listed in a text document like this:

\'b0 \tab &deg;\par
\'b1 \tab &plusmn;\par
\'b2 \tab &sup2;\par
\'b3 \tab &sup3;\par
\'b4 \tab &acute;\par
\'b5 \tab &micro;\par
\'b6 \tab &para;\par
\'b7 \tab &middot;\par
\'b8 \tab &cedil;\par
\'b9 \tab &sup1;\par
\'ba \tab &ordm;\par
\'bb \tab &raquo;\par
\'bc \tab &frac14;\par
\'bd \tab &frac12;\par
\'be \tab &frac34;\par

And I needed to create a dictionary with the key being the HTML code (third column) and the RTF code (first column) the value. Like this:

Dictionary<string, string> charsMapping = 
    new Dictionary<string, string>();
charsMapping.Add("&euro;", @"\'80");

Here is the expression to find the matches within Visual Studio: __ {\\’:a:a}{.}{&:a;}{\\par}

Each pair of { } is a group to be matched. The difference is that the usual \w (letters or numbers) is :a. In my expression I have four groups the fist is the match for the RTF character and the third is the match for the HTML code. Knowing that the Replace expression is as follows: __charsMapping.Add(”\3”, @”\1”);

Here is how it would look like in VS:

Doing this is much easier then creating the dictionary by hand of even writing a console app to do the replace. Sure I could have used some other text tool to do the same but it wouldn’t be as much fun as figuring out how to do it in VS.

Here is the final output:

Dictionary<string, string> charsMapping = 
    new Dictionary<string, string>();
charsMapping.Add("&deg;", @"\'b0");
charsMapping.Add("&plusmn;", @"\'b1");
charsMapping.Add("&sup2;", @"\'b2");
charsMapping.Add("&sup3;", @"\'b3");
charsMapping.Add("&acute;", @"\'b4");
charsMapping.Add("&micro;", @"\'b5");
charsMapping.Add("&para;", @"\'b6");
charsMapping.Add("&middot;", @"\'b7");
charsMapping.Add("&cedil;", @"\'b8");
charsMapping.Add("&sup1;", @"\'b9");
charsMapping.Add("&ordm;", @"\'ba");
charsMapping.Add("&raquo;", @"\'bb");
charsMapping.Add("&frac14;", @"\'bc");
charsMapping.Add("&frac12;", @"\'bd");
charsMapping.Add("&frac34;", @"\'be");
charsMapping.Add("&iquest;", @"\'bf");

Of course the number of characters was much bigger but it doesn’t matter here. If you need more info on regular expressions you might want to check out the Regular-Expressions.info site, they have a lot of good info on the subject. There are some specifics to using regular expressions on VS so you need to make sure to visit MSDN Reference.

Find out the calling method

This is one that I found really interesting. I needed to log which methods were calling a certain method, I knew that reflection was the answer but I never thought it would be so easy.

Have you used the CallStack window on your VisualStudio when you are debugging? Well, all that information is available through the System.Diagnostics.StatckTrace class. This means that you have access to method calling stack to do whatever you like.

The StackTrace is composed of an array of StackFrames which represent each method on the stack.

To demonstrate this I’ll create a class with four methods (Method1, Method2, Method3, Method4) which will be called in the following order:

Main -> Method1 -> Method2 -> Method3 -> Method4

class Program
{
    static void Main(string[] args)
    {
        StackTraceTest stt = new StackTraceTest();
        stt.Method1();
    }
}

class StackTraceTest
{
    public void Method1()
    {
        Console.Out.WriteLine("Inside Method1");
        Method2();    
    }

    private void Method2()
    {
        Console.Out.WriteLine("Inside Method2");
        Method3();
    }

    private void Method3()
    {
        Console.Out.WriteLine("Inside Method3");
        Method4();
    }

    private void Method4()
    {
        Console.Out.WriteLine("Inside Method4");
        StackTrace st = new StackTrace();
        StackFrame[] frames = st.GetFrames();
        for (int i = 0; i < frames.Count(); i++)
        {
            Console.Out.WriteLine("StackTrace info: Index: {0}/Method: {1}", 
                i, frames[i].GetMethod().Name);
        }
    }
}

Each method displays a message on the console letting you know that it has been invoked. When the program gets to Method4 it will print the name of the methods on the stack.

Here is the output:

Put a break point on the end of the Method4 and you can take a look at VisualStudios CallStack window to compare with the console output.

As a test you might want to move the StackTrace code to the other methods to see that it will show all the method that led to method currently executing.

For more information look at the StackFrame and MethodBase classes at MSDN.

When to use GUID over Autoincrement

The autoincrement feature in SQLServer tables is one that is really very handy. I’ve always like Oracle databases but it’s sequences are really much more complicated to manage than the autoincrement columns in SQLServer. If you are doing a project that is only going to run on Oralce or SQLServer either approach is fine and you won’t have any trouble.

The project I’m working on however has a requirement to work just the same on Oralce or SQLServer and the possibility that other databases may be added in the future. From day one my first worry was about if we were going to use Autoincrement and Sequences or we had to find another way out. The way out in this case would be to use GUID (Globally Unique Identifiers). In out case we chose to use Autoincrement for SQLServer and Sequences in Oracle. Mostly this approach was chosen because the guys that hired me thought that it would be much easier to search database for a record with a primary key like 1 or 15604 then something like 3F2504E0-4F89-11D3-9A0C-0305E82C3301. And I agreed with them on this, it is really simpler to say to the guy next to you to check if the person with id 2350 exists in the database the to tell him a GUID.

Of course we had a price to pay for this decision. Our DAL (Data Access Layer) was much more complicated because we had to deal with the Autroincrement vs Sequences problem. Imagine that you have a simple table called person with two columns only: ID and Name. Look at the difference in the insert clauses for each database:

Oracle
INSERT INTO PERSON (ID, NAME) VALUES (SEQ_PERSON.NEXTVAL, 'GABRIEL');
SQLServer
INSERT INTO PERSON (NAME) VALUES ('GABRIEL');

Observe that with Oracle I have to specify the PK column and in SQLServer I don’t and even worst I have to call the sequence SQL_PERSON to get the next value for the insert. If I want to return the value of the ID of the record we just inserted I’d have to do this:

Oracle
INSERT INTO PERSON (ID, NAME) VALUES (SEQ_PERSON.NEXTVAL, 'GABRIEL') RETURNING ID INTO :ID;
SQLServer
INSERT INTO PERSON (NAME) VALUES ('GABRIEL');
SELECT CAST(SCOPE_IDENTITY() AS INT);

I think you get the point right? There are a lot of differences in both databases! If we had choosen to use GUID id’s our life in the DAL would be much simpler. The GUID would be generated in the DAL which would make the insert statements very similar if not equal most of the time. Returning the generated GUID would also be a piece of cake. It’s true that using numeric PK’s creates better indexes and would consume less space but I find that these improvements would’ve been superseded by the ease in development.

So to sum up, when developing a system that should be database independent I would recommend using the table’s primary key’s as GUID in order to avoid using Autoincrement and Sequences. Your DAL layer would be more uniform and you could use ANSI SQL more often.

Just in case you are wondering we did when we couldn’t use ANSI SQL we created a SQL translator that would convert all the commands create for SQLServer to Oracle and this translator is part of our DAL generator so when I create a DAO for SQLServer the generator will create its’ structure and also Oracle’s all at once.

Entity Framework Free Book

If you are interested in learning more about the Entity Framework you need to visit Zeeshan Hirani’s Blog and download an e-book that he made available for free. It’s a problem solution approach to explain the EF in good detail. The book has 514 pages of lots of good information.

You might also like to watch the two short videos on the EF available at the asp.net site. Here are the links:

Get started with the entity framework

Use the new Entity Data Source

Ajax.BeginForm: Clear Form After Submit

If you are using ASP.NET MVC, here is a simple tip on how to clear an ajax form after successfully submitting it with a little help from jQuery.

The first step is to get the jQuery Form Plugin, add it to your Scripts folder and then add a script reference to it in your masterpage. jQuery is already included in the projects since the release of the MVC so you don’t need to download and include it.

<script src="../../Scripts/jquery-1.2.6.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.form.js" type="text/javascript"></script>

You can then create a function that will call the clearForm function from the Form Plugin.

<script type="text/javascript">
   function done() {
       $('form').clearForm();
   }
</script>

Now you can use the OnSuccess callback from the Ajax.BeginForm helper to point to the done() function we just created. This function will be called automatically after the form submit completed successfully.

<% using (Ajax.BeginForm("SaveComment", new AjaxOptions { 
         UpdateTargetId = "feedback", 
         InsertionMode = InsertionMode.Replace, 
         OnSuccess = "done"}))
{ %>

Here is the complete code:

<script type="text/javascript">
            function done() {
                $('form').clearForm();
            }
    </script>
    <h2 id="feedback"></h2>
    <fieldset>
        <% using (Ajax.BeginForm("SaveComment", new AjaxOptions { 
               UpdateTargetId = "feedback", 
               InsertionMode = InsertionMode.Replace, 
               OnSuccess = "done"}))
           { %>
            <dl>
                <dd><%= Html.TextBox("Comment.Author")%></dd>
                <dd><input type="submit" title="Submit" /></dd>
            </dl>
        <% } %>
    </fieldset>

 

Sharing Static Field Only Within a Thread

When you use a static field it’s data is shared among any classes using it. That’s something that everyone should know. When programming web applications, every request from the browser will span a new Thread. If you have a static field in a class that is used in a page’s code behind all it’s value will be shared by all requests.

This is great but sometimes you want to share the static field between a bunch of classes that do some business logic when the browser sends a request and you want the static field to share data among all these business logic classes. But when you think that there will be several requests to your site simultaneously (hopefully) you notice that the static field is not only being shared between all business classes in the request but between all business classes in all the requests. You might or might not want this behavior.

In order for a field to have a different value for each thread running, the simplest way is to decorate the static field with a ThreadStaticAttribute attribute.

[ThreadStaticAttribute]
public static int ThreadInfo;

If you never used this attribute here is piece of code that will prove that this really works:

class Program
    {
        static void Main(string[] args)
        {
            ParentClass.MySharedInfo = 5;

            for (int i = 1; i < 3; i++)
            {
                ParameterizedThreadStart pts = new ParameterizedThreadStart(RunTest);
                Thread t = new Thread(pts);

                t.Start(i * 10); 
        }

        }

        public static void RunTest(object val)
        {
            ParentClass.MySharedInfo = (int)val;

            ParentClass cp = new ParentClass();
            cp.Write();
            cp.ChildClass.Write();

            Thread.Sleep(1000);
            cp = new ParentClass();
            cp.Write();
            cp.ChildClass.Write();
        }
    }

    class ParentClass
    {
        [ThreadStaticAttribute]
        public static int MySharedInfo;

        public ChildClass ChildClass { get; set; }

        public ParentClass()
        {
            ChildClass = new ChildClass();    
        }

        public void Write()
        {
            Console.WriteLine("ParentClass ThreadId:{0} / MySharedInfo:{1}",
                Thread.CurrentThread.ManagedThreadId, MySharedInfo);
        }
    }

    class ChildClass
    {
        public void Write()
        {
            Console.WriteLine("ChildClass ThreadId:{0} / MySharedInfo:{1}", 
                Thread.CurrentThread.ManagedThreadId, ParentClass.MySharedInfo);
        }
    }

The code above defines two classes: ParentClass and ChildClass. ParentClass has a static field decorated with the ThreadStaticAttribute attribute and an instance of a ChildClass. The Main method set’s the static filed to 5. Then a loop will start two Threads and create a new ParentClass in each of them. The static field value is set to different values. The class will print the static field value from the ParentClass and from the ChildClass two times. Between the first and the second time the value is printed there is a Thread.Sleep of 1 second. This pause shows that each thread maintains it’s own value.

ToDataTable Method for Linq Queries Results

When you query a DataTable using Linq the normal result will be an IEnumerable, which is not a DataTable (obviously). If you need a DataTable as a result you already have an extension method called CopyToDataTable which will turn your IEnumerable into a new DataTable. Although if you want to join two DataTables and the merge the DataRows into a new Anonymous Type the CopyToDataTable will not help you. Let’s see how to create a helper method that will transform an IEnumerable of anonymous types into a new DataTable.

First let’s create two DataTables: Person and Job. Here’s the code:

DataTable dtPerson;
DataTable dtJob;

dtPerson= new DataTable("Person");
DataColumn dc;

dc = new DataColumn("Id", typeof(int));
dtPerson.Columns.Add(dc);

dc = new DataColumn("Name", typeof(string));
dtPerson.Columns.Add(dc);

dc = new DataColumn("Age", typeof(int));
dtPerson.Columns.Add(dc);

//JOB DataTable
dtJob = new DataTable("Job");

dc = new DataColumn("PersonId", typeof(int));
dtJob.Columns.Add(dc);

dc = new DataColumn("Position", typeof(string));
dtJob.Columns.Add(dc);

Here is the code to populate the DataTables:

DataRow dr = dtPerson.NewRow();
dr[0] = 1;
dr[1] = "Gabriel";
dr[2] = 31;
dtPerson.Rows.Add(dr);

dr = dtPerson.NewRow();
dr[0] = 2;
dr[1] = "Elisa";
dr[2] = 27;
dtPerson.Rows.Add(dr);

dr = dtJob.NewRow();
dr[0] = 1;
dr[1] = "Programmer";
dtJob.Rows.Add(dr);

dr = dtJob.NewRow();
dr[0] = 2;
dr[1] = "Manager";
dtJob.Rows.Add(dr);

Now let’s write a Linq query to join these two DataTables:

var query = from p in dtPerson.AsEnumerable()
             join j in dtJob.AsEnumerable() on p.Field<int>("Id") equals j.Field<int>("PersonId")
             select new
             {
                 Id = p.Field<int>("Id"),
                 Name = p.Field<string>("Name"),
                 Job = j.Field<string>("Position")
             };

Notice that the result of the query is an IEnumerable of an anonymous type with three properties (Id, Name and Position) which is a merge of our two DataTables data. Now for the helper method that will convert this result to a new DataTable. The base of this idea is in my previous article on using reflection on anonymous types. I’ll use this principle to inspect the properties of the anonymous type and create new DataColumns for the new DataTable. After that all it’s needed is iterating over the results creating new DataRows. Here’s the method:

public static DataTable ToDataTable(this IEnumerable objectList)
{
    //if the result is null or if the number of
    //objects is less then 1, return null
    if (objectList == null || 
        objectList.OfType<object>().Count() < 1)
    {
        return null;
    }
    //create a new list based on the IEnumerable
    List<object> list = new List<object>(objectList.OfType<object>());

    //take the first object in the list
    object o = list[0];
    //get the type of the object
    Type t = o.GetType();
    //read all the info of the properties
    PropertyInfo[] properties = t.GetProperties();

    DataTable dt = new DataTable();
    //for each property create a new column
    //in the DataTable
    foreach (var pi in properties)
    {
        //the new column has the name of the property
        //and it's type
        DataColumn dc = new DataColumn(pi.Name, pi.PropertyType);
        //add the column to the DataTable
        dt.Columns.Add(dc);
    }

    //add the rows to the DataTable
    foreach (var item in list)
    {
        DataRow dr = dt.NewRow();
        //each property represents a column 
        //that has to be set
        foreach (var pi in properties)
        {
            dr[pi.Name] = pi.GetValue(item, null);
        }
        dt.Rows.Add(dr);
    }
    return dt;
}

That’s it. The returning DataTable will have three columns (int Id, string Name, string Position). If you want you can download the code for the class here. In this code for download I transformed the ToDataTable method into an extension method.

Reflection on Anonymous Types

Using reflection on anonymous types is just like reflection on any other type.

Consider this simple anonymous object being instantiated:

var anonyObject = new
{
    Name = "Gabriel",
    Age = 31
};

If you want to know all the properties, it’s values and types you can query the object with the reflection classes like this:

//get the type of the anonymous object
Type anonyType = anonyObject.GetType();
//get all the properties info
PropertyInfo[] props = anonyType.GetProperties();
//display each of the properties info
foreach (var prop in props)
{
    Console.WriteLine("Name:{0}, Value:{1}, Type:{2}",prop.Name, 
        prop.GetValue(anonyObject, null), prop.PropertyType);
}

I just wanted to share this code because I’m going to use it in my next article in which I will talk about creating a helper method to transform the result from a Linq query that returns anonymous types to a DataTable.

ASP.NET MVC: ListBox

The Html.ListBox helper is a good choice if you need to represent many-to-many relationships in a form.

Lets say you have a many-to-many between the Posts table and the Categories table. When you are creating a new post you need to select all the categories that it belongs to. When you are editing a post you need to show the categories it already belongs to in order to make a new selection (or not).

 The ListBox would allow you to make all the selections necessary, so the Action and the View for the New Post would need something like this:

Action:

[AcceptVerbs("GET")]
public ActionResult New()
{
        ViewData["Categories"] = _postService.GetCategories();
        return View();
}

View:

<%= Html.ListBox("CategoryList", new MultiSelectList((IList<Category>)ViewData["Categories"], "ID", "Name"))%>

And the View and Action for the Edit would be like this:

Action:

[AcceptVerbs("GET")]
public ActionResult Edit(int? id)
{
        int postId = id ?? 0;
        //get the post that is being edited
        Post post = _postService.GetPost(postId);
        //get all the categories
        ViewData["Categories"] = _postService.GetCategories();
        //get the id's of the categories to which the post belongs
        ViewData["CategoryIDs"] = post.Categories.Select(c => c.ID);
        return View(post);
}

View:

<%= Html.ListBox("CategoryList", new MultiSelectList((IList<Category>)ViewData["Categories"], "ID", "Name", (IEnumerable<int>)ViewData["CategoryIDs"]))%>

Note that this time I had to pass an extra parameter to the ListBox method which is a list of the categories ID’s that are already associated with the Post. This list will be used to make the initial selection in the ListBox rendered in your HTML.

One last thing you need to know is how to get the ID’s of the selected categories back in your action. This is pretty simple as well. The Form will have a CategoryList item that will have a comma separated string with all the selected lines, all you need to do is split this in a array of strings and them save them to the database as you see fit.

string[] selected = Request.Form["CategoryList"].Split(',');

I hope this tip is useful to others that are testing the MVC Framework.

ASP.NET MVC: DropDownList

Here is an example of how to use the Html.DropDownList helper method available in the MVC framework to generate a combo in you page.

Let’s use the Northwind example and say that you want to create a product and in the product for you need to select a category to which this product belongs in a dropdownlist.

The first step is in the select the list of categories in the appropriate controller action. In my case I’m going to use the new Action.

public ActionResult New()
{
    ViewData["CatList"] = new SelectList(_db.Categories.ToList(), "CategoryID", "CategoryName");
    return View();
}

Notice that I used the SelectList class. In this case I used the constructor that takes 3 parameters:

  1. The list of categories I got from my Linq DataContext
  2. The name of the property of the Category class that has the ID value that is going to be stored in the select list and which will be the value that actually is passed to the Product class
  3. The name of the property of the Category class that has the value I want to display to the user

The SelectList class will be used by the DropDownList helper to generate the html code. Here is part of the View code:

...
<tr>
       <td>Category:</td>
       <td><%= Html.DropDownList("CategoryID",(SelectList)ViewData["CatList"]) %></td>
</tr>
...

 

Where is the RenderPartial method?

I was coding an demo application using the ASP.NET MVC Beta 1 and all the sudden I couldn’t access the RenderPartial method of the HtmlHelper from a Helper method I was writing. So where did it go?

I noticed that in the previous release the RenderPartial was a static method but in the Beta 1 they changed it to an Extension Method for the and it now lives in the namespace ’’‘System.Web.Mvc.Html’’’. So if you want to use this method all you need is to import this namespace in the classes where you are using the System.Web.Mvc.HtmlHelper class. In the Views you will notice that it keeps working as if nothing changed, that’s why the MVC’s development team has already added the System.Web.Mvc.Html namespace in the web.config. Here is the namespace node of the web.config the in MVC Beta 1.

<namespaces>
   <add namespace="System.Web.Mvc"/>
   <add namespace="System.Web.Mvc.Ajax"/>
   <add namespace="System.Web.Mvc.Html"/>
   <add namespace="System.Web.Routing"/>
   <add namespace="System.Linq"/>
   <add namespace="System.Collections.Generic"/>
 </namespaces>

 

Extension Methods

Extension methods are one of my favorite features of C# 3.0, they allow you to create new methods and plug them in classes already defined without having to derive them or even change it’s source code.

Everyone uses the DateTime class and a lot of those people have a class with handy methods to handle DateTime. Many of the handy methods would look better in the DateTime class but you can’t change it’s source code and you don’t want to derive from it and create a new DateTime class (of course). With extension methods you can plug these new methods in the DateTime class.

Let’s create a simple method named ’’‘DaysSince” that operates on two dates returning the number of days from one date to the other. The logic of the method is really simple:

    public static class DateUtil
    {
        public static int DaysSince(DateTime d1, DateTime d2)
        {
            TimeSpan ts = d1.Subtract(d2);
            return ts.Days;
        }
    }

You would use this class like this:

DateTime today = DateTime.Now;
DateTime pastDate = new DateTime(2008, 10, 9);
Console.WriteLine(DateUtil.DaysSince(today, pastDate);

My goal now is to be able to do this:

DateTime today = DateTime.Now;
DateTime pastDate = new DateTime(2008, 10, 9);
Console.WriteLine(today.DaysSince(pastDate));

To make this change just put a ’’‘this’’’ keyword in front of the first parameter of the static method. Now it should be like this:

public static class DateUtil
{
    public static int DaysSince(this DateTime d1, DateTime d2)
    {
        TimeSpan ts = d1.Subtract(d2);
        return ts.Days;
    }
}

That is it, you can now make a call to the DaysSince method from any DateTime instance variable.

Here a the rules for creating a ExtensionMethod:

  1. Create a public static class (you call call it anything you want)
  2. Create the method you want as a public static method
  3. The first parameter of the method must always the a ’’‘this’’’ keyword followed by the class you want to plug the method to and the name of the parameter
  4. Whenever you want to use the extension method the ’’‘namespace’’’ in which the class is into must be referenced

If you want to create a method ’’‘WeeksAgo’’’ that let you get a new DateTime x weeks before the a certain date all you need to do is this:

public static class DateUtil
{
    public static int DaysSince(this DateTime d1, DateTime d2)
    {
        TimeSpan ts = d1.Subtract(d2);
        return ts.Days;
    }
    public static DateTime WeeksAgo(this DateTime d1, int numberOfWeeks)
    {
        DateTime newDate = d1.AddDays(-numberOfWeeks * 7);
        return newDate;
    }
}

And then you can use it like this:

Console.WriteLine(today.WeeksAgo(2).ToString());

Really cool addition to your utility belt, isn’t it?

C# Custom Type Conversions

C# allows for implicit and explicit type conversion between classes when there is an inheritance situation. Something like this:

class BaseClass { }

    class DerivedFromBaseClass : BaseClass { }

    class Program
    {
        static void Main(string[] args)
        {
            BaseClass bc = new DerivedFromBaseClass(); //implicit conversion

            DerivedFromBaseClass dbc = (DerivedFromBaseClass)bc; //explicit conversion
        }
    }

Ok, this shouldn’t be anything new to know since this is a feature present in all object oriented languages I know. But now I want to talk about a stranger kind of conversion and for this I’ll have to mix apples and oranges.

Let’s define to classes: Apple and Orange.

class Apple
    {
        public string Farm { get; set; }

        public Apple(string farm)
        {
            this.Farm = farm;
        }

        public override string ToString()
        {
            return string.Format("I'm an apple from the {0} farm", this.Farm);
        }

    }

    class Orange
    {
        public string Farm { get; set; }

        public Orange(string farm)
        {
            this.Farm = farm;
        }

        public override string ToString()
        {
            return string.Format("I'm an orange from the {0} farm", this.Farm);
        }
    }

As you can see these two classes are totally unrelated, they don’t have any inheritance relation with each other.

Let’s convert Apples to Oranges using the cast-like sintax. This is possible using the keywords ’’‘operator’’’, ’’‘explicit’’’ in a static method that will do the conversion. Here are the changes to the Apple class so that it can be converted explicitly to an Orange.

class Apple
    {
        public string Farm { get; set; }

        public Apple(string farm)
        {
            this.Farm = farm;
        }

        public override string ToString()
        {
            return string.Format("I'm an apple from the {0} farm", this.Farm);
        }

        public static explicit operator Apple(Orange o)
        {
            Apple a = new Apple(o.Farm);
            return a;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Orange o = new Orange("GreatSouth");
            Console.WriteLine(o.ToString());

            Apple a = (Apple)o; //explicit conversion
            Console.WriteLine(a.ToString());
        }
    }

Ok, it works. You can also do an implicit conversion but in this case you must be aware that it will also create (automatically) the explicit conversion. This is why you can’t define both these conversions in the same class. Following is the changes necessary to the Orange class so that you can make implicit and explicit conversions from Apples to Oranges:

class Orange
    {
        public string Farm { get; set; }

        public Orange(string farm)
        {
            this.Farm = farm;
        }

        public override string ToString()
        {
            return string.Format("I'm an orange from the {0} farm", this.Farm);
        }

        //this will allow implicit and explicit conversion
        public static implicit operator Orange(Apple a)
        {
            Orange o = new Orange(a.Farm);
            return o;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Apple a = new Apple("GreatSouth");
            Console.WriteLine(a.ToString());

            Orange o = a; //implicit
            Console.WriteLine(o.ToString());

            //or you could do it like this
            o = (Orange)a; //explicit
            Console.WriteLine(o.ToString());
        }
    }

I hope you found this interesting. Once again a know that my examples are not always the most thought out but I’m certain that you got the idea and will be able to put it work in a real life situation.

Set the Default Database in SQL Management Studio

Hi, this one is for the lazy programmers (like I). If you work a lot of time on the same project chances are that you know that every time you create a new query on SQL Server Management Studio it always sets your connection to the Master database. For those who are annoyed like me, you can configure the default database of your user to whatever you want.

  1. On the Object Explorer expand the Security folder.
  2. Expand the Logins folder.
  3. Right click your user and select Properties.
  4. Now select the Default Database you want.

That’s it!

Understanding how yield keyword works

If you work with C# you must know that in order to traverse a collection using the ‘foreach’ construct the collection must implement the IEnumerable interface. There’s a lot of documentation about that on the web so I won’t go into it. What I’d like to show you is an alternative to the IEnumerable interface using the ‘yield’ keyword. Take a look at this code:

public class Player
    {
        public string Name { get; set; }

        public Player(string name)
        {
            this.Name = name;
        }
    }

    public class Team
    {
        Player[] players = new Player[3];

        public Team()
        {
            players[0] = new Player("Gabriel");
            players[1] = new Player("Elisa");
            players[2] = new Player("Rafaela");
        }

        public IEnumerator GetEnumerator()
        {
            foreach (Player player in players)
            {
                yield return player;
            }
        }
    }

You can now test the code in a foreach like this:

 public static void TestYield()
        {
            Team team = new Team();
            foreach (Player player in team)
            {
                Console.WriteLine(player.Name);
            }
        }

This is really interesting, right? But how does it work? Shouldn’t the iteration through the players array start from scratch every time you call the method? Nope! This is where the magic of the yield comes in. Every time the yield is executed it will “pause the state” of the iteration and the next time the method is called it will resume the iteration from the next item. I could even rewrite my code in the following way and it would have the same effect:

public IEnumerator GetEnumerator()
        {
            yield return players[0];
            yield return players[1];
            yield return players[2];
        }

This code is only for demonstration purposes, I know that iterating the array like this wouldn’t be very smart :-) I just wanted to show you that the execution will pause.

This woks because in compile time the method using the yield will be transformed into a class which implements the IEnumerator interace and it’s stated will be maintained like any other object, that is why you get the impression the method is paused. It’s cool to understand how these things work under the hood, isn’t it?

MaskEditExtender causes problem with TextChanged event

Have you ever used the Ajax ControlToolkit MaskedEdit control? Last week I found an unexpected behavior with it.

Page:

<form id="form1" runat="server">
    <div>
    <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>

        <asp:TextBox ID="TextBox1" runat="server" ontextchanged="TextBox1_TextChanged"></asp:TextBox>
        <cc1:MaskedEditExtender ID="TextBox1_MaskedEditExtender" runat="server" 
            CultureAMPMPlaceholder="" CultureCurrencySymbolPlaceholder="" 
            CultureDateFormat="" CultureDatePlaceholder="" CultureDecimalPlaceholder="" 
            CultureThousandsPlaceholder="" CultureTimePlaceholder="" Enabled="True" 
            Mask="99-99-99" TargetControlID="TextBox1" ClearMaskOnLostFocus="False" 
            MaskType="Number">
        </cc1:MaskedEditExtender>
        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />

        <asp:Button ID="Button2" runat="server" onclick="Button2_Click" Text="Button" />

    </div>
    </form>

CodeBehind:

 protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void TextBox1_TextChanged(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            TextBox1.Text = "101208";
        }

        protected void Button2_Click(object sender, EventArgs e)
        {

        }

This page has one edit with a MaskEditExtender and two buttons. On the first button click I change the value of the TextBox. On the second button click I do nothing. If I click the first button then the second, the TextChanged event of the edit will fire. Funny, right? Here is the reason.

Let’s say you have a mask like this: 99-99-99. To apply the value to the textbox you do:


TextBox1.Text = "101208";

The resulting value on the web page will be: 10-12-08. Here is the catch: The mask is applied to the textbox only after the page is rendered using JavaScript. So the value for the control in the ViewState is 101208 and the value in the page is 10-12-08. When another postback occurs the framwork will detect that the value in the page is different from the value in the ViewState therefore it fires the TextChanged event when in fact the value hasn’t changed.

You can avoid this behavior by setting the value to the TextBox already with masked value.


TextBox1.Text = "10-12-08";

I hope this can help someone out there.

Set a property of a server tag dynamically

Setting a property of a server tag is pretty standard stuff:


<asp:TextBox ID="TextBox1" runat="server" Text="My name is Gabriel" />

Now, what if you want to use a class to set the value?


<asp:TextBox ID="TextBox1" runat="server" Text='<%= DateTime.Now %>' />

This will give you an error like this:

Server tags cannot contain <% ... %> constructs

If you ever need to solve this kind of problem I found a very interesting solution in the Infinites Loop Blog

It’s a very clever solution to use the Expression Builders, introduced in the Asp.Net 2.0 feature, to let you execute your custom code within the server tags.

LINQ: OrderBy with nullable columns in TypedDataSets

This article shows a tip on how you can do sorting using the LINQ OrderBy with Typed DataSets. For our example I’ll use the the Northwind Database and it’s Customers table. I’ll use two columns in this table. One is the ContactName which doesn’t have any null values and the Region column which has null values.

First lets populate the DataTable we want to query using TableAdapter I had previously generated in the DataSet.

CustomersTableAdapter ta = new CustomersTableAdapter();
DataSetNorthwind.CustomersDataTable dt = ta.GetData();

I want to use LINQ select all values ordering them by the Region column (which may be null). So here is the initial idea:

 var query = from r in dt.AsEnumerable()
                        orderby r.Region
                        select r;

Ok, no compilation errors but when you run the query you will get an error:

The value for column ‘Region’ in table ‘Customers’ is DBNull. -> System.InvalidCastException: ...

If you think about it this is expected. The nullable columns in the DataSet all have an IsNull method to check if the column is null or not and avoid this kind of error. We are going to use the IsRegionNull() method in our favor to help us solve the problem:

var query = from r in dt.AsEnumerable()
        orderby (r.IsRegionNull() ? "" : r.Region)
        select r;

I used the ternary operator to check if the column region is null or not. If it is then I’ll use an empty string as the value, if it’s not null I can call the Region property to get the value.

To see the ending result you can print all the values:

foreach (DataSetNorthwind.CustomersRow row in query)
{
     Console.WriteLine("{0} - {1}", row.ContactName, 
          row.IsRegionNull() ? "" : row.Region);
}

Of course you could have filtered out the rows with null regions, but the goal here is to show what you can do to order the rows when you have a column with values that may be null.

Get the number of business days between two dates

Here’s a simple way of getting the number of business days between two dates using C#.

DateTime dtBegin = new DateTime(2008, 8, 6);
            DateTime dtEnd = new DateTime(2008, 8, 13);

            int dayCount = 0;

            //while the End date is not reached
            while (dtEnd.CompareTo(dtBegin) > 0)
            {
                //check if the day is not a weekend day
                if ((dtBegin.DayOfWeek != DayOfWeek.Saturday) && (dtBegin.DayOfWeek != DayOfWeek.Sunday))
                {
                    dayCount++;
                }
                //go to next day
                dtBegin = dtBegin.AddDays(1);
            }

You can enhance this method consulting a list of holidays to check if the current date is indeed a business day. For this you have to have the list of holidays somewhere. In our example I’ll create a fake method that will provide the holidays list.

public static void CalculateNumberOfWeekdays()
        {
            DateTime dtBegin = new DateTime(2008, 8, 6);
            DateTime dtEnd = new DateTime(2008, 8, 13);
            List<DateTime> holidays = GetHolidays();

            int dayCount = 0;

            //while the End date is not reached
            while (dtEnd.CompareTo(dtBegin) > 0)
            {
                //check if the day is not a weekend day
                if ((dtBegin.DayOfWeek != DayOfWeek.Saturday) 
                    && (dtBegin.DayOfWeek != DayOfWeek.Sunday)
                    && (!holidays.Contains(dtBegin)))
                {
                    dayCount++;
                }
                //go to next day
                dtBegin = dtBegin.AddDays(1);
            }
            Console.WriteLine(dayCount);
        }

        public static List<DateTime> GetHolidays()
        {
            List<DateTime> holidays = new List<DateTime>();
            holidays.Add(new DateTime(2008, 8, 7));
            return holidays;
        }            

See you next time.

Asp.Net: UpdatePanel concurrent requests

Yesterday I was coding the infrastructure to start a thread in the server that would take too long to finish and would timeout the browser. The idea is that you could start a thread to run your long operation and let the server return the response to the browser. In order to give some feedback to the user I would query the server from time to time to check on the progress of the operation.

Everything was going great but then someone said the client wanted to be able to cancel the task running on the server. At first though it would not mess up what I had done already. The thing is that if the server was already querying the status of the task and I tried to cancel at the same time I would get an error.

Long story short, you have problem when the UpdatePanel makes multiple requests concurrently. When you do this the last request being executed wins. I looked around and found an interesting solution to this problem.

http://geekswithblogs.net/rashid/archive/2007/08/08/Asp.net-Ajax-UpdatePanel-Simultaneous-Update—-A-Remedy.aspx

What this guy did was to intercept the asyn requests and enqueue them so they are only done one at a time. Of all the things I found on the Internet this was the most interesting solution.

There is also an interesting solution in the Asp.Net site that allows you to define on among several UpdatePanel that gets precedence over the others. So, if one request is being executed and the preferred UpdatePanel trying to execute the other one is canceled. See it here

Add Controls Dynamically - Part 4

The part 3 of this series was getting a bit long for my taste so I decided to break it in 2. Here we’ll continue dealing with the controls added dynamically to our page only now we’re going to access them by ID.

Related posts:

Naming the controls

By now you have noticed that we haven’t explicitly set the ID of any of our controls. Of course the controls have ID’s but they are defined automatically by the Asp.Net framework when the controls are instantiated. The reason this works is because the framework will create the names consistently the same, again and again as long as you create the controls always in the same order (we are doing that).

It is this automatically naming feature that allows our components to keep their state between requests. When the page is submitted all of the controls states are sent back from the browser to the server, but the server doesn’t know how to create the controls that’s why we had to do it every time the page is submitted. After the control has been created the Asp.Net framework is able to get it’s state from the page based on it’s name.

Ok, enough theory. Let’s give our controls and ID manually. Since the controls are added dynamically the ID’s have to be something that can be predicted. Let’s say: TextBox + a number. For this will change the createDynamicControls method to add a parameter which will be the number of the control added.

//this method takes care of creating the controls
    private void createDynamicControls(int count)
    {
        TextBox tb = new TextBox();
        tb.TextChanged += TextBox_TextChanged;
        //now we set the control ID manually
        tb.ID = "TextBox" + count;
        PlaceHolder1.Controls.Add(tb);
        controlsList.Add(tb);
    }

When the add control button is clicked we need to pass the number to the method. We can use the control count that we’re storing in the ViewState.

protected void Button1_Click(object sender, EventArgs e)
    {
        createDynamicControls((int)ViewState["count"]);
        //increment the number of controls
        ViewState["count"] = (int)ViewState["count"] + 1;
    }

Another place we need to change is the Page_Load event when the controls are re-created. Here for loop when we pass in the new parameter:

for (int i = 0; i < controlCount; i++)
            {
                //notice that now we pass the i as parameter
                createDynamicControls(i);
            }

To test our new functionality we will add TextBox, a Button and a Label. We are going to inform the ID of the TextBox we want to get the value for. When the button is clicked the event will get the control and display it’s value in the label.

<asp:TextBox ID="TextBoxControlId" runat="server"></asp:TextBox>
        <asp:button ID="ButtonGetValue" runat="server" text="Get value" 
            onclick="ButtonGetValue_Click" />
        Valor: <asp:Label ID="LabelValue" runat="server" Text=""></asp:Label>

And here is the event where we get the TextBox we want:

protected void ButtonGetValue_Click(object sender, EventArgs e)
    {
        //find the control we want using the name informed by the user in the 
        //TextBoxControlId control
        TextBox tb = (TextBox)PlaceHolder1.FindControl(TextBoxControlId.Text);
        LabelValue.Text = tb.Text;
    }

Now if you add 3 TextBoxes (which will have id’s TextBox0, TextBox1 and TextBox2) and you input TextBox0 in the interface and hit the button the LabelValue control will show the value in the first TextBox.

This one was a bit longer than I would like to so I’ll try to make the next article shorter.

Here is the final version of our page after all of our modifications:

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

    System.Collections.Generic.List<TextBox> controlsList = new System.Collections.Generic.List<TextBox>();

    void Page_Load(object sender, EventArgs e)
    {
        //when the user first enters the page set the count as zero
        if (!IsPostBack)
        {
            ViewState["count"] = 0;
        }
        //on every subsequent postback, check the control count
        //and recreated all the controls
        else
        {
            int controlCount = (int)ViewState["count"];
            for (int i = 0; i < controlCount; i++)
            {
                //notice that now we pass the i as parameter
                createDynamicControls(i);
            }
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        createDynamicControls((int)ViewState["count"]);
        //increment the number of controls
        ViewState["count"] = (int)ViewState["count"] + 1;
    }

    //this method takes care of creating the controls
    private void createDynamicControls(int count)
    {
        TextBox tb = new TextBox();
        tb.TextChanged += TextBox_TextChanged;
        //now we set the control ID manually
        tb.ID = "TextBox" + count;
        PlaceHolder1.Controls.Add(tb);
        controlsList.Add(tb);
    }

    private void TextBox_TextChanged(object sender, EventArgs e)
    {
        //the sender is the control that fired the event
        //that is the control we want to change the color
        TextBox tb = (TextBox)sender;
        tb.BackColor = System.Drawing.Color.Yellow ;
    }

    protected void ButtonAdd_Click(object sender, EventArgs e)
    {
        int value = 0;
        foreach (TextBox tb in controlsList)
        {
            value += int.Parse(tb.Text);
        }
        LabelTotal.Text = value.ToString();
    }

    protected void ButtonGetValue_Click(object sender, EventArgs e)
    {
        //find the control we want using the name informed by the user in the 
        //TextBoxControlId control
        TextBox tb = (TextBox)PlaceHolder1.FindControl(TextBoxControlId.Text);
        LabelValue.Text = tb.Text;
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
        <br />
        <asp:Button ID="Button1" runat="server" Text="Add TextBox" 
            onclick="Button1_Click" />
        <br />
        <asp:Button ID="ButtonAdd" runat="server" Text="Add all values" 
            onclick="ButtonAdd_Click" />
        <br />
        Total:<asp:Label ID="LabelTotal" runat="server" Text=""></asp:Label>
        <br />
        <br />
        <asp:TextBox ID="TextBoxControlId" runat="server"></asp:TextBox>
        <asp:button ID="ButtonGetValue" runat="server" text="Get value" 
            onclick="ButtonGetValue_Click" />
        Value: <asp:Label ID="LabelValue" runat="server" Text=""></asp:Label>
    </div>
    </form>
</body>
</html>

See you next time.

Add Controls Dynamically - Part 5

In parts 1 to 4 I have talked about creating dynamic controls and adding them to the page. I haven’t talked about a important aspect of Asp.Net that is very important for any developers and specially if you are dealing with dynamic controls. So in this article I’m going to talk about the Asp.Net Life cycle.

Related posts:

Asp.Net Life Cycle

As I said in previous articles the state of the page or any of it’s components is not stored on the sever. Everything is stored on the page. This is due to the characteristics of HTTP protocol which is stateless. Having this in mind, every time there is a postback the structure of the page is recreated so that you can have access to the controls through code. I’m not sure if I made myself clear so here another way to put it:

HTML is HTML and that is it. When you look at the page in the browser all there is is HTML, there is no C# or VB.Net. Only when the page is submitted to the server is that the HTML is going to be read transformed in server side controls. The programmer then uses these server side controls to manipulate the controls. At the end this controls will render HTML again which will be sent to the page.

Ok, so why is this important? Well, the process of creating the server side code from the HTML happens in several stages which fire events that let you interact with the components in the right moment.

The life cycle has a lot of stages but the ones we are interested in are the Initialization and Load. For more details on all stages check out MSDN

Initialization

In this stage the controls available on the page (not the ones created dynamically) become available. The ViewState has not been retrieved however and therefore the control values cannot be loaded in the controls. The postback data is also not available at this stage.

The Load stage has three events to help the programmer:

  1. PreInit
  2. Init
  3. InitComplete

In the PreInit event the controls don’t even exist yet. They have not been created.

If you set a property like the Text of a TextBox in these events this value will be lost in future stages when the control is loaded. If you want to use these events you need to declare the following methods in your code:

void Page_PreInit(object sender, EventArgs e)
    {

    }

    void Page_Init(object sender, EventArgs e)
    {

    }

    void Page_InitComplete(object sender, EventArgs e)
    {

    }

Load

This is an important stage for us because it is here that the values of the controls are loaded. Before this stage you might have the controls but it’s values have are not there yet.

The Load stage has three events to help the programmer:

  1. PreLoad
  2. Load
  3. LoadComplete

We have used the Page_Load event in our previous examples to create our dynamically created controls. The thing to watch is that when these controls are created they don’t have it’s values from the page loaded yet. If you want to get the values from the controls you can only do it in the Page_LoadComplete event. Only then all the values of the controls will be loaded.

You can test this using creating the method for each of these events and using the debugger to check the controls we the event is hit.

void Page_PreLoad(object sender, EventArgs e)
    {

    }

    void Page_Load(object sender, EventArgs e)
    {
        //when the user first enters the page set the count as zero
        if (!IsPostBack)
        {
            ViewState["count"] = 0;
        }
        //on every subsequent postback, check the control count
        //and recreated all the controls
        else
        {
            int controlCount = (int)ViewState["count"];
            for (int i = 0; i < controlCount; i++)
            {
                //notice that now we pass the i as parameter
                createDynamicControls(i);
            }
        }
    }

    void Page_LoadComplete(object sender, EventArgs e)
    {

    }

Notice that I have used the Load event defined in the previous articles but the methods for the other events are new. If you set a breakpoint and use the Watch to inspect the controls you can see when the values have been loaded.

Ok, so if you need to create the controls you do it where we’ve been doing up to now: In the Page_Load

If you need to get the values from these controls right after you loaded them you need to wait for the Page_LoadComplete event.

Well, I hope this info was useful.

Add Controls Dynamically - Part 4

The part 3 of this series was getting a bit long for my taste so I decided to break it in 2. Here we’ll continue dealing with the controls added dynamically to our page only now we’re going to access them by ID.

Related posts:

Naming the controls

By now you have noticed that we haven’t explicitly set the ID of any of our controls. Of course the controls have ID’s but they are defined automatically by the Asp.Net framework when the controls are instantiated. The reason this works is because the framework will create the names consistently the same, again and again as long as you create the controls always in the same order (we are doing that).

It is this automatically naming feature that allows our components to keep their state between requests. When the page is submitted all of the controls states are sent back from the browser to the server, but the server doesn’t know how to create the controls that’s why we had to do it every time the page is submitted. After the control has been created the Asp.Net framework is able to get it’s state from the page based on it’s name.

Ok, enough theory. Let’s give our controls and ID manually. Since the controls are added dynamically the ID’s have to be something that can be predicted. Let’s say: TextBox + a number. For this will change the createDynamicControls method to add a parameter which will be the number of the control added.

//this method takes care of creating the controls
    private void createDynamicControls(int count)
    {
        TextBox tb = new TextBox();
        tb.TextChanged += TextBox_TextChanged;
        //now we set the control ID manually
        tb.ID = "TextBox" + count;
        PlaceHolder1.Controls.Add(tb);
        controlsList.Add(tb);
    }

When the add control button is clicked we need to pass the number to the method. We can use the control count that we’re storing in the ViewState.

protected void Button1_Click(object sender, EventArgs e)
    {
        createDynamicControls((int)ViewState["count"]);
        //increment the number of controls
        ViewState["count"] = (int)ViewState["count"] + 1;
    }

Another place we need to change is the Page_Load event when the controls are re-created. Here for loop when we pass in the new parameter:

 for (int i = 0; i < controlCount; i++)
            {
                //notice that now we pass the i as parameter
                createDynamicControls(i);
            }

To test our new functionality we will add TextBox, a Button and a Label. We are going to inform the ID of the TextBox we want to get the value for. When the button is clicked the event will get the control and display it’s value in the label.

<asp:TextBox ID="TextBoxControlId" runat="server"></asp:TextBox>
        <asp:button ID="ButtonGetValue" runat="server" text="Get value" 
            onclick="ButtonGetValue_Click" />
        Valor: <asp:Label ID="LabelValue" runat="server" Text=""></asp:Label>

And here is the event where we get the TextBox we want:

protected void ButtonGetValue_Click(object sender, EventArgs e)
    {
        //find the control we want using the name informed by the user in the 
        //TextBoxControlId control
        TextBox tb = (TextBox)PlaceHolder1.FindControl(TextBoxControlId.Text);
        LabelValue.Text = tb.Text;
    }

Now if you add 3 TextBoxes (which will have id’s TextBox0, TextBox1 and TextBox2) and you input TextBox0 in the interface and hit the button the LabelValue control will show the value in the first TextBox.

This one was a bit longer than I would like to so I’ll try to make the next article shorter.

Here is the final version of our page after all of our modifications:

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

    System.Collections.Generic.List<TextBox> controlsList = new System.Collections.Generic.List<TextBox>();

    void Page_Load(object sender, EventArgs e)
    {
        //when the user first enters the page set the count as zero
        if (!IsPostBack)
        {
            ViewState["count"] = 0;
        }
        //on every subsequent postback, check the control count
        //and recreated all the controls
        else
        {
            int controlCount = (int)ViewState["count"];
            for (int i = 0; i < controlCount; i++)
            {
                //notice that now we pass the i as parameter
                createDynamicControls(i);
            }
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        createDynamicControls((int)ViewState["count"]);
        //increment the number of controls
        ViewState["count"] = (int)ViewState["count"] + 1;
    }

    //this method takes care of creating the controls
    private void createDynamicControls(int count)
    {
        TextBox tb = new TextBox();
        tb.TextChanged += TextBox_TextChanged;
        //now we set the control ID manually
        tb.ID = "TextBox" + count;
        PlaceHolder1.Controls.Add(tb);
        controlsList.Add(tb);
    }

    private void TextBox_TextChanged(object sender, EventArgs e)
    {
        //the sender is the control that fired the event
        //that is the control we want to change the color
        TextBox tb = (TextBox)sender;
        tb.BackColor = System.Drawing.Color.Yellow ;
    }

    protected void ButtonAdd_Click(object sender, EventArgs e)
    {
        int value = 0;
        foreach (TextBox tb in controlsList)
        {
            value += int.Parse(tb.Text);
        }
        LabelTotal.Text = value.ToString();
    }

    protected void ButtonGetValue_Click(object sender, EventArgs e)
    {
        //find the control we want using the name informed by the user in the 
        //TextBoxControlId control
        TextBox tb = (TextBox)PlaceHolder1.FindControl(TextBoxControlId.Text);
        LabelValue.Text = tb.Text;
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
        <br />
        <asp:Button ID="Button1" runat="server" Text="Add TextBox" 
            onclick="Button1_Click" />
        <br />
        <asp:Button ID="ButtonAdd" runat="server" Text="Add all values" 
            onclick="ButtonAdd_Click" />
        <br />
        Total:<asp:Label ID="LabelTotal" runat="server" Text=""></asp:Label>
        <br />
        <br />
        <asp:TextBox ID="TextBoxControlId" runat="server"></asp:TextBox>
        <asp:button ID="ButtonGetValue" runat="server" text="Get value" 
            onclick="ButtonGetValue_Click" />
        Value: <asp:Label ID="LabelValue" runat="server" Text=""></asp:Label>
    </div>
    </form>
</body>
</html>

See you next time.

Add Controls Dynamically - Part 3

On the last article of this series we saw how we could assign event handlers to dynamically created controls and how the PlaceHolder control could help us add the controls in a more organized way.

Related posts:

In this article I want to show how you can keep a reference of a dynamically created control so that you can use it later somewhere else in your code. For this I’ll continue using the code created add the end of the last article of this series.

Now that you can add as many TextBoxes to the form as you want let’s say that you want to use them to input numeric values and then add up all the values for display. The first thing then is to decide where do we want to keep the reference to the controls. I chose to use a generic list of TextBox (List) but you could have chosen another structure that you feel more comfortable with.

System.Collections.Generic.List<TextBox> controlsList = new System.Collections.Generic.List<TextBox>();

Now that the list is declared and created the next step is deciding when we are going to add the controls to the list. To me using the method that adds the controls dynamically feels like the best choice, maybe someone has another idea (please share if you do). So the method would look like this:

 private void createDynamicControls()
    {
        TextBox tb = new TextBox();
        tb.TextChanged += TextBox_TextChanged;
        PlaceHolder1.Controls.Add(tb);
        controlsList.Add(tb);
    }

Easy, right? Ok, the last step now is adding a button to the form that will call the logic to add the values within all the controls and add a label that will display the result of the addition. The logic for adding the values is very simple, once you have a list with all the controls you only need to iterate through the list, get the value of the control and add it to a variable. Here is the code:

 protected void ButtonAdd_Click(object sender, EventArgs e)
    {
        int value = 0;
        foreach (TextBox tb in controlsList)
        {
            value += int.Parse(tb.Text);
        }
        LabelTotal.Text = value.ToString();
    }

Please notice that I have assumed that all the TextBoxes are provided with valid numeric values. We could improve the code to check for empty values and conversion errors however this is not the main goal of this article. Here is a complete version of the page after all our changes were made:

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

    System.Collections.Generic.List<TextBox> controlsList = new System.Collections.Generic.List<TextBox>();

    void Page_Load(object sender, EventArgs e)
    {
        //when the user first enters the page set the count as zero
        if (!IsPostBack)
        {
            ViewState["count"] = 0;
        }
        //on every subsequent postback, check the control count
        //and recreated all the controls
        else
        {
            int controlCount = (int)ViewState["count"];
            for (int i = 0; i < controlCount; i++)
            {
                createDynamicControls();
            }
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        createDynamicControls();
        //increment the number of controls
        ViewState["count"] = (int)ViewState["count"] + 1;        
    }

    //this method takes care of creating the controls

    private void createDynamicControls()
    {
        TextBox tb = new TextBox();
        tb.TextChanged += TextBox_TextChanged;
        PlaceHolder1.Controls.Add(tb);
        controlsList.Add(tb);
    }

    private void TextBox_TextChanged(object sender, EventArgs e)
    {
        //the sender is the control that fired the event
        //that is the control we want to change the color
        TextBox tb = (TextBox)sender;
        tb.BackColor = System.Drawing.Color.Yellow ;
    }

    protected void ButtonAdd_Click(object sender, EventArgs e)
    {
        int value = 0;
        foreach (TextBox tb in controlsList)
        {
            value += int.Parse(tb.Text);
        }
        LabelTotal.Text = value.ToString();
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
        <br />
        <asp:Button ID="Button1" runat="server" Text="Add TextBox" 
            onclick="Button1_Click" />
        <br />
        <asp:Button ID="ButtonAdd" runat="server" Text="Add all values" 
            onclick="ButtonAdd_Click" />
        <br />
        Total:<asp:Label ID="LabelTotal" runat="server" Text=""></asp:Label>
    </div>
    </form>
</body>
</html>

 

Visual Studio 2008: WebForms Designer Annoyingly Slow

Lately one of the developers of my team had been complaining that the WebForms designer was very slow. Editing properties of controls was taking forever and switch from code view to design view was a test to his patience. He was the only one in the team having this problem but it didn’t take very long for me to find out that Microsoft has published a hotfix to deal with this issue among others.

If your Visual Studio is really slow take a look at the Visual Web Developer Team Blogfor the full list of issues addressed and the download link.

Design Pattern: Singleton

This is the first post on a series about Design Patterns using C#. I will not publish all the articles in a sequence but you can expect from time to time to have a new post about some pattern.

The first pattern I want to talk about is the Singleton.

Objective

You need a singleton when your application require one and only one instance of a single class and also that this instance can be accessed whenever necessary.

Case Scenario

Imagine that you want a Logger class that will store all messages in a internal list. You need the hold the all the messages in a single place. If you had more than one instance of a Logger class you would have the messages scattered over the various instances. To avoid this will use a singleton.

The Solution

We are going to create a Logger class in our example.

The first issue the singleton should handle is how to prevent users from creating multiple instances of a class. To achieve this you have to block (hide) the constructor. This can be done making it private.

private Logger() { }

Now the that the constructor is private how can you instantiate the class? You are right, you can’t do it from outside the class so we are going to do it from the inside. Since we need to keep the one instance we create we need a variable to hold it. We are going to declare this variable as static so that we don’t need the class to be instantiated in order to keep the value.

//this will hold our unique instance
private static Logger instance = null;

The next step is to come up with a way to create the only instance and at the same time gain Access to that instance. This can be done using a static method that will check the instance variable and if it is null it will create a new instance and return it, if it’s not null it will return the previously create instance.

public static Logger Instance()
        {
            //if the instance is null you have to instantiate it
            if (instance == null)
            {
                instance = new Logger();
            }
            return instance;
        }

This is all we need for our singleton but we still need to add the functionality for the Logger class. We need a list to store the messages, a method to add new messages and a method to print all the messages already stored. Here is the code for it:

//holds all the messages
        private List<string> messages = new List<string>();

        //add a new message to the Logger
        public void Log(string message)
        {
            messages.Add(message);
        }

        public void PrintAllMessages()
        {
            foreach (string message in messages)
            {
                Console.WriteLine(message);
            }
        }

Here is the code for the whole class:

public class Logger
    {
        private static Logger instance = null;

        private Logger() { }

        public static Logger Instance()
        {
            //if the instance is null you have to instantiate it
            if (instance == null)
            {
                instance = new Logger();
            }
            return instance;
        }

        //holds all the messages
        private List<string> messages = new List<string>();

        //add a new message to the Logger
        public void Log(string message)
        {
            messages.Add(message);
        }

        public void PrintAllMessages()
        {
            foreach (string message in messages)
            {
                Console.WriteLine(message);
            }
        }
    }

How to use it

Using the singleton is easy, the only difference from normal class use is that when you need an instance of the object you will not be able to call the constructor (it’s private now) so you need to request an instance through the Instance() method that we created.

In our usage examples I’ll declare two logger variables and pass different messages to each one. Since there’s only one instance both these variables will have references to the same object. This can be verified when you call the PrintAllMessages method of any of the loggers. You’ll notice that they will print all the messages that were passed to any of the variables.

Here is the code so you can test it at home:

 class Program
    {
        static void Main(string[] args)
        {
            Logger logger1 = Logger.Instance();
            Logger logger2 = Logger.Instance();

            logger1.Log("loading one");
            logger2.Log("loading two");

            logger1.Log("Success");
            logger2.Log("Failure");

            logger1.PrintAllMessages();
        }
    }

That’s it for the Singleton, I hope this is useful to someone somewhere :-)

 

Add Controls Dynamically - Part 2

This post continues what’s been done in the Part 1

On my last post I talked about creating controls dynamically in asp.net. In this post I’m going to continue with common issues or needs that users have based on what I noticed on the Asp.Net Forums

Related posts:

First I want to talk about assigning events to the controls that we are creating, this is a simple task but still and important topic.

Adding Events

The first thing we need to do is create a method that will be the handler for the event. When the event is fired on the control this is the method we want to be called to handle the event. In our example we are using TextBoxes so we want to handle the TextChanged event and make the background of the control yellow. Here is the method:

private void TextBox_TextChanged(object sender, EventArgs e)
    {
        //the sender is the control that fired the event
        //that is the control we want to change the color
        TextBox tb = (TextBox)sender;
        tb.BackColor = System.Drawing.Color.Yellow ;
    }

The name of the method is irrelevant but it’s return type and parameters are not. If you create an event through VisualStudio you’ll notice that the signature of the method is the same.

Now that we have the method we need to set this method as the handler for the event on the controls that we are creating. Adding the method to the controls handler is as simples as this:

tb.TextChanged += TextBox_TextChanged;

If you add your controls now all of them will have this handler and it’s background will turn yellow (after submit) if you change the content of the textbox.

PlaceHolder

Up until now we’ve been adding the controls directly to the Form. This will cause the controls to be added to the end of the page after all other controls. This is fine as an example but might not be you desired result. We will you the PlaceHolder control as a container to our controls, this way we can put the PlaceHolder wherever we want in the page and the controls will be added within it.

Another advantage of the PlaceHolder control is that it doesn’t generate any html, it’s just the to serve (as it’s own name says) as a place holder. So you don’t need to worry about adding extra html just to have a place to put your controls in.

In our example I will put the PlaceHolder before the button that we are using just to show that the controls will no longer be added to the end of the page.

The new page with the events and the PlaceHolder control will be like this:

<script runat="server">

    void Page_Load(object sender, EventArgs e)
    {
        //when the user first enters the page set the count as zero
        if (!IsPostBack)
        {
            ViewState["count"] = 0;
        }
        //on every subsequent postback, check the control count
        //and recreated all the controls
        else
        {
            int controlCount = (int)ViewState["count"];
            for (int i = 0; i < controlCount; i++)
            {
                createDynamicControls();
            }
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        createDynamicControls();
        //increment the number of controls
        ViewState["count"] = (int)ViewState["count"] + 1;        
    }

    //this method takes care of creating the controls
    private void createDynamicControls()
    {
        TextBox tb = new TextBox();
        tb.TextChanged += TextBox_TextChanged;
        PlaceHolder1.Controls.Add(tb);
    }

    private void TextBox_TextChanged(object sender, EventArgs e)
    {
        //the sender is the control that fired the event
        //that is the control we want to change the color
        TextBox tb = (TextBox)sender;
        tb.BackColor = System.Drawing.Color.Yellow ;
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
        <asp:Button ID="Button1" runat="server" Text="Add TextBox" 
            onclick="Button1_Click" />
    </div>
    </form>
</body>
</html>

Stay tuned for more about dynamically created controls.

Add Controls Dynamically

Dynamic controls are an interesting topic that keep showing up in the asp.net forums. I’ll try to explain the main points about creating and working with dynamically created controls in a few articles (this one would be too long otherwise).

First of all there are two points you need to understand:
  1. Adding the controls dynamically is easy, the tricky part is getting them to stick around.
  2. The controls are not kept between postbacks therefore you have to keep recreating them every time there is a postback.
  3. The best place to recreate the controls in the Page_Load or Page_Init events.

Creating a new control is easy, it’s just a matter of instantiate the class. Adding the control to the page is also easy you only need to add the new control to the page controls.

//create a new textbox
TextBox tb = new TextBox();
//add the new textbox to the page
Page.Form.Controls.Add(tb);

You’ve seen how easy it is to add the controls but if you don’t keep recreating them when you submit the page the dynamic controls will be gone.

First understand that this need to be recreated is not exclusive for dynamic created controls. Every time there is a postback the whole page is recreated. The difference is that all the controls that are declared in the aspx page are created automatically what gives the user the impression that the controls are always there (they are not!).

Since dynamically created controls are not hard coded anywhere (obviously) you are the one responsible for recreating them.

If you create a control in the Page_Load event you’ll notice that it works just like any control already in the aspx page:

<script runat="server">

    void Page_Load(object sender, EventArgs e)
    {
        TextBox tb = new TextBox();
        Page.Form.Controls.Add(tb);
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

    </div>
    </form>
</body>
</html>

Granted that if you could create the control like this you might declare it in the aspx page as well. Ok, so let’s improve our example and create a button that adds one and only one edit to the page. If the edit already exists the button won’t do any thing.

<script runat="server">

    void Page_Load(object sender, EventArgs e)
    {
        //means that the control has been created already so you 
        //need to recreate it
        if (ViewState["tb"] != null)
        {
            createDynamicControls();
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        //means the control has not been created yet
        //create the control and store the viewstate
        if (ViewState["tb"] == null)
        {
            createDynamicControls();
            ViewState["tb"] = true;
        }        
    }

    //this method takes care of creating the controls
    private void createDynamicControls()
    {
        TextBox tb = new TextBox();
        Page.Form.Controls.Add(tb);
    }

</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" Text="Add TextBox" 
            onclick="Button1_Click" />
    </div>
    </form>
</body>
</html>

Notice that in this version of the code I created a method responsible for creating the dynamic control. This will help to encapsulate the method creation and avoid duplicating code. Also notice that I’m using the ViewState to help maintain a variable that indicates if the control has been added yet in order to avoid duplication.

When the user clicks the button I check my ViewState variable to see if the TextBox has been created, if it hasn’t I create the TextBox, add it to the page and set the ViewState variable. Now, as long as you don’t leave the page the control and it’s state will be maintained.

We could also let the user add an undefined number of TextBoxes to the page making some small changes.

<script runat="server">

    void Page_Load(object sender, EventArgs e)
    {
        //when the user first enters the page set the count as zero
        if (!IsPostBack)
        {
            ViewState["count"] = 0;
        }
        //on every subsequent postback, check the control count
        //and recreated all the controls
        else
        {
            int controlCount = (int)ViewState["count"];
            for (int i = 0; i < controlCount; i++)
            {
                createDynamicControls();
            }
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        createDynamicControls();
        //increment the number of controls
        ViewState["count"] = (int)ViewState["count"] + 1;        
    }

    //this method takes care of creating the controls
    private void createDynamicControls()
    {
        TextBox tb = new TextBox();
        Page.Form.Controls.Add(tb);
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" Text="Add TextBox" 
            onclick="Button1_Click" />
    </div>
    </form>
</body>
</html>

Now you are able to add any number of controls keeping the state of them all. On my next post I’ll keep working with dynamic created controls so stay tuned.

Related posts:

Bind DropDownList to Enum

Unfortunately you can’t Databind an Enum to a DropDownList or to any control for that matter. You can however transform the Enum into something “bindable” like a HashTable.

First let’s define an Enum to use in our example:

public enum Cars
{
    Ford = 1,
    Kia = 2, 
    Mitsubishi = 3,
    Volkswagen = 4
}

Now that we have a method that will allow an enum to a HashTable all we need to do is bind the hash to the DropDownList.

//call our previously defined method to create the HashTable
        Hashtable ht = GetEnumForBind(typeof(Cars));

        //set the HashTable as the DataSource
        DropDownList1.DataSource = ht;
        //set the value of the Hash as the display
        DropDownList1.DataTextField = "value";
        //set the key of the Hash as the value
        DropDownList1.DataValueField = "key";

        DropDownList1.DataBind();

That is it, it should now bind without problems. There are alternate solutions that do not involve binding but instead adding each item of the enum to the DropDownList. You can take a look at the asp.net forums to see alternate solutions proposed by other members.

Access Asp.Net WebService from PHP Client

Creating and consuming webservices in asp.net is an easy task with the help of Visual Studio. Although most of the scenarios I worked with were always with asp.net applications consuming asp.net web services, which makes things even easier. This week however I learned something new when I had to get a PHP client application to connect to my asp.net webservices.

One of out clients was called saying that the service was not working. When I tested hisPHP client I noticed the the parameters that he was passing where not getting to my webservice even though the service was being called. The only problem then was passing the parameters. I Googled a little and got my own PHP client running.

For the sake of this post let’s say that our webservice gets an string as a parameters and returns the same value, this will let us test our code. So here is the asp.net webservice:

[WebService(Namespace = "http://tempuri.org/")]
public class Service : System.Web.Services.WebService
{

    [WebMethod]
    public string MyTestMethod(string myParameter)
    {
        return "The value of the parameter is: " + myParameter;
    }

}

As you can see there’s nothing to it.

The PHP code is not much harder once you Google a little. First you have to haveNuSoap Library which has the webservices infrastructure for PHP. You may put it in the same directory of your test page. Then you code a simple client to access our service:

<?php

    require_once('./nusoap.inc');

    $wsdl = "http://mysite/myapp/Service.asmx?wsdl";

    $mynamespace = "http://tempuri.org/";

    $theVariable = array('myParameter'=> 'gabriel');

    $s = new SoapClient($wsdl,true);

    $result = $s->call('MyTestMethod',$theVariable);

    echo "<h1>Resultado:</h1>";

    echo "<pre>"; print_r($result); print "</pre>";
?>

After I had the code I could verify for my self that my client was right. The parameters in the above code are not getting to the webservice. The coding is right, I checked in several sites in the Internet, so where could the problem be?

Well, SOAP specification allows for two formatting options: Style and Use. Style handles the formatting of the Body element of the envelope. Style allows for 2 values:
  1. RPC (Remote Procedure Call) which is the older format;
  2. Document which is a newer format and is VisualStudio default format.

By now I bet you have figured out the solution, right? If you said that PHP default encoding is RPC and asp.net default encoding is Document then you’re right on.

How to solve the problem? Well, you can solve the problem on both ends, it all depends on your choice. First let’s fix it on the asp.net side, it’s really simple. All you have to do is use the SoapRpcMethod attribute on WebMethod, like this:

[WebService(Namespace = "http://tempuri.org/")]
public class Service : System.Web.Services.WebService
{

    [SoapRpcMethod()]
    [WebMethod]
    public string MyTestMethod(string myParameter)
    {
        return "The value of the parameter is: " + myParameter;
    }

}

That’s it, the PHP client starts to work instantly.

This is a good solution if you only had PHP clients, since that was not my case I didn’t want to mess with my webservice and have to make changes to all other asp.net clients. I wanted to solve the problem on the PHP client, so let’s see how we could code the PHP client to fix the problem.

<?php

    require_once('./nusoap.inc');

    $wsdl = "http://mysite/myapp/Service.asmx?wsdl";

    $mynamespace = "http://tempuri.org/";

    $theVariable = array('myParameter'=> 'gabriel');

    $s = new SoapClient($wsdl,true);

    //here is the only change you need to do
    $result = $s->call('MyTestMethod',array('parameters' =>  $theVariable));

    echo "<h1>Resultado:</h1>";

    echo "<pre>"; print_r($result); print "</pre>";
?>

What I had to do in the PHP code was to add an extra array around the array with the original variables. This handles the difference in the Document encoding used by asp.net.

This problem really got on my nerves last week and I’m really glad to have found a solution. As usual I wanted to share this with the world and maybe avoid the same headache to others. Ohh, and I also got to learn a little php on the way…

Happy coding friends!

DataSet Designer (Editor) Missing

his week one of my co-workers had a strange problem with his VisualStudio 2008. All the sudden he couldn’t view the DataSet designer in any applications. When the DataSet file was clicked all that it showed was the XML file, no sign of the Designer.

We don’t know what happened but as I tried to figure out the problem I found that there’s very few information about this problem on the Internet, so I decide to blog about it so that it might help someone in distress.

If you’re having this problem you might first try to right click the DataSet file and then select the Open With… option. A list of editors will show, if you don’t see the DataSet Editor then you you have the same problem we did.

 

I have found a few posts about it, here are the solutions proposed:

  • Run the following command in the VisualStudio prompt: devenv /resetsettings
  • Run the following command in the VisualStudio prompt: devenv /setup
  • With Visual Studio setup disc select the Repair option.
  • Re-install Visual Studio.
All these are valid solutions and I found people on the web who claimed that this helped them but for my unfortunate teammate it didn’t help. The only thing that did it for us was:
  1. Remove VisualStudio
  2. Delete any folder left from VS installation
  3. Install VisualStudio

Finally, problem solved! I know this is not an optimal solution, far from it but at the end of the day it works. Nothing else did. I hope this post helps some else.

Problem with FormView inside UpdatePanel

Today I struggled for a while with a FormView that for no apparent reason wasn’t updating some of my fields to the database. After sometime I noticed that the fields that were not getting inserted into the database where the ones I had wrapped inside an UpdatePanel. Coincidence? I don’t think so…

I did a few tests and noticed that that was the problem indeed. I can’t say exactly what is the problem but it seems like that the FormView doesn’t like to have it’s fields inside an UpdatePanel.

The way I found to get around this issue is to populate the parameters manually in the events of the ObjectDataSource (ODS). So if you’re trying to insert a record you might using the Inserting event of the ODS to populate the problematic paramters:

protected void ObjectDataSource1_Inserting(object sender, ObjectDataSourceMethodEventArgs e)
    {
        e.InputParameters["FirstName"] = ((TextBox)FormView1.FindContro("TextBoxFirstName")).Text;
        e.InputParameters["LastName"] = ((TextBox)FormView1.FindContro("TextBoxLastName")).Text;
        e.InputParameters["City"] = ((TextBox)FormView1.FindContro("TextBoxCity")).Text;
    }

In the Inserting event of the ODS the InputParamters have already been populated (at least the ones outside the UpdatePanel) but the record hasn’t been inserted yet, so you are intercepting the parameters, adjusting it’s values and then letting it continue with the insertion.

I hope this code spares someone to have to go through the tests I had to do.

Force File Download

One handy feature that browser’s offer is the ability to automatically open know file types in their respective program. There are however times when you want to force the user to download the file, you want the Save As dialog box to appear to the user.

In order to avoid the default behavior and stop file from being open automatically you can use the content-disposition header. This is an HTTP header, and is not asp.net specific.

Content-disposition: attachment; filename=fname.ext

To do this using asp.net resources you can use the Response object to set the header like this:

Response.AppendHeader(“Content-disposition”, “attachment; filename=” + fileName);

It’s very simple and very handy. I wrote a working example below:

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

    protected void Button1_Click(object sender, EventArgs e)
    {
        string fileName = "MyFile.doc";
        string filePath = Server.MapPath("MyFiles/"+fileName);
        Response.AppendHeader("Content-disposition", "attachment; filename=" + fileName);
        Response.ContentType = "Application/msword";
        Response.WriteFile(filePath);
        Response.End();
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" Text="Download" 
            onclick="Button1_Click" />
    </div>
    </form>
</body>
</html>

 

 

Exposing events in Web User Controls

Web User Controls are a way encapsulating code that would have to be repeated in various pages, they are definitely a huge help.

VisualStudio makes so simple to create these user controls that even novice users can do it. When the page doesn’t need to interact with the user control it is really simple, and there’s nothing to it but putting the controls you want in the user control. However the controls that are inside the user control are isolated from the Page and you can’t use it’s events. This post will show you how easy it is to overcome this issue.

Let’s say we want to create a simple control with a DropDownList, a Button and a Label. When the button is clicked the selected value in the DropDownList is copied to the label. Here’s the code for it:

<%@ Control Language="C#" ClassName="MyUserControl" %>

<script runat="server">

    protected void ButtonCopy_Click(object sender, EventArgs e)
    {
        LabelText.Text = DropDownListNames.SelectedValue;
    }
</script>
<asp:DropDownList ID="DropDownListNames" runat="server">
    <asp:ListItem>Elisa</asp:ListItem>
    <asp:ListItem>Gabriel</asp:ListItem>
    <asp:ListItem>Rafaela</asp:ListItem>
</asp:DropDownList>
<br />
<br />
<asp:Button ID="ButtonCopy" runat="server" Text="Copy SelectedValue to Label" 
    onclick="ButtonCopy_Click" />
<br />
<br />
<asp:Label ID="LabelText" runat="server" Text="Label" Font-Size="X-Large"></asp:Label>

This is simple enough, right? All you have to do is place this control in any page and this behavior is going to be replicated. What I notice that most novice programmers miss is if you need the control to send some kind of information to the page.

Say you want to have a label in your page showing the time that the Copy button of the user control is clicked. It would be easy if you could access the button click event of the button inside the user control but unfortunately you can’t. What you want is to make the event of the inner button accessible to outside the control, this is done creating a new event exposing the event you want.


<%@ Control Language="C#" ClassName="MyUserControl" %>

<script runat="server">

    //this is the event that will be exposed
    public event EventHandler ButtonClick;

    protected void ButtonCopy_Click(object sender, EventArgs e)
    {
        LabelText.Text = DropDownListNames.SelectedValue;

        //this tests if the event has been subscribed by any method
        if (ButtonClick != null)
        {
            //fires the event passing the same arguments of the button
            //click event
            ButtonClick(sender, e);
        }
    }
</script>
<asp:DropDownList ID="DropDownListNames" runat="server">
    <asp:ListItem>Elisa</asp:ListItem>
    <asp:ListItem>Gabriel</asp:ListItem>
    <asp:ListItem>Rafaela</asp:ListItem>
</asp:DropDownList>
<br />
<br />
<asp:Button ID="ButtonCopy" runat="server" Text="Copy SelectedValue to Label" 
    onclick="ButtonCopy_Click" />
<br />
<br />
<asp:Label ID="LabelText" runat="server" Text="Label" Font-Size="X-Large"></asp:Label>

Now you are able to put the control in a page and use it’s event, like in the following example:

<%@ Page Language="C#" %>

<%@ Register Src="MyUserControl.ascx" TagName="MyUserControl" TagPrefix="uc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
    protected void MyUserControl1_ButtonClick(object sender, EventArgs e)
    {
        LabelTime.Text = DateTime.Now.ToString();
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <!-- Notice here that I use ButtonClick event I just created in the user control -->
        <!-- Also notice that I didn't misspell the event, the On is added by a VisualStudio convention   -->
        <uc1:MyUserControl ID="MyUserControl1" runat="server" OnButtonClick="MyUserControl1_ButtonClick" />
        <br />
        <asp:Label ID="LabelTime" runat="server" Text="Label" Font-Bold="True" 
            Font-Italic="True" ForeColor="#FF3300"></asp:Label>
    </div>
    </form>
</body>
</html>

You could also subscribe to the event in the code behind just like you do with asp.net controls. Here is the code for it:

<%@ Page Language="C#" %>

<%@ Register Src="MyUserControl.ascx" TagName="MyUserControl" TagPrefix="uc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
    public void Page_Load(object sender, EventArgs e)
    {
        MyUserControl1.ButtonClick += MyUserControl1_ButtonClick;
    }

    protected void MyUserControl1_ButtonClick(object sender, EventArgs e)
    {
        LabelTime.Text = DateTime.Now.ToString();
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <!-- Notice here that I use ButtonClick event I just created in the user control -->
        <!-- Also notice that I didn't misspell the event, the On is added by a VisualStudio convention   -->
        <uc1:MyUserControl ID="MyUserControl1" runat="server" />
        <br />
        <asp:Label ID="LabelTime" runat="server" Text="Label" Font-Bold="True" 
            Font-Italic="True" ForeColor="#FF3300"></asp:Label>
    </div>
    </form>
</body>
</html>

I wrote this post because I helped a few people in the asp.net forums and I hope it can help other people that are beginning to write web user controls. Happy coding guys.

GridView: Select last inserted record

The other day a responded a post on the asp.net forums about this so I think it might be useful to others.

Imagine if you have a GridView using pagination. When you insert a new record using a DetailsView or a FormView you want this new record to be automatically selected on the GridView, even if it’s not at the same page (of the GridView) that you currently have selected.

//returns a collection of records, including the one you just inserted
DataRowCollection drc = Dal.GetData();

//RecordID is the id of the record you just inserted, 
//you need to store this somewhere when you insert the record
DataRow dr = drc.Find(RecordID);

//having found the datarow of the record you need to know it's position(index) in the results
int index = drc.IndexOf(dr);

//Get the page the record will appear on
int page = index / GridView1.PageSize;

//If you're not already on the right page, set the PageIndex to the correct page
if (GridView1.PageIndex != page)
{
     GridView1.PageIndex = page;
}

 //gets the index of the record in the page
GridView1.SelectedIndex = index - (page* GridView1.PageSize);

 

Cache using Dynamic LINQ and Generics

You know those tables in your systems that are almost static (never change) by are consulted thousands of times a day? Well, the other day at work some asked me if we could avoid all this trips to the database.

The solution I came up with creates a cache at our BLL (Business Logic Layer) avoiding DAL layer to be called. First of all our base architecture is based on the principles on the asp.net tutorial Creating a Business Logic Layer. This article basically creates something very similar to a proxy pattern before the DAL which gives me the perfect place to intercept any calls to the DAL and consult my cache.

To avoid the trip to the database, when the BLL is instantiated I do one query to the database which returns all the records in the table. The resulting DataTable is stored in my cache class which is declared as static in the class. This will make possible that the cache is populated only once. All subsequent queries will fetch the results from the Cache instead of making a trip to the database.

The cache table is very simple. It stores a DataTable and performs filters in it using LINQ syntax. I had other options but since I was starting to work with LINQ at the time it seemed like a good choice. For this code I use the Dynamic LINQ which I mentioned in my previous post.

In order to work with TypedDataSets (which was a requirement for me) I create the Cache class to accept the DataTable and DataRow types.

public class CacheDataTable<T, S>  where T : DataTable where S : DataRow
    {
        private T cacheDataTable;

        //stores the DataTable that will be used for future consults
        public CacheDataTable(T dataTable)
        {
            this.cacheDataTable = dataTable;
        }

        //returns a DataTable filtered by the expression
        public T GetData(string expression, params object[] values)
        {
            IEnumerable<S> tmp = ((IEnumerable<S>)cacheDataTable).AsQueryable().Where(expression, values);
            return getDataTablePopulated(tmp);
        }

        //returns all the records
        public T GetData()
        {
            return getDataTablePopulated((IEnumerable<S>)cacheDataTable);
        }

        //takes an enumeration and creates a new DataTable
        private T getDataTablePopulated(IEnumerable<S> rows)
        {
            T dt = Activator.CreateInstance<T>();
            foreach (S row in rows)
            {
                dt.ImportRow(row);
            }
            return dt;
        }
    }

After having the Cache class defined you can use it in the BLL like this:

public class CountryBLL
{
        CountryDAL dal;

        //the cache is static so that it is shared among all instances from the CountryBLL class
        private static CacheDataTable<DataSet1.CountryDataTable, DataSet1.CountryRow> cache;

        public TBG_CountryBLL()
        {
            dal = new CountryDAL();
            //tests if the cache class has not been created yet. Only happens at the first access
            if (cache == null)
            {
                cache = new CacheDataTable<DataSet1.CountryDataTable, DataSet1.CountryRow>(dal.GetData());
            }
        }

        public DataSet1.CountryDataTable GetData()
        {
            //gets all records from the cache
            return cache.GetData();
        }

        public DataSet1.CountryDataTable GetDataByPK(decimal id)
        {
            return cache.GetData("id == @0", id);
        }
}

Coded like this the CountryBLL will only cause a database connection at its first instantiation. This approach should only be used with tables which are static (or almost). If one record is inserted in this table it would demand the application to be restarted so that the static cache variable would be unloaded and created again. There are ways around this but it is not the objective of this post.

Hope this will help someone :-)

Autocomplete has a problem with numbers

When using Ajax ControlTookit Autocomplete Extender I noticed that when the value I wanted to dislplay was a number starting with 0 (zero), like 0012, this initiating zero is removed and the result would show as 12. I didn’t want this beahavior so after googling for a few minutes I found a post that had a solution.

The each string of the list that is returned to the page should have escaped double quotes before and after the string. In the following example I take a DataTable and loop through it, creating a new List in which I add the element 0 (zero) of each row sorrounding it with the escaped double quotes.

List<string> list = new List<string>(10); 

 for (int i = 0; i < dt.Rows.Count; i++)
 {
     list.Add("\""+ dt.Rows[i][0].ToString() + "\"");
 }

 string[] arrayString = list.ToArray();

I can only assume that when the result is rendered on the page ajax library try to convert the results to numbers. Surrounding each number with escaped double quotes forces them to be treated as strings.

Thanks to my friend Allison Bertoloto who brought this problem to my attention.