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");
}

Creative Commons License
This work by Tito is licensed under a Creative Commons Attribution 3.0 Unported License.