Exploring Enums support in ASP.NET MVC 5.1 – Part 2

This is second part of the series of exploring enums support in ASP.NET MVC 5.1 that was recently got released with Visual Studio 2013 Update 2. The first part of the series can be read from the below link

Enums support in ASP.NET MVC 5.1- Part 1

In last post we discussed that how the new scaffolding works fantastic for enum types as well. But there are other different scenarios where we need to customize it before displaying on UI. We discuss the issue in one of the sceanio in last post. To handle these scenarios, few other new helper methods got introduced. A new class EnumHelper got added which has two methods :

GetSelectList – which has four overridden method and it returns a list of SelectListItem which can be used to further populate the dropdown in UI.

IsValidForEnumHelper- This method also has two overridden method that tells whether the passed type is enum. This should be used to check the type of passed value and GetSelectList should be used if IsValidForEnumHelper returns true.

So let’s jump to the example and use the above methods.

In part-1 of the series, we used the following enum in the example

public enum ExpertiseArea
{
    ASPNET,
    Csharp,
    WindowsAzure,
    WCF
}

but as we know that enum properties can not include space or some special characters. Say, if we want to display WindowsAzure as Windows Azure or ASPNET as ASP.NET etc. In this scenario, we need to create custom views for edit and display purposes.

First let’s change the enum itself and add the display attributes as

    public enum ExpertiseArea
    {
        [Display(Name = "ASP.NET")]
        ASPNET,
        [Display(Name = "C#")]
        Csharp,
        [Display(Name = "Windows Azure")]
        WindowsAzure,
        WCF
    }

Now let’s create the partial view for display scenario.  Here we need to cater multiple scenarios like

- If there are some items which has some selected value for enum property then find the selected text/vale. SelectedText represent the display attribute

- If nothing is selected then show the empty value. (Empty value cannot be converted in enum type)

- If the type itself is not an enum then use the normal value.

We can write it as

@model Enum

@if (EnumHelper.IsValidForEnumHelper(ViewData.ModelMetadata))
{
    string displayAttrName = null;
    foreach (SelectListItem item in EnumHelper.GetSelectList(ViewData.ModelMetadata, (Enum)Model))
    {
        if (item.Selected)
        {
            displayAttrName = item.Text ?? item.Value;
        }
    }

    // displayAttrName is not assigned to any value
    if (String.IsNullOrEmpty(displayAttrName))
    {
        if (Model == null)
        {
            displayAttrName = String.Empty;
        }
        else
        {
            displayAttrName = Model.ToString();
        }
    }

    @Html.DisplayTextFor(model => displayAttrName)
}
else
{
    @Html.DisplayTextFor(model => model)
}

Make sure that above Partial View enum.cshtml is created in EditorTemplates folder under the Shared directory.

So if we see the above code, then we find that EnumHelper.IsValidForEnumHelper is used to check that whether the passed value is of enum type and the other one EnumHelper.GetSelectList which returns the list of items in SelectListItem type as discussed.

Now let’s us create the partial view for Edit purposes as

@model Enum

@if (EnumHelper.IsValidForEnumHelper(ViewData.ModelMetadata))
{
    @Html.EnumDropDownListFor(model => model, htmlAttributes: new { @class = "form-control" })
}
else
{
    @Html.TextBoxFor(model => model, htmlAttributes: new { @class = "form-control" })
}

This partial view also should be in EditorTemplates folder under the Shared directory. Here again the new helper method EnumHelper.IsValidForEnumHelper which tells whether the provided model data is of type enum or not. When it is of type enum then it uses @Html.EnumDropDownListFor else uses normal @Html.TextBoxFor

Now let’s see the Create/Edit views and here we have not used
@Html.EnumDropDownListFor instead used normal @Html.EditorFor which uses the display and edit templates that we created

   @Html.EditorFor(model => model.Area)

Now let’s run the application, in create page looks like

Part2-1

and after adding Index look as

part2-2Here the earlier issue is resolved and we are able to see the consistent values on diffrent CRUD screen. We can write the similar custom code in other scenarios as well.

Happy learning,
Brij

Enums support in ASP.NET MVC 5.1- Part 1

Hello All,

Recently Microsoft releases a second update for Visual Studio 2013 named Visual Studio Update 2 RC. Here RC means that it is in Release candidate version  and you may expect few changes in the final version. But there are a list of changes they provided in ASP.NET MVC and Webforms that will be going to help a lot in your day to day coding. The new version of ASP.NET MVC is named as ASP.NET MVC5.1. In few of my coming posts, I’ll be discussing the major changes in ASP.NET MVC with examples.

So in this post, We’ll discuss few features of ASP.NET MVC5.1. ASP.NET MVC provides scaffolding that enables us to create the controller and views for our model. The controls on views are rendered based on the type of properties in the model but it is not true for all types. Say if you have property in your which is of type Enum then the UI generate the normal textbox for it which allows to enter free text which may become brutal to your application if it is not handled properly. To handle this scenario, I discuss that in one my old post, how you can extend EditorFor for custom type. You can refer the link

Html.EditorFor – Extend for custom type

But it requires lots of steps and require to handle various scenarios like displaying, editing etc which is error prone as well. Let’s take the same earlier example, I took a class as

    public class Speaker
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public bool IsAvailable { get; set; }

        public ExpertiseArea Area { get; set; }
    }

The enum type ExpertiseArea is defined as

    public enum ExpertiseArea
    {
        ASPNET,
        Csharp,
        WindowsAzure,
        WCF
    }

Now when I created the Controller and Views via scaffolding as

Controller

and

addcontroller

and It created the controller and related views. Now lets run the application so it looks like as

page

Great!! Now you can see that expertise area is rendered as dropdown without any specific code. That’s fantastic.

Now let’s have a look on the cshtml page itself

 @Html.EnumDropDownListFor(model => model.Area, htmlAttributes: new { @class = "form-control" })

So here, we find that there is a new helper method EnumDropDownListFor got introduced that is used for enum types. And this is used for on Create and Edit views because these views only allows user to edit or enter new data. Rest of the views are same as earlier.

This is very good feature that will help a lot to developers.For simple scenario it is fine, so let us discuss another scenario, where we dont want to show the actual enum value but we want to show some different value on the UI. So let’s add display attribute in enum as

    public enum ExpertiseArea
    {
        [Display(Name = "ASP.NET")]
        ASPNET,
        [Display(Name = "C#")]
        Csharp,
        [Display(Name = "Windows Azure")]
        WindowsAzure,
        WCF
    }

Now again, let’s run the application and see the create page

part1-1It seems great, the value that populated in dropdown is what we put in display attribute. That’s what we want. Let’s add it and see the index page

part1-2Ohh.. this we did not expect. We expected that it should be C#. It means that it cannot be handled without just by simple scaffolding but it is required some custom code.

We’ll discuss this scenario in next part. Stay tuned!

Cheers,
Brij

How to Override Finalize method in C#

Being a .NET Developer, you must have basic information about Garbage Collector. Garbage Collector is a boon for .Net developers which takes care of memory management for .NET programs in the background.

But as we know that there are some limitations as well. Garbage collector can collect only managed object. So what about unmanaged objects. Garbage collector cannot clean up unmanaged object properly because these object are not limited to .NET framework and CLR does not have complete control on it. So it is developer’s responsibility to clean up unmanaged resources. It is advised to override the Finalize method (that is a virtual method in Object class) to clean up the unmanaged resources. Garbage collector calls the finalize method of each object (which has overridden Finalize method) while collection process.

So have you ever tried to override the Finalize method in C#? Let’s do that

 public class MyClass
    {
        protected override void Finalize()
        {
            // Do unmanaged resource clean up
        }
    }

For simplicity, I just override the Finalize method. Now let’s build the code.
Ohh.. The above code does not build. It gives the following errorErrorSo if you see the error, it says that do not override Finalize. Instead use destructor.

It means We cannot override Finalize directly in C#.

So what is other way? As in error it suggests to provide destructor. So let us write the destructor (destructor in any class starts with tilde (~)). So now my class looks like

    public class MyClass
    {
        ~MyClass()
        {
            // Do unmanaged resource clean up

            Console.WriteLine("In destructor");
        }
    }

Now let’s build it.
It builds successfully. Now let’s see this class using assembly Reflector.
destuctorSo here our destructor turned into Finalize method. So it means that destructor and Finalize are same in C#. But obviously while writing code in C#, it does not allow to override the Finalize method so we have only option to write destructor for that.

So don’t get confused ever if you see somewhere that say to override Finalize and you are not able to override it. Instead use destructor for that purpose.

Cheers,
Brij

Speaking on ASP.NET MVC5 at C# Corner Annual Conference 2014 – Apr 12

Hello All,

csharpcornerI am very excited to share you all that I’ll be speaking in C# Corner Annual Conference 2014. C# Corner Annual Conference is North India’s largest conference and hosted by http://www.c-sharpcorner.com/ from last four years.

It is a full day event and you’ll get ample opportunity to learn from renowned International/national speakers. For more details Click here

I’ll be speaking on the latest version of ASP.NET MVC (5) and discuss how it solves your real time issues and make our life easier. The agenda of my session will be

  • One ASP.NET
  • Know the power of Attribute routing
  • Authentication using external authentication providers
  • Build the rich and clean UI with Bootstrap
  • Using Authentication filters
  • Lots of demos

You’ll enjoy the day with lot of learnings and fun. See you all there..

Cheers,
Brij

 

Exploring ASP.NET FriendlyURLs – Guest Post on South Asia TechNet Blog

Recently, I write a post on ASP.NET new feature FriendlyURLs on South Asia Technet Blog.

Being an ASP.NET developer, you must have worked on ASP.NET Web Forms and ASP.NET MVC. One of the things in MVC, most of us like that is pretty and elegant URL. But this is not in the case of using ASP.NET web forms.

 These URLs include crappy extensions like aspx. Many developers have written their custom URL writer or used some third party libraries to achieve it. And here we either end up paying some extra bucks for the third party library or writing custom URL writer which is itself painful task.. Read more

 

Writing Asynchronous Web Pages with ASP.NET- Part 3

This is third post in the series of Writing Asynchronous Web Pages with ASP.NET. In first post, We discussed briefly about various asynchronous patterns and wrote an asynchronous web Page using APM model. In second part, we used Event-based asynchronous pattern (EAP) and discussed it with a example. Please find the links of my earlier post below.

  1. Writing Asynchronous Web Pages with ASP.NET- Part 1
  2. Writing Asynchronous Web Pages with ASP.NET- Part 2

 

In this post, we are going to use another pattern. .NET 4.0 introduced Task Parallel Library (TPL), which simplified the way to write asynchronous code. Let’s briefly understand the TPL. It provides a method (as naming convention method name ends with async) which returns a Task (or Task<TResult>) .

Task represents an asynchronous operation which contains the Result once completes. After getting the task, we can do some other activity and can keep checking the status of the Task. Once it completes, read the result from the Task.

We can provide an asynchronous method in our class that provides an async method that returns a task as

public class MyCustomClass
{
    public Task<int> ReadAsync(byte[] buffer, int offeset, int count);
}

Task actually internally uses Thread Pool and a thread is allocated to the task using thread pool to complete the task but all this complexity is hidden from the user and .NET itself lays down the required infrastructure for this.

Now, scores of classes in .NET libraries supports this pattern and we can make use of that.

.NET4.5 made our life much easier by introducing to keywords async and await which allows us to write the asynchronous code in a synchronous way. All the other required basic activities like context switching etc are taken care by the .NET framework for us. These keywords are provided over Task Parallel Library  that got introduced in .NET 4.0. Writing asynchronous activities with these keywords are highly optimized, performance oriented and make best use of TPL.

Now let’s use this pattern and write another asynchronous page. So in this examples, I am using a WCF service that returns a list of Employees and that is getting displayed on the web page. So our Page_Load method could look like

protected async void Page_Load(object sender, EventArgs e)
{
    WcfService.Service1Client client = new Service1Client();

    var customers = await client.GetEmployeesAsync();
    gdCustomers.DataSource = customers;
    gdCustomers.DataBind();
}

So as we see here that my service supports the TPL, async and await keywords based asynchronous pattern.

In page life cycle, when Page_load gets fired, ASP.NET finds it async and when it reaches to await, it releases the current thread and a new thread is picked from the thread pool to continue the activity and the call the web service took place asynchronously. Once the data returns from service, the same UI thread is assigned to execute further.
But there is better way to use async and await in web page. This has an issue as well and execute the code in synchronous mode . As we know our page life cycle has a set of events that gets fired in a predefined order and next event will be fired only when the last event completes. So if we use the above way of async Page_Load, this event will be fired during page life cycle event once it reaches to async, current thread gets free and a another thread got assigned to complete the task asynchronously, but the ASP.NET cannot execute the next event in life cycle because Page_Load has not been completed yet. And underlying synchronization context waits till the asynchronous activity completes. Then only the next event of page lifecycle will be fired which makes the whole process in synchronous mode only.

So to avoid it, there is a better is available. So the new way uses ASP.NET method RegisterAsyncTask which takes PageAsyncTask as a parameter. So let’s write the code then we’ll discuss that How does it work?

protected void Page_Load(object sender, EventArgs e)
        {
            RegisterAsyncTask(new PageAsyncTask(async () =>
            {
                using (Service1Client client = new Service1Client())
                {

                    var customers = await client.GetEmployeesAsync();
                    gdCustomers.DataSource = customers;
                    gdCustomers.DataBind();
                }
            }));
        }

Here, we have register a delegate using method RegisterAsyncTask at Page_Load. It does not fire the event while running the Page_Load event. Here it just register an event and tell the ASP.NET to execute it. Now as we have already marked page as async, ASP.NET itself decides the best time to execute it asynchronously and Page Life cycle events gets fired as usual without waiting for the async task to complete. This is very useful in the scenarios where we want to run multiple asynchronous tasks. Multiple tasks can run parallel if required. So now we have given the liberty to ASP.NET to execute this task asynchronously rather than waiting for the async task to get it completed then fire the next page life cycle events.

Hope you have enjoyed the post.

Cheers,
Brij

Writing Asynchronous Web Pages with ASP.NET- Part 2

This is the second part in the series of Writing Asynchronous web pages in ASP.NET. In my last post, we discussed about various programming model for writing asynchronous code and wrote a asynchronous page using Asynchronous Programming model(APM). The link of part-1 of the series is given below

Writing Asynchronous Web Pages with ASP.NET- Part 1

In this post we’ll use another approach that is Event-based asynchronous pattern(EAP).

What is Event-based asynchronous Pattern (EAP)?

This model provides another way to write asynchronous code. In this pattern, it provides one void method (as a naming convention method name ends with async) and one or more events to notify the caller that there is a change in status. It means we don’t need to keep checking the status of the task, an event will be raised once the task will be completed. This asynchronous task runs in the background and simplest one, uses BackgroundWorker class to implement.

Any class that provides the capability to call its method asynchronously (using EAP model), provides a method that ends with async (naming convention) and an event that notifies when the task completes. It can provide more events to provide the status of the thread. We should follow these rules in our class if we want to write our own custom asynchronous methods that uses EAP Model.

So let’s create a class that uses this pattern

public class MyCustomClass
{
    public void ReadCharCountAsync(byte[] buffee, int offset, int count);
    public event ReadCompletedEventHandler ReadCompleted;
}

public delegate void ReadCompletedEventHandler(object sender, ReadCompletedEventArgs readCompletedEventArgs);

public class ReadCompletedEventArgs : AsyncCompletedEventArgs
{
    public int Result { get; }
}

We can see here that my class has one async method and one event handler. Then we defined the event handler and event arguments which contains the result of the method.

In this post, I’ll be using a .NET class WebClient that provides a method that can consumed asynchronously using EAP model. In this example, I am just downloading a page from the given URL and showing it on the screen. There could be many other scenarios.

I have created a webpage and put Async=”true” in the page directive in aspx file. This tells the page that this will be executed asynchronously. So let’s see the code behind

public partial class AsyncEAP : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

            WebClient client = new WebClient();
            Uri uri = new Uri("http://www.google.com/");

            // Specify that the DownloadStringCallback method gets called
            // when the download completes.
            client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(DownloadStringCallback);
            client.DownloadStringAsync(uri);
        }

        void DownloadStringCallback(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                renderedItem.InnerHtml = e.Result;
            }
        }
    }

So if we see the above code then we see that in Page_Load method after creating the instance of WebClient, I have subscribed the completed event and then called the DownloadStringAsync method. DownloadStringCallback method gets called once the download completes. Here I just checked if there is an error while executing and if there is no error then accessed the result. Here there is no way to find the status of the task but sure that once the method completes its processing, the completed event handler will be fired.

There are many other classes that provides the async feature using this model and we can use that. In my next post, We’ll use Task based asynchrony and see how can we leverage that in our ASP.NET pages.

Cheers,
Brij