CONNECT WITH US

Featured Post

ASP.NET MVC: HandleError action filter

ASP.NET MVC: HandleError

HandleError attribute is used to catch unhandled exception in controller action method. In default MVC template, HandleError attribute is already added to GlobalFilterCollection. In MVC 3, we can see it in Global.asax while in MVC 4 we can see it in App_Start/FilterConfig.cs. One thing to keep in mind is that HandleError will handle exception only if customErrors mode="On" is set in web.config.

Attribute Usage: Controller & method

Sample Code:

[HandleError]
public ActionResult Index()
{
    throw new Exception("HandleError Exception");
    return View();
}

As noted earlier, if we have not set customErrors mode="On" then HandleError will not catch this exception and it will show default YSOD(Yellow Screen Of Death).

YSOD(Yellow Screen Of Death) ASP.NETA

To enable exception catching, enable customErrors in web.config as below.

<system.web>
  <customErrors mode="On"></customErrors>
</system.web>

Now again run application, it should catch exception & it should display error.cshtml as displayed below.

With HandleError we can also specify ExceptionType for which to catch unhandled exception, View to display when exception is caught, and Master view.

Check out ASP.NET MVC: Action filter series post to read about other available  action filters.

You can follow me on twitter for latest link and update on ASP.NET & MVC.

Read More

ASP.NET Web Optimization Framework (Bundling & Minification) Articles

Right from developer preview version of ASP.NET 4.5 & MVC 4 (vNext), I have covered ASP.NET Web Optimization Framework (a.k.a Bundling & Minification) in my MVC 4 article series. Later on I have posted several articles covering different aspects of ASP.NET Web Optimization Framework and how I implemented it. So I'm writing this post as an index post of articles covering ASP.NET Web Optimization Framework. So it would be easier to access all posts under one roof. In upcoming days I'm planning to add few more articles on this topic, as and when I will add new articles I will update this index post as well.

If you come across any good article on this topic then do comment here, I will include it in this list.

You can follow me on twitter for latest link and update on ASP.NET & MVC.

Read More

[Picture] ASP.NET MVC: Flow between Model-View-Controller

Many times I'm asked this very basic question that how the ASP.NET MVC application flows between Model-View-Controller. So here we will try to understand it with Picture Post.

Flow between Model-View-Controller in ASP.NET MVC
  • User requests URL
  • Request is mapped to Controller('s Action Method)
  • Action Method process Model and select View(Result Type)
  • Processed Model is passed to View or Result Type
  • Generated response sent back to user

Hope this would be helpful. Stay tuned for more post.

You can follow me on twitter for latest link and update on ASP.NET & MVC.

Read More

ASP.NET 4.5 Model Binding: Creating Custom Value Provider

With ASP.NET 4.5, ASP.NET introduced model binding for web forms as well. Model binding helps to simplify code focused data access logic within web forms. Check out this video by Scott Hanselman to know more on ASP.NET 4.5 Web Forms Model Binding.

Here in this post, we will see how we can create our own custom value provider (read my post on how I used value provider for encrypted query string in MVC application). We will also examine inbuilt class of ASP.NET 4.5 model binding framework which can be useful in creating custom value provider more easily with focused approach.

Before we look into actual interfaces and classes, let us examine few basics of model binding framework. All model binding framework and corresponding classes are resides in System.Web.ModelBinding namespace which is newly introduced with ASP.NET 4.5. For any value provider to work with model binder it requires two components one is implementation of value provider which reads data from request and forward it to model binder and other one is value provider source attribute which expose the actual value provider instance. Have a look at below code snippet here QueryStringAttribute is value provider source attribute which expose object of QueryStringValueProvider so model binder can use it to fetch data.

public IQueryable<Blog> SelectMethod([QueryString]int? id)

Creating Value Provider Source Attribute

To create custom value provider attribute we can derive Attribute class and implement IValueProviderSource interface as displayed in below code snippet.

public class CustomValueProviderAttribute : Attribute, IValueProviderSource
{
    public IValueProvider GetValueProvider(ModelBindingExecutionContext modelBindingExecutionContext)
    {
        return new CustomValueProvider(modelBindingExecutionContext);
    }
}

Here we can have access of ModelBindingExecutionContext and we can pass same to value provider if it is required. Through ModelBindingExecutionContext we can also have access of HttpContextBase and ModelStateDictionary.

Creating Value Provider

Same way we can create Custom Value Provider by implementing IValueProvider interface. Below code snippet shows pseudo code for the same.

public class CustomValueProvider : IValueProvider
{
    ModelBindingExecutionContext _modelBindingExecutionContext;
 
    public CustomValueProvider(ModelBindingExecutionContext modelBindingExecutionContext)
    {
        this._modelBindingExecutionContext = modelBindingExecutionContext;
    }
 
    public bool ContainsPrefix(string prefix)
    {
        // validate if requested key is exist or not
    }
 
    public ValueProviderResult GetValue(string key)
    {
        // return ValueProviderResult object we 
        // can use ModelBindingExecutionContext
        // to access request data
    }
}

Once we are ready we can use created value provider as

SelectMethod([CustomValueProvider]int? id, [CustomValueProvider]string name)

As noted earlier, there are few inbuilt classes in ASP.NET 4.5 model binding framework which give more focused control over custom business logic. Here we will also examine one of its which is SimpleValueProvider. Here we will examine how we can focus on core logic and leaving other responsibility on core framework.

public class CustomValueProvider : SimpleValueProvider
{
    public CustomValueProvider(ModelBindingExecutionContext modelBindingExecutionContext)
        : base(modelBindingExecutionContext)
    {
    }
 
    protected override object FetchValue(string key)
    {
        // here we can access this.ModelBindingExecutionContext
        // and can look into request data. Once we fetch requested
        // data we just need to return actual value for e.g.            
        return "dotnetExpertGuide.com";
        // NOTE: WE ARE NOT RETURNING ValueProviderResult INSTANCE
    }
}

Earlier with IValueProvider, we had to check if requested key exist or not and if it is then instantiating ValueProviderResult and return it. While with SimpleValueProvider we only need to return actual value of requested key or null incase if it does not exist rest will be taken care by SimpleValueProvider class. Another such framework class is NameValueCollectionValueProvider which act as a base class to create value provider from name value collection. Here I am not demonstrating it. I am leaving it for reader :).

SimpleValueProvider and ASP.NET MVC

Can’t we have/introduce SimpleValueProvider class for MVC in upcoming version?

ModelStateDictionary

Once model binding is done for parameter it is added to ModelStateDictionary dictionary along with its value. For e.g.

SelectMethod([CustomValueProvider]int? id, [CustomValueProvider]string name)

In above code once model binding is done for parameter id, it is added to ModelStateDictionary and it is accessible in rest of the parameter model binding i.e. parameter name here.

Hope this would be helpful. Stay tuned for more post.

You can follow me on twitter for latest link and update on ASP.NET & MVC.

Read More

[Picture] ASP.NET MVC: Action Filter Life Cycle

It is said that A picture is worth a thousand words, so this time I come up with Picture Post to discuss action filter life cycle in ASP.NET MVC. Hope reader would like it. So do share it and stay connected for more post on Action Filter.

ASP.NET MVC: Action Filter Life Cycle
ASP.NET MVC: Action Filter Life Cycle

You can follow me on twitter for latest link and update on ASP.NET & MVC.

Read More

PowerShell: Accessing static member in PowerShell Script

Recently I created NuGet package which auto upgrade ASP.NET MVC 3 application to MVC 4 and while I was creating this package I worked with powershell. Before that I never worked with powershell so I learned a few thing so thought to share it with reader. If you are new to powershell then you can execute powershell script with command prompt or if you are GUI inclined then Windows 7 also have PowerShell ISE (Integrated Scripting Environment).

To open command prompt type powershell in Run window and press enter or search for powershell in Start all programs and open powershell ISE.

In PowerShell ISE we can see two pane Command Pane & Output Pane. Both pane names are self explanatory so I'm leaving it upto you ;) But yes in command window we can fire any command which we can fire in Windows Command Prompt.

Accessing Static Member

Sometime we need to access static member from powershell script as I required it while creating this NuGet package. So in powershell, we can access static member with Scope Resolution Operator (::). For e.g. type following command in powershell command pane

Upon hitting enter in command prompt we can see output in output pane

So in powershell we can access static member with the help of Scope Resolution Operator (::). Hope this would be helpful!

You can follow me on twitter for latest link and update on ASP.NET & MVC.

Read More