Wednesday, December 21, 2011

Upgrading Nuget 1.5 to 1.6 - Installation error

If you have the Nuget 1.5 extension installed, your Visual Studio (VS 2010) will prompt to update to Nuget 1.6 version. If you try to update to Nuget 1.6, you might run into installation error. If so, uninstall the older version - Nuget 1.5 and then try installing the new version - Nuget 1.6. In order to uninstall Nuget, you need to run the VS 2010 in "administrator" mode.


For more details view the release notes here.

Monday, December 19, 2011

C# extension method - OrderBy sort expression as string

Recently I came across a question in a forum where a part of the solution requires the sort expression as string type for the OrderBy extension method. The requirement is, upon passing a string of property name separated by comma, the respective sort need to be applied and returned.

Without explaining further, directly I dive into the implementation so that you can easily infer from that. I altered the snippet got from http://www.extensionmethod.net/Details.aspx?ID=124 based on our needs.

Snippet 1 (Core extension method for OrderBy and ThenBy)

public static class IEnumerableExtensions
{
    public static IOrderedEnumerable<T> OrderBy<T>(this IEnumerable<T> list, string sortExpression)
    {
        sortExpression += "";
        string[] parts = sortExpression.Split(' ');
        bool descending = false;
        string property = "";

        if (!(parts.Length > 0 && parts[0] != ""))
        {
            throw new Exception("Invalid sort expression.");
        }

        property = parts[0];

        if (parts.Length > 1)
        {
            descending = parts[1].ToLower().Contains("esc");
        }

        PropertyInfo prop = typeof(T).GetProperty(property);

        if (prop == null)
        {
            throw new Exception("No property '" + property + "' in + " + typeof(T).Name + "'");
        }

        if (descending)
            return list.OrderByDescending(x => prop.GetValue(x, null));
        else
            return list.OrderBy(x => prop.GetValue(x, null));
    }

    public static IOrderedEnumerable<T> ThenBy<T>(this IOrderedEnumerable<T> list, string sortExpression)
    {
        sortExpression += "";
        string[] parts = sortExpression.Split(' ');
        bool descending = false;
        string property = "";

        if (!(parts.Length > 0 && parts[0] != ""))
        {
            throw new Exception("Invalid sort expression.");
        }

        property = parts[0];

        if (parts.Length > 1)
        {
            descending = parts[1].ToLower().Contains("esc");
        }

        PropertyInfo prop = typeof(T).GetProperty(property);

        if (prop == null)
        {
            throw new Exception("No property '" + property + "' in + " + typeof(T).Name + "'");
        }

        if (descending)
            return list.ThenByDescending(x => prop.GetValue(x, null));
        else
            return list.ThenBy(x => prop.GetValue(x, null));
    }

    public static IEnumerable<T> OrderByStringExpression<T>(this IEnumerable<T> queryObj, string orderByProperties)
    {
        if (string.IsNullOrWhiteSpace(orderByProperties))
        {
            //throw new Exception("Invalid sort expression");
            return queryObj;
        }

        string[] orderByPropertyArray = orderByProperties.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
        IOrderedEnumerable<T> orderedItem = null;

        if (orderByPropertyArray.Length > 0)
        {
            orderedItem = queryObj.OrderBy(orderByPropertyArray[0]);

            if (orderByPropertyArray.Length > 1)
            {
                for (int i = 1; i < orderByPropertyArray.Length; i++)
                {
                    orderedItem = orderedItem.ThenBy(orderByPropertyArray[i]);
                }

            }
        }

        return orderedItem;
    }
}

Snippet 2 (Example code)

var sortResult = listInst.OrderByStringExpression("Id,Name desc");

As you see, each property name should be separated by comma and if required you can specify the sort mode (asc/desc) followed by a blank space with the respective parameter.

Now with the above specified method, we can pass simple comma separated string as sort expression and get the related instance sorted. This will helpful in scenarios like implementing the Repository pattern as I did here.  Hope this helps.

References
http://www.extensionmethod.net/Details.aspx?ID=124





Sunday, December 4, 2011

Windows Phone 7.1 - Things to know about Dormant and Tombstone states

In WP 7.1, if we click on the start button when an application is running, the application will have the Deactivated event got fired. Usually developers will save any application state in this event handler into the application level dictionary object represented through the PhoneApplicationService.State property and make use of it in the Activated state again.

After the Deactivated event got invoked, the application which is in running state is moved to the Dormant state. Most developers get this state unnoticed. In this Dormant state, application still remain in memory but without processing happen and without application getting terminated. Based on the memory resource requirements for other applications, the application in the Dormant state has the possibility to get into the Tombstone state. The Tombstone state for an application represents the application as terminated, in the meantime, it holds the state info of the application. By state info we mean, the application state which is represented through the PhoneApplicationService.State property (as specified above) and the page state which is represented through PhoneApplicationPage.State property.

The main thing we need to notice is the reactivation scenario of an application. The application might get  reactivated from both the states directly. In both the cases, it raises the Activated event, where we need to identify whether the application is activated from the Tombstone state. If so, we can get values from the application level state dictionary (PhoneApplicationService.State) and make use of it. If it was from Dormant state, we don't need to do anything as the OS automatically preserves the state.

Since both scenarios raises the Activated event, there needs to be a mechanism to identify whether the immediate previous state is Dormant or Tombstone state. It is the IsApplicationInstancePreserved property of the ActivatedEventArgs which helps us to achieve this. As you might guess, if the IsApplicationInstancePreserved is true then it was from Dormant state and if it is false, then it was form Tombstone state.

While debugging your application you can validate both these Dormant and Tombstone state scenarios by clicking on the start button of your emulator when your application is running . When you click on the start button of the emulator, by default, the application will move to the Dormant state. If you want to validate the Tombstone state, check the "Tombstone upon deactivation while debugging" check box in the Debug tab of the project properties.

Following snippet helps you to understand handling of Dormant and Tombstone states:

Snippet 1 (App.xaml.cs)

private void Application_Launching(object sender, LaunchingEventArgs e)
{
    Debug.WriteLine("Application launching event");
}

private void Application_Activated(object sender, ActivatedEventArgs e)
{
    Debug.WriteLine("Application activated event");
    
    if (e.IsApplicationInstancePreserved)
    {
        Debug.WriteLine("Application activated from Dormant state....");
    }
    else
    {
        Debug.WriteLine("Application activated from Tombstone state.....");
    }
}

private void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
    Debug.WriteLine("Application deactivated event");
}

private void Application_Closing(object sender, ClosingEventArgs e)
{
    Debug.WriteLine("Application closing event");
}

Saturday, November 19, 2011

ScrollToBottom extension method in ScrollViewer - Silverlight 4

ScrollViewer is one among the commonly used Silverlight control. When you develop Silverlight application, at some time, you'll come across using ScrollViewer. Using ScrollViewer is straightforward in most of the cases. In some scenarios (like displaying chat history messages, stock history update), we might want to bind values to elements inside the ScrollViewer and then scroll to the bottom in order to make the latest message appear in the visible region.

ScrollToBottom() is one among the several extension methods available for ScrollViewer which helps us to achieve scrolling vertically to the end of the ScrollViewer content. While using this ScrollToBottom() method some developers won't see the ScrollViewer scrolls upto the bottom. So, why it is like that what need to be done to make it work? Let us dive into the implementation of ScrollToBottom() method and find out the solution.

Snippet 1: (ScrollToBottom() implementation)

public static void ScrollToBottom(this ScrollViewer viewer)
{
    if (viewer == null)
    {
        throw new ArgumentNullException("viewer");
    }

    viewer.ScrollToVerticalOffset(viewer.ExtentHeight);
}

As most of us might guess, it scrolls the veritical offset to the height of the content inside the ScrollViewer. Actually the values for properties like ScrollViewer.ExtentHeight, ScrollViewer.VerticalOffset are not recalculated immediately. It seems that they placed such restrictions due to performance considerations.

We can force to recalculate and update values of related properties by calling the UpdateLayout() method of the ScrollViewer. Anyhow be sure to call the UpdateLayout() only required. Please view the remarks section here at msdn documentation.

Ultimately, calling the UpdateLayout() method on the ScrollViewer before ScrollToBottom() is called will solve the obstacle.

Following is a sample snippet to help you understand the above specified scenario. Try executing the following snippet and inspect the value of ExtentHeight(and related properties) property by inserting the breakpoint in the call to UpdateLayout() method.

Snippet 2:
ScrollViewerTest.xaml

<UserControl x:Class="TestSilverlightApplication1.ScrollViewerTest"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="500" d:DesignWidth="500">
    <Grid Background="DeepSkyBlue">
        <Grid x:Name="LayoutRoot" Background="SkyBlue" Height="300" Width="400">
            <Grid.RowDefinitions>
                <RowDefinition></RowDefinition>
                <RowDefinition Height="Auto"></RowDefinition>
                <RowDefinition Height="70"></RowDefinition>
                <RowDefinition Height="Auto"></RowDefinition>
                <RowDefinition Height="70"></RowDefinition>
                <RowDefinition></RowDefinition>
            </Grid.RowDefinitions>
            <StackPanel>
                <TextBlock Text="ScrollToBottom Check" HorizontalAlignment="Center" FontWeight="Bold" ></TextBlock>

            </StackPanel>
            <TextBlock Grid.Row="1" Text="Enter multiline text here......"></TextBlock>
            <ScrollViewer Grid.Row="2">
                <TextBox AcceptsReturn="True" Text="{Binding SampleTextString, Mode=TwoWay}"></TextBox>
            </ScrollViewer>
            <Button Content="...and click here...." Click="ScrollDownCheck_Click" Width="150" Grid.Row="3" Margin="10"></Button>
            <ScrollViewer Grid.Row="4" Name="TestScrollControl">
                <TextBox AcceptsReturn="True" Name="TestTextBox" Text="{Binding AlteredTextString}"></TextBox>
            </ScrollViewer>
        </Grid>
    </Grid>
</UserControl>


ScrollViewerTest.xaml.cs

using System.Windows;
using System.Windows.Controls;
using System.ComponentModel;

namespace TestSilverlightApplication1
{
    public partial class ScrollViewerTest : UserControl, INotifyPropertyChanged
    {
        public ScrollViewerTest()
        {
            InitializeComponent();
            InitControls();
        }

        private string sampleTextString;

        public string SampleTextString
        {
            get { return sampleTextString; }
            set
            {
                sampleTextString = value;
                NotifyPropertyChanged("SampleTextString");
            }
        }

        private string alteredTextString;

        public string AlteredTextString
        {
            get { return alteredTextString; }
            set
            {
                alteredTextString = value;
                NotifyPropertyChanged("AlteredTextString");
            }
        }
         
        private void ScrollDownCheck_Click(object sender, RoutedEventArgs e)
        {
            ManipulateScrollDownCheck();
        }

        private void InitControls()
        {
            this.DataContext = this;
        }

        private void ManipulateScrollDownCheck()
        {
            this.AlteredTextString = this.SampleTextString;
            //Insert breakpoint here and validate the value of 
            //ExtentHeight before and after the execution of UpdateLayout().
            TestScrollControl.UpdateLayout();
            TestScrollControl.ScrollToBottom();
        }

        #region INotifyPropertyChanged Members

        protected void NotifyPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        #endregion
    }
}


You can infer from the above example that the call to UpdateLayout() is made before calling ScrollToBottom() and after assinging the value to the property bound to the content(UIElement contained inside the ScrollViewer) of the ScrollViewer. Since developers will face such problem only at certain workflows, call the UpdateLayout() only when you encounter that problem.

Reference
http://msdn.microsoft.com/en-us/library/system.windows.controls.scrollviewer.scrolltoverticaloffset(v=vs.95).aspx
http://msdn.microsoft.com/en-us/library/system.windows.controls.scrollviewer.scrolltobottom.aspx
https://epiinfo.svn.codeplex.com/svn/Silverlight.Controls.Toolkit/Controls.Toolkit/Common/ScrollViewerExtensions.cs

Sunday, November 13, 2011

n layer web app with Entity Framework 4.1/4.2 - Things to consider

With Entity Framework 4.1, it releases DbContext API and CodeFirst development model. It is recommended to work with DbContext which exposes the commonly used features of ObjectContext.
Creating object context in DatabaseFirst or ModelFirst approach can be done with the help of ADO.NET DbContext Genrator template in Visual Studio. To achieve that open the .edmx file and right click the base surface >> Add Code Generation Item >> Code >> ADO.NET DbContext Generator. This template is available only when you install EF 4.1 directly. If you install the EF4.1 with NuGet packages, the reference will get added but the ADO.NET DbContext Generator template won't be available. You can use NuGet packages for adding(and managing) the reference to the specific project or solution.

Repository pattern suits best for this case, so that we can create an individual repository for each entity. For details on repository pattern please visit msdn() and Martin Fowler's explanation. Following is a simple and common representation of repository that developers adopt using EF4.1. Please note that following snippet is just to understand the concept.

Snippet 1

public class CompanyRepository: IDisposable
{
    private HSMDBEntities Context { get; set; }

    public CompanyRepository()
    {
        this.Context = new HSMDBEntities();
    }

    public void Create(Company company)
    {
        this.Context.Companies.Add(company);
        this.Context.SaveChanges();
    }

    public Company GetCompanyById(int id)
    {
        //this.Context.Companies.Load();
        //return this.Context.Companies.Where(c => c.Id == id).Single();
        return this.Context.Companies.Find(id);
        
    }

    public IEnumerable<Company> GetAll()
    {
        return this.Context.Companies.ToList();
    }
    
    public void Update(Company company)
    {
        Company currentEntry = this.Context.Companies.Where(c => c.Id == company.Id).First();

        //Client wins model.
        this.Context.Entry(currentEntry).CurrentValues.SetValues(company);
        this.Context.SaveChanges();
    }

    public void Remove(Company company)
    {
        Remove(company.Id);
    }

    public void Remove(int id)
    {
        Company currentEntry = this.Context.Companies.Where(c => c.Id == id).Single();
        this.Context.Companies.Remove(currentEntry);
    }

    public void Dispose()
    {
        this.Context.Dispose();
    }
}

The above Repository snippet exposes the basic operations performed over the entity. Most of the methods are straight forward to understand and the two methods we need to concentrate are GetCompanyById() and Update().

GetCompanyById()  - The DbSet<T> property of the DbContext instance exposes a Find method which uses the primary key to find the entity. The speciality of this method is that the database will be hit only if the entity with the specific key is not found in the context. If the specific entity already got loaded, that entity will be returned upon request without hitting the database. That's why I've commented out the default way of retrieving the entity.

Update() - Consider the following scenario. In n layer architecture, the data model/entity retrieved will be converted into domain specific model and other DTOs(Data Transfer Objects), while passing across the layer to reach the client application(like web app). Similarly the modified data from the client reaches the data tier passing several transitions, and we simply update the database with the values from client. If any other request updates some column value of the entity in the interim time, those changes won't be respected, and whatever value reaches the data tier is updated in a brutal manner. This approach is called as client wins approach which is used common among n layer web applications. I restrict myself ending this update scenario with this short detail as this discussion itself can extend as a separate article. This client wins model is achieved in the above snippet by fetching the current status from the database and overwriting the values got from the client and continue saving it. The highlight here is the SetValues() method of the property DbPropertyValue, which assigns all the current values of individual properties with that of the properties of the parameter object supplied to it. This eradicates the great work of reassigning the individual property values explicitly.

this.Context.Entry(currentEntry).CurrentValues.SetValues(company);


in the place of

var entityEntry = this.Context.Entry(currentEntry);
entityEntry.Property(p => p.Id).CurrentValue = 1;
entityEntry.Property(p => p.CompanyName).CurrentValue = "Company name altered";

 

Now comes the reason for implementing the IDisposable. The best practice regarding the creation of DbContext instance when handling with a web application is - one context instance per request. Hence in n layer web application architecture, components in other layer(most of the times will be Business components) should take the responsibility of handling the lifetime of the context. This can be achieved by handling the respective repository instance with the using construct which automatically calls the dispose method of the repository instance.

using (CompanyRepository companyRepository = new CompanyRepository())
{
...............................
}


In real cases a base and a generic repository will be created based on the project nature and repository  created for each entities will be extended from the base repository. At that situation the base repository class will implement the IDisposable which handles the context instance creation and its lifetime.

public class CompanyRepository : BaseRepository
{        
    public CompanyRepository()
        :base()
    {
        
    }

    public void Create(Company company)
    {
        this.Context.Companies.Add(company);
        this.Context.SaveChanges();
    }

    public Company GetCompanyById(int id)
    {
        //this.Context.Companies.Load();
        //return this.Context.Companies.Where(c => c.Id == id).Single();
        return this.Context.Companies.Find(id);

    }

    public IEnumerable<Company> GetAll()
    {
        return this.Context.Companies.ToList();
    }

    public void Update(Company company)
    {
        Company currentEntry = this.Context.Companies.Where(c => c.Id == company.Id).First();

        //Client wins model.
        this.Context.Entry(currentEntry).CurrentValues.SetValues(company);
        this.Context.SaveChanges();
    }

    public void Remove(Company company)
    {
        Remove(company.Id);
    }

    public void Remove(int id)
    {
        Company currentEntry = this.Context.Companies.Where(c => c.Id == id).Single();
        this.Context.Companies.Remove(currentEntry);
    }

}

public class BaseRepository : IDisposable
{
    protected HSMDBEntities Context { get; set; }

    public BaseRepository()
    {
        this.Context = new HSMDBEntities();
    }

    public void Dispose()
    {
        this.Context.Dispose();
    }
}


The BaseRepository also need to be extended further. Its good to have the above things in mind while developing n layer web application. 

Saturday, October 29, 2011

ASP.NET MVC 3 - Representing contents in Razor View

The Razor view engine in ASP.NET MVC 3, throws error when we specify the content block directly without enclosing it in tags especially inside the coding constructs like if, for loop and so on.

Following Snippet throws error
@if(condition) {
    Any direct content.......
}


In such cases, developers usually specify tags like <span> as a workaround in order to specify the contents. But there exists two ways for directly represent this case.
  1. @: - for indicating the characters following it are content items and usually used for representing single line content.
  2. <text>....</text> - entire content block is enclosed within the <text>....</text> element and usually used for representing multi line contents.

@if(condition) {
    <text>Multi line statement 1
    Multi line statement 1
    ..................
    Multi line statement n</text>
}


@if(condition) {
    @:single line content goes here....
}


This is a straight forward feature but unexposed to several developers. It is simple but effective.

Sunday, October 23, 2011

Parsing and Manipulating HTML strings - C#

Recently I came across a situation, where I need to retrieve an HTML string created and stored by an ASP application. Upon retrieving the html string, I need to parse the string and manipulate html string by removing some deprecated attributes and us some other equivalent alternate instead. For instance the size attribute in the font element need to be replaced with css font-size attribute.

Snippet 1:

<font size="1">......</font>

to 

<font style="font-size: 9px;">......</font>


One additional thing we need to note here is, since we don't have any direct equivalent of the unit and value for the size attribute, I simply changed it to the expected size for the invoking applications.

Fine, now comes core of the issue about how to manipulate the HTML string. Initially I thought of using regex. Suddenly, I remembered of the nice tool Html Agility Pack which I explored few months back. Its an HTML parser that allows us to select an HTML element and manipulate it very easily. It uses the XPath to navigate through the elements. If you don't know XPath, no problem. You can refer to examples over the net (like in msdn and w3schools ) and find the XPath that suits better your requirement in less than a minute.

Following is the code for the situation I mentioned above.
Snippet 2:

private string RestructureDeprecatedAttributes(string htmlText)
{
    HtmlDocument document = new HtmlDocument();
    HtmlNodeCollection fontNodeCollection;
    
    document.LoadHtml(htmlText);
    fontNodeCollection = document.DocumentNode.SelectNodes("//font[@size]");

    if (fontNodeCollection != null)
    {
        foreach (HtmlNode fontNode in fontNodeCollection)
        {
            HtmlAttribute sizeAttribute = fontNode.Attributes["size"];

            if (!string.IsNullOrWhiteSpace(sizeAttribute.Value) && int.Parse(sizeAttribute.Value) > 0)
            {
                if (sizeAttribute.Value.Equals("1"))
                {
                    fontNode.SetAttributeValue("style", "font-size: 9px;");
                }
                else
                {
                    fontNode.SetAttributeValue("style", "font-size: 11px;");
                }
                
                fontNode.Attributes["size"].Remove();
            }
        }
    }

    return document.DocumentNode.WriteTo();
}

The selectors are really powerful which allows us to select the nodes that perfectly matches our criteria. The Html Agility Pack provides several methods that supports the manipulation of HTML strings in a very easy manner. You can infer this from the above code.
Creative Commons License
This work by Tito is licensed under a Creative Commons Attribution 3.0 Unported License.