Filters in Asp.net MVC

. Saturday, January 10, 2015
1 comments

Hello Friends,

Today We're going to discuss What are the Filters,How many types they are and How do they Work, so without any further Ado lets start.

If you want to perform Your Stuff "Pre" or "Post" Action then use Filters. They Work in similar way as there are various Filters Implemented in any Water Filter that's why They are called Filters :).

Lets look at the diagram below
 
This is how the Filters are Arranged in the Asp.net MVC Pipeline. The Arrangement shown in the Diagram is same as Arrangement in MVC i.e. each one is being kept in the sequence as per its Work.
 
Now You've the Basic Idea about Filters in MVC, Now we need to explore each one of them, Lets start with Authorize Filter First.
 
I think I've explained everything related to authorize Filter so in Brief You're action can be Executed only by the Users, Roles to whom You've granted the Permission.
 
Now Lets dig into Next and very Important ActionFilter. There are actually two methods Representing This First OnActionExecuting This one fires as soon as Authorization has been taken place but Action doesn't start Executing i.e. "Before" Action and another one is OnActionExecuted this one fires as soon as Action has executed all of Its Code and and before Its Ready to return the Contents to View i.e. "After" Action Execution.
Lets see the diagram
 

 
Once these two filters has been Executed Control leaves the coding Part Action,Controller and Now Its Time to Render the Contents to related View.The Two Filters responsible for this are OnResultExecuting and OnResultExecuted Respectively.Please note that OnResultExecuting is something where You can make manipulation in the Contents which will be rendered in the View whereas OnResultExecuted is something where You can release the Resources,finish the tasks,Log the Changes etc.
 
 
Apart from this one more is there Exception Filter which is inherited from IExceptionFilter and Implements OnException which will occur whenever there's any error occur during Execution of any Filter. Please note that even if there's error in any of the Filter the Sequential Execution of Filters will Remain means They will execute their Code but the Actual Exception can only be caught at Exception Level Filter.
 
 
In How Many Ways You can apply the Filters in MVC ?
well, There're mainly Four Ways You can do this
 
1)Decorate the inbuilt Filters given by System.web.mvc upon any Action.
e.g.
 
[Authorize(User="UserName",Roles="Specify one or more roles separated by comma"]
Public ActionResult Index()
 
2)Use Custom Filters i.e. Create various Classes and Inherit them as follows :
       a)If Its AuthorizeFilter then IAuthorizeFilter,Implements OnAuthorization
       b)If Its ActionFilter then ActionFilterAttribute which implements 
       OnActionExecuting,OnActionExecuted.
       c)If Its ResultFilter then again the mentioned above but Implement
       OnResultExecuting,OnResultExecuted.
      d)If Its ExceptionFilter then IExceptionFilter,Implements OnException.
3)Registering Filter using Filters.FilterProvider for specificity.
4)Registering Global Filters.
 
Orders and Scope of the Filters
 
a)Order :
Its an Attribute which you can specify to determine Execution Order of Similar Type of Filters.
by default Filters Decorated on any Action arranged as Stack in which the Top one has the Less value than the bottom one i.e. -1 so lesser Order value Filter Executes First,You can explicitly specify this while decorating.
 
 
b)Scope :
What If two same filter type have same Order ? then the Scope comes in,following is their precedence
 
First
Global
Controller
Action
Last


 
 
Cancellation :

Suppose there are two different Filters A,B, placed A above B. each one Implements are the basic four type of Filters.
so below will be their Executing Sequence.

OnAuthorization - A
OnAuthorization - B
OnActionExecuting - A
OnActionExecuting - B
OnActionExecuted - B
OnActionExecuted - A
OnResultExecuting - A
OnResultExecuting - B
OnResultExecuted - B
OnResultExecuted - A
OnException - A
OnException - B

Now Let Say You want to suspend the Executing of A during the Process then You can do this by setting the Result Property to non null value which will abort the upcoming events of similar type for this Filter and Other Filters but any pending or Already Executed Filter's events will be Executed.
so lets say you set Result in OnActionExecuting - A to any string value then the above sequence will be
OnAuthorization - A
OnAuthorization - B
OnActionExecuting - A
All the Upcoming Implementation of similar Types will be aborted
OnResultExecuting - A
OnResultExecuting - B
and so on....

So That's It from my side, Hope You've enjoyed the Article If you have any queries in this You can ask it.
Complete Project for the above explanation can be downloaded from Here.
 

One To Many,Many To Many In Entity Framework Practical Approach

. Sunday, December 23, 2012
0 comments

Hi Guys,
I wondered through lots of places to find solution of my problem that How to establish One To Many,Many To Many Relationships in Entity Framework,but I didn't find any good solution so finally decided to create my own practical solution for this.

In my solution I'm providing following things :-
a)Created the corresponding database for relationships like One To One,Many To One (vice-versa),Many To Many etc.
b) Established Entity-Framework Model from Database i.e. Database First Technique.
c) Performed Add in Many To One & Many To Many Relationships.
d) Performed Cascade Delete in relationships
e)Give me one commitment to Perform Cascade update after finding the complete solution so that my this post will get succeed.

You should follow the exact approach which I shown in the example given for saving of many to many deleting etc, such techniques are built-in features of Entity-Framework Relationship Model we should use them.

Please find the complete code from my GitHub repository Here.

Hope you'll enjoy my this article Please feel free to comment.
Thanks Happy Coding.

Creating classes in Javascript

. Sunday, November 18, 2012
0 comments

Hi Guys,

If you searched for classes in javascript ? then you are on the right place, Well like any other technology javascript also supports for oops but unfortunately it does not support for classes, Yes , Javascript is a class-less technology script.

We can simulate class behavior in javascript by creating an object for the function and then we can achieve behavior for accessing various methods of that function through the object created.

Lets take a look 
 
function Car( model ) {
  var value=1; //private member   

  this.model = model;  //all members with this are public
  this.color = "silver";
  this.year  = "2012";
  this.getInfo = function () {
    return this.model + " " + this.year;
  };
}

Now we create an object for this function to access method like this


function Run()
{
var myCar = new Car("ford");
myCar.year = "2010";
alert( myCar.getInfo() );
}

First we create object of Car then we set the year property and then accessed the method , all these are available only because its declared as public with 'this.' but we would not access value member as its declared privately, so here's we are achieving encapsulation by hiding the some members declared privately,which can be used for security purpose.
Please find the complete code on git here

Disable functionality with jquery -a simple approach

. Wednesday, October 24, 2012
0 comments

Hi Guys,
How can you disable any control with particular Id/class etc of html, with jquery its fairly very simple
create a method which will disable the control.
Note : that the disable method is not jquery's method . Its a custom method (command) created for our application use.
 
(function ($) {
   $.fn.disable = function () {
       return $(this).each(function () { 
            $(this).attr('disabled', 'disabled'); 
       });
    };

Now access the element with Id(in my case)

 
var input = $('#txtname');
// Disable all the controls having
input.disable();

body of html appear like this

 
             
                

as all of you know now i'm using git so please download the complete example from here

Add/Delete Row In Table Using Javascript

. Thursday, October 18, 2012
0 comments

Hi Guys,Today I will tell you how can you add/delete rows of html table using javascript functions,so lets start with this.
First I m creating a html table very simple table with one row as default to appear.

 
    
Quantity

Now create two buttons which will be used to add/delete row as follows 
 
    
    

What the magic going on here on click of both the buttons ?????
well , when you click on Add Row button javascript function addRowProduct is called which receives the id of table,we've passed inside the single quote, and inside this function we did following :
a) access the table by its id and assign it to var variable.
b) find the total number of rows right now,and insert a empty row to current index which equals to total row count here.
c)create cell at first position i.e. 0 of row and append an element of type input with  its properties like id,type,class name etc inside this cell.

Similarly when clicking on delete button javascript function deleteRow called in which we did following :
a)access the table by its id in var type variable.
b) find the total number of row in table.
c)delete the row of total row count minus 1.

what's the interesting point to remember here is  table row index starts from 0 so while add new row we just need to insert the row with total row count which automatically inserts row to current index and count increases by one while deleting the row we passes the total row count minus 1 because its deletes by index so if total row count is n then we need to delete the row at n-1 index to delete the max. row.
One good news for all my readers now I m on github (a social coding site uses git (distributed version control system)) so that I can share the running code as well for better understanding of how things are happening.
Really amazing isn't it .
Please find the entire code for this stuff here.
Thanks and happy coding... 

UrlRewritingNet with asp.net

. Saturday, August 25, 2012
0 comments

What’s a Url Rewriting ?

Well, writing urls in such a friendly manner so that it can be more readable and seo-friendly, we use urlrewriting.

for example suppose i am having an url like

http://domainname.com/mypage.aspx?Id=1

after using url rewriting i can rewrite this url like

http://domainname.com/mypage.aspx/1

isn’t it more readable off course it is, and in this way search engines also recognizes your url better way and good page ranking can be achieved.

read in details regarding what’s url rewriting here

For now i am using urlrewritingnet  a third party component to rewrite and redirect your urls.

so before proceeding ahead I want to also discuss regarding Url Redirection,

well url redirection is used to redirect an incoming http request from current url to any other url there are basically two types of redirections we used.

a) Http 301 (Permanent Redirect)

b) Http 302 (Temporary Redirect)

suppose some one requests for domanname.com/FirstPage and you want to display SecondPage in place of FirstPage so you can redirect user with any of the above technique.

read here regarding when to use which technique.

For Now let install this component to redirect the urls and also to redirect them.

a) Download the zip from here

b) Extract the zip and reference the urlrewritingnet.urlrewrite.dll to your project.

do the following steps inside web.config file

c) Arrange the config section inside configuration node following way

 




d) Create UrlRewritingnet Node this way



 


Your urls will be mapped here......



e) configure HttpHandler inside system.web which will listen to the requests



 




finally your whole code should look like this way



 

<?xml version="1.0"?>



























































 



Now url rewriting will work..



to give intellisense support include urlrewritingnet.xsd file into your project which is available in the package you downloaded.



here are some cool urls rewrite I done from this configuration



UrlRewrite



In the above image as shown in Image Code 100 if request made for Invoice/(.*) then request is handled by product.aspx page with query string parameter as category and this parameter we are received in code behind and the text is displayed.



In Image Code 101 if request made for Invoice/(.*)/(.*) then in two query string parameters are used one is category (as done before) another is price ,both the parameters are received in code behind.



In Image Code 102 if request made for Invoice/(.*)/(.*)/ then the query string parameters are the same way as done just before this in Image Code 101 and received them in code behind.



this is the code behind of Product.aspx page



 
protected void Page_Load(object sender, EventArgs e)
{
string item = Request.QueryString["Category"];
string price = Request.QueryString["Price"];
lblItem.Text = "You chosen the Category " + item;

if (price != null && price!="")
{
lblItem.Text += " and its price is " + price;

}
}


now what’s the interesting behind these all the mappings ???



The interesting thing which I noticed here is the prioritizing of mappings  same as we have done in asp.net mvc routing so whenever a request is made for the request as virtual url the http handler checks the route which matches first and mapped to corresponding physical url,



so you should always put most-specific-mappings first in the way and then the less-specific mappings as in above we have put invoice(.*)/(.*)/ before invoice(.*)/(.*) because if someone requests for invoice/LG/20000/ and  we’ve mapped the url first this one invoice(.*)/(.*) then at the last the price text will be 20000/ instead of being 20000,same way we put mapping invoice/(.*) after the most-specific mapping invoice/(.*)/(.*).

Response.Write inside gridview with updatepanel

. Tuesday, June 5, 2012
0 comments

Hi guys, if you are using functionality which includes response.write on button click eg : export to pdf or xls etc and its inside gridview and gridview is inside content template of UpdatePanel then response.write will not work.

Why ?

because you’re firing an ajax request (xmlhttprequest) and with response.write it actually refresh the html content which is not possible.

take an example from aspx here :

 




























InvoiceNumber
CustomerName
BillerName













from code above the thing which need to note is this



 




by specifying Postback Trigger Id with Gridview control you can PostBack controls of Gridview.



Happy coding.. Thanks