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

Object Datasource with different select methods

. Sunday, April 1, 2012
0 comments

Hi Guys, I am going to tell you how can we use object datasource with specifying different select method at runtime.

What does Object Datasource Do for Us ?

Object Datasource contains the record set of specified collection and later this can be bind to any data control available like gridview, list view etc.

Following are the few properties which we need to specify when using object datasource

a)Type Name : This is the name of class which method will be binded to the object datasource.

b)Select Method :  Name of the method which will return the returns the collection.

Now lets take a look at the following :

    


its a simple object datasource with set the above properties.



which retrieves all the available biller as datatable from method getall billers.



and on page load I have bind objectdatasource to gridview as follows :



protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindBillerGrid("GetAllBillers", "DataAccess.DALBiller");
}
}

private void BindBillerGrid(string selectmethod,string typename)
{

//bind objDSBiller to GrdVwBiller
GrdVwBiller.DataSource = objDSBiller;
GrdVwBiller.DataBind();

}


Now I want to set a search method in Select Method of ObjDS with some parameters, but before doing this I need to look the sequence diagram of object ds which is as follows :



 



 objectds



so before fetching data from database objectds's Selecting method is called which sets the required parameters for Defined method in property select method for now, and then invokes the specified method and after which objectds’s selected method is invoked.



so I did the following to specify two parameters here for Search Method of biller inside selecting method of objds.



    protected void objDSBiller_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
{
if (objDSBiller.SelectMethod=="SearchBiller")
{
//add parameters to objDSBiller
objDSBiller.SelectParameters.Add(param1);
objDSBiller.SelectParameters.Add(param2);

//set values of parameters
e.InputParameters["columnname"] = ddlBillerColumn.SelectedValue;
e.InputParameters["value"] = txtSearch.Text.Trim();
}
}


param1,param2 are defined in variable region as follows



    #region variables
Parameter param1 = new Parameter("columnname", TypeCode.String);
Parameter param2 = new Parameter("value", TypeCode.String);
#endregion


all the things will work fine except you can get an exception something like



ObjectDataSource 'XXX' could not find a non-generic method 'XXX' that has parameters: XXX, XXX



to resolve this exception we need to look at seqeunce diagram again that after fetching records from db object datasource binds the data with data control like gridview so we can remove the added parameter which were for specified select method as follows :



        //bind objDSBiller to GrdVwBiller
GrdVwBiller.DataSource = objDSBiller;
GrdVwBiller.DataBind();

//remove parameters after objectdatasource has retrieved data.
if (objDSBiller.SelectMethod == "SearchBiller")
{
objDSBiller.SelectParameters.Remove(param1);
objDSBiller.SelectParameters.Remove(param2);
}


so that object datasource’s property select method can have any other method which doesn’t have input parameters and if its having then we can specify and remove them as discussed above.





here is the complete code for the stuff discussed above



public partial class People_Biller_BillerGrid : System.Web.UI.Page
{

#region variables

BLLBiller objBllbiler = new BLLBiller();
Biller biller = new Biller();
Parameter param1 = new Parameter("columnname", TypeCode.String);
Parameter param2 = new Parameter("value", TypeCode.String);

#endregion

#region functions

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindBillerGrid("GetAllBillers", "DataAccess.DALBiller");
}
}

private void BindBillerGrid(string selectmethod,string typename)
{
//set selectmethod,typename of objDSBiller
objDSBiller.SelectMethod = selectmethod;
objDSBiller.TypeName = typename;

//bind objDSBiller to GrdVwBiller
GrdVwBiller.DataSource = objDSBiller;
GrdVwBiller.DataBind();

//remove parameters after objectdatasource has retrieved data.
if (objDSBiller.SelectMethod == "SearchBiller")
{
objDSBiller.SelectParameters.Remove(param1);
objDSBiller.SelectParameters.Remove(param2);
}

}
protected void objDSBiller_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
{
if (objDSBiller.SelectMethod=="SearchBiller")
{
//add parameters to objDSBiller
objDSBiller.SelectParameters.Add(param1);
objDSBiller.SelectParameters.Add(param2);

//set values of parameters
e.InputParameters["columnname"] = ddlBillerColumn.SelectedValue;
e.InputParameters["value"] = txtSearch.Text.Trim();
}
}

protected void GrdVwBiller_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
//change pageindex and bind datasource
GrdVwBiller.PageIndex = e.NewPageIndex;
GrdVwBiller.DataSource = objDSBiller;
GrdVwBiller.DataBind();
}

protected void GrdVwBiller_RowCommand(Object sender, GridViewCommandEventArgs e)
{

if (e.CommandArgument == "Edit")
{
//check if edit is clicked
int billerid;

//get the current row clicked.
GridViewRow row = (GridViewRow)(((Button)e.CommandSource).NamingContainer);

//Get the current row biller id.
billerid = Convert.ToInt32(GrdVwBiller.DataKeys[row.RowIndex].Value);

//redirect user to Edit Biller Page.
Response.Redirect("~/People/Biller/AddModifyBiller.aspx?billerid=" + billerid);
}
else if (e.CommandArgument == "View")
{
//check if edit is clicked
int billerid;

//get the current row clicked.
GridViewRow row = (GridViewRow)(((Button)e.CommandSource).NamingContainer);

//Get the current row biller id.
billerid = Convert.ToInt32(GrdVwBiller.DataKeys[row.RowIndex].Value);

//redirect user to View Biller Page.
Response.Redirect("~/People/Biller/ViewBiller.aspx?billerid=" + billerid);
}

}

protected void btnSearch_Click(object sender, EventArgs e)
{
BindBillerGrid("SearchBiller", "DataAccess.DALBiller");
}
protected void btnClear_Click(object sender, EventArgs e)
{
//clear the search data and redisplay gridbiller
BindBillerGrid("GetAllBillers", "DataAccess.DALBiller");
}

#endregion
}

Difference Between Server.Transfers and Response.Redirect in Asp.net

. Sunday, February 5, 2012
0 comments

HI Guys Today I want to tell you a little bit about these two things

a)Server.Transfer : This method is same as Response.redirect Except This Method is to   transfer user from one page to another page without generating a fresh httprequest,which means that transferring from one to another page is done at server.

Advantage : The Main advantage of using this method is less roundtrip time and hence good performance,because the user is transferred from one page to another page at server side rather than making request first at client side and sending this request to server side.

Disadvantage : The main disadvantage of using this method is url is not changed while sending user from one page to other page so User can be confused some time regarding application behavior.  when I transferred to other page the Url didn't changed but only contents are changed.

Image1 

Image2 b)

Response.Redirect : With Response.redirect method first request in send for requested page at browser's end then the browser send this request to Server,server processes the requested and send httpresponse to browser and hence in the whole process roundtrip time is exceed as compare to Server.Transfer method.

Advantage: The main Advantage of using response.redirect is user can understand the redirect in application from one page to other page as the url change when redirecting the user.

Disadvantage : The disadvantage is rountrip time is more than server.transfer which is not good from performance perspective. you can send all those things with server.transfer which you send with response.redirect like parameteres values and receiveing them in same way as did for response.redirect.

Page1.aspx.cs

    protected void Button1_Click(object sender, EventArgs e)
{
Server.Transfer("~/Page2.aspx?Id=1&Name=Vishal");
}
protected void Button2_Click(object sender, EventArgs e)
{
Response.Redirect("~/Page2.aspx?Id=1&Name=Vishal");
}

Page2.aspx.cs

	lblid.Text = Request.QueryString["Id"];
lblname.Text = Request.QueryString["Name"];

IEnumerable,IList,ICollection in C#

. Friday, January 20, 2012
4 comments

Hello Friends, I am writing blog after really a long time due to my busy work schedule, anyway Today I am going to tell you about these interfaces with their uses.
IEnumerable
Its a core interface which is used to iterate over collection of specified type.Mainly it Implements two methods:
MoveNext: which is of boolean type which tells whether there are more records to move on or not.
GetCurrent: which returns the current record from the collection.
ICollection :Implements IEnumerable
Its a Interface used to Manipulate generic Collections,as it is Implements IEnumerable interface so its obvious that this will also Implements methods MoveNext and GetCurrent,so with this interface you can iterate through collection.
Apart from this its also having its own methods like
Add:Which adds record at the end of collection.
Remove:Removes Specified Item from collection.
Contains:Its a boolean type method which tells whether collection contains the specified item or Not.
I will post code later to explain something tricky thing in this hierarchy.

class Collection
{
static void Main(string[] args)
{
//declare array
string[] arystr = new string[] { "Ajay", "Anil", "Ravi", "Vishal", "Ram" };
//Check for IEnumerable
IEnumerable enumstr = from record in arystr select record;
Console.WriteLine("Start for Enumerable");
foreach (string name in enumstr)
{
Console.WriteLine("Names are {0}", name);
}
Console.WriteLine("Ends for Enumerable");

//Check for IList
IList Liststr = (from record in arystr select record).ToList();
Console.WriteLine("Start for List");
Liststr.Add("Rakesh");
foreach (string name in Liststr)
{
Console.WriteLine("Names are {0}", name);

}
Console.WriteLine("Ends for List");

//Check for ICollection
ICollection Collectionstr = (from record in arystr select record).ToList();
Console.WriteLine("Start for Collection");

Console.Write(Collectionstr.Contains("Ram"));
foreach (string name in Collectionstr)
{
Console.WriteLine("Names are {0}", name);

}
Console.WriteLine("Ends for Collection");
Console.Read();
}
}


IList


Interface which is collection of Non-generic type objects and can be accessed by index. Its the Interface which Implements two interfaces ICollection and IEnumerable.so its obvious that this will Implements the methods of the both the interfaces.Its own methods are like


Insert: Insert the given item at specified Index.


RemoveAt:Removes the Item from Specified Index.


IndexOf : retrieves the item from specified Index.


Now Lets take and Example


When I use IL to see the compilation of above Code I get the following:


 image


image




image


image





This was for IEnumerable Which Implements two basic methods MoveNext and GetCurrent.


image


image


image


 image


 image


From IL its very clear that IList also Implements Interface IEnumerable so when I receive array of string inside IList it internally uses movenext and GetCurrent these two methods to iterate over records,and one more is the method Add,which is because its also Implements ICollection.


image


  image


image


ICollection also Implements IEnumerable but I didn’t added IL code for this, only you can see for ICollection is Contains method which is a boolean type as you can see from IL Output.


So among IList,ICollection,IEnumerable the hierarchy is like


IList Implements ICollection Implements IEnumerable.


hope you enjoyed this article. Thanks

uses of success and complete events in Jquery Ajax

. Wednesday, December 14, 2011
0 comments

Hello Friends,after a long time I'm writing this post.well everyone of us uses Ajax and there are two Events in this

Success : this event is called when your request get succeed. else this does not call.

Complete: doesn't matter whether your request get succeed or not, this event always called,and you can   check various http status code like 200 for OK,501 for Internal Server Error, 400 bad ,404
page not found etc.inside this event for the response for xmlhttprequest.


Which event fires first.?

between success and complete event success event fires before complete event. for details about the sequence of these event check on the official site of jquery ajax here

here is a simple code snippet







the ajax is called when GetQoute form is submitted and receives the httpxmlresponse which later displayed inside the various div's in success event. and if status code received is 200 then success alert message shown in complete event.

What the trick inside this ?

well, as success is fired before complete event we can get response data only in success event and not in complete event because this is useful only for check response status. in the above code,data corresponding to openingPrice,Ratings are displayed but not displayed for closingPrice because its inside complete event.

Hope you enjoyed this.Thanks

Really a Great book by Mr steve sanderson for Asp.net MVC

. Tuesday, December 13, 2011
0 comments

Download this Ebook from Here.
also follow steve sanderson for asp.net mvc updates here

Json Post and Get in Asp.net MVC

. Thursday, October 13, 2011
0 comments



What is Json ?


Json stands for javascript object notation which is used to interchange data between various languages a typical example is any server side language like c#,vb.net with Javascript.


How to use Json in MVC ?

well,whenever you make an Ajax Call to retrieve some sort of data then the best format to retrieve data is Json which is string:value pair.
get more about json here

Now lets create a Html to Make an Ajax call and retrieve Json.

What time is it?

<% using (Ajax.BeginForm("GetTime", new AjaxOptions { UpdateTargetId = "myResults" })) { %> Show me the time in: <% } %>
Results will appear here
This page was generated at <%= DateTime.UtcNow.ToString("h:MM:ss tt") %> (UTC)
Confirmation Dialog..

which looks like as follows :






















Now my Javascript with making ajax call is as follows :



The Main thing for this post is $.Ajax with Get and Post xmlHttpRequests.
on successful response its get displayed else response received with an Error like internal server error (500) etc.

following action receives the submit for this page with an Ajax Call.

public JsonResult GetTime(string zone)
        {
            Person person = new Person();
            person.Name = "Vishal";
            person.Address = "Indore";
            return Json(person);
        }

Which returns the data in Json Format.


When I use xmlhttprequest Post in $.Ajax function of Jquery I receive the following Response.






and When I use xmlhttprequest type Get in $.Ajax function nothing is updated in Red dotted area and I receive internal server Error (500) with following Error Message as Response.

This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet.

Its because Json only allow Json Post(as its more secure) Request but deny Get request because confidential information can not be retrieve using get request.

but if you aware its risk and want to allow Get request for Json you can do this as follows :
return Json(person,JsonRequestBehavior.AllowGet);

in this way you can retrieve data from Get Request but its won't be secure anymore as anyone can now access this infromation by simply sending request using url.

client side validation in Asp.net mvc 2 and mvc 3

. Monday, October 3, 2011
0 comments

Hello Guys,

we all are aware about how do we validate user input for model in asp.net mvc using server side validation.
but this feature is also applicable for client side as well. its a pretty thing to hear..
So what will do the client side validation if Server side validation already over there?
well this give you very much facility as you don't need to make the whole page refresh just put some javascript libraries and they will do their job by making partial page refresh and without posting your page back.
So with this technique of validation we can validate user input without making page to post back every time and displaying the validation after the complete page Call.

Lets have a look for this pretty thing.

a)First I create a model which will need to validate for user input in our View.
 public class Person
    {
        public int Id { get; set; }

        [Required(ErrorMessage = "First Name is required")]
        [StringLength(10, ErrorMessage = "First Name max length is 10")]
        public string FirstName { get; set; }
    
        [Required(ErrorMessage = "Last Name is required")]
        [StringLength(10, ErrorMessage = "Last Name max length is 10")]
        public string LastName { get; set; }
    
        [Required(ErrorMessage = "Email is required")]
        [RegularExpression(@"^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$", ErrorMessage = "Email Format is wrong")]
        public string Email { get; set; }
    }

b) create an action method in controller which will used to render View later for this model.
       
        public ActionResult Person()
          {
                return View();
          }

c)Now just need to reference some of the js libraries for client side validation to work,so for this 
  reference following js which are already in script folder into your Master Page.
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>


    Person


    

Person

<%Html.EnableClientValidation(); %> <% using (Html.BeginForm()) { %>

<%=Html.ValidationSummary(true) %>

Id:

<%=Html.TextBoxFor(x=>x.Id) %>
<%=Html.ValidationMessageFor(x=>x.Id)%>

FirstName;

<%=Html.TextBoxFor(x=>x.FirstName) %>
<%=Html.ValidationMessageFor(x=>x.FirstName)%>

LastName:

<%=Html.TextBoxFor(x=>x.LastName) %>
<%=Html.ValidationMessageFor(x=>x.LastName)%>

Email:

<%=Html.TextBoxFor(x=>x.Email) %>
<%=Html.ValidationMessageFor(x=>x.Email)%>


<%} %>


Here thing to notice is that everything is same as Server Side Validation Except one new thing is added which is
<%Html.EnableClientValidation(); %>

Which Causes the Client Side Validation.
The above scenario will look like as follows :
When someone enter the wrong value for field the validation is displayed.

          
           
 



















Now when someone enters the correct value for specified field the validation removes without causing the whole page refresh.



























Client Side Validation in Asp.net MVC 3 :

All the things are same as done with mvc 2 except the following :
a)Add the appropriate references in the master page as follows :



 

Here a New thing to note is Unobrustive Javascript library which is generally writing Html and Javascript separately.

you also need to set Unobrustive js and clientside validation in Web.config file
as follows :


 
        
     
 

both the options need to set true if you want client side validation in your application.

Hope you Enjoyed this article.

In vs Exists in Sql Server

. Monday, September 19, 2011
0 comments

Hi Guys you've used lots of time In and Exists in Sql and they look almost same
but there is difference between both of these.

Suppose you have two tables as follows :

a)tbl_employee(id,emp_name,comp_id)
b)tbl_company(id,comp_name)

Now if you fire following query

select * from tbl_employee where comp_id in (select id from tbl_company)

by the way this query is executes in the following way :

select * from tbl_employee,(select distinct(id) from tbl_company) tbl_company
where tbl_employee.comp_id=tbl_company.id

What's the scenario Here:
a)the indexed result from tbl_employee,which is fast in terms of time.
b)a full scan through tbl_company for and selecting distinct of id from this,
for matching records in where condition.

Where's the IN is suitable:
well, in a scenario where your subquery having less record then IN suitable in that
case,because you main query have indexed and only need to have matched with subquery
while subquery need to have a full scan for each matching id with where condition.

Now if you fire following query

select * from tbl_employee where exists(select null from tbl_company where id=tbl_employee.comp_id)


query is executes in the following way :

for emp in ( select * from tbl_employee )
loop
if ( exists ( select null from tbl_company where id = emp.comp_id )
then
output the record
end if
end loop

What's the scenario Here:
a)indexed on tbl_employee which gives emp rowset.
b)for each emp rowset we need to check weather if exists is true or false if so output the record.


Where's the Exists is suitable:
well, in a scenario where your subquery having Huge records then Exists suitable ,because you only need to check with subquery that if the above record id exist or not and a full scan is made with main query for each rowset.









Display jquery dialog when Ajax calls in Asp.net MVC

. Wednesday, September 14, 2011
0 comments

If you want to display jquery dialog box when you post using Ajax there are various Jquery dialog available you can check them here.
For Now I am going to tell you how can you use jquery confirmation dialog when click on button which post to action in asp.net mvc using Ajax.

First We need to include neccessary libraries.
<pre name="code" class="js">
<script src="../../Scripts/jquery-1.6.2.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.bgiframe-2.1.2.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.ui.core.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.ui.widget.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.ui.mouse.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.ui.button.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.ui.draggable.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.ui.position.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.ui.resizable.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.ui.dialog.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.effects.core.js" type="text/javascript"></script>
</pre>
these are the necessary script need to include for calling jquery confirmation dialog.
in addition to this I added two css files to look dialog pretty.

<link rel="stylesheet" href="../../Content/demos.css">
<link rel="stylesheet" href="../../Content/jquery.ui.all.css">

after this we need to set Ajax in Asp.net MVC.

as we know Ajax is used for partial page refresh,which uses javascript.microsoft provides two beautiful js for ajax just include them in your page as follows:

<script src="../../Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="../../Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>

and for calling ajax using the following ajax extension methods with a dropdown and submit button to post to action using Ajax.
<% using(Ajax.BeginForm("GetTime",
new AjaxOptions { UpdateTargetId = "myResults" })) { %>
<p>
Show me the time in:
<select name="zone" id="zone">
<option value="utc">UTC</option>
<option value="bst">BST</option>
<option value="mdt">MDT</option>
</select>
<input type="submit" value="Go"  id="create-user"/>
</p>
<% } %>

<div id="myResults" style="border: 2px dotted red; padding: .5em;">
Results will appear here
</div>

in the above code when the submit is clicked an ajax call is made for the associated action which returns the response as string which will update the text inside div myResult.

for this my action is as follows:

 public ActionResult GetTime(string zone)
{
DateTime time = DateTime.UtcNow.AddHours(1);
if (Request.IsAjaxRequest())
{
// Produce a fragment of HTML
string fragment = string.Format(
"
The time in {0} is {1:h:MM:ss tt}
", zone.ToUpper(),time); return Content(fragment); } else { // Produce a complete HTML page return View(time); } }
well we need to write a little bit of script so that we can detect when submit button is clicked then we can call jquery to display confirmation dialog.  <script type="text/javascript">     var zone;     $(function() {         // a workaround for a flaw in the demo system (http://dev.jqueryui.com/ticket/4375), ignore!         $("#dialog:ui-dialog").dialog("destroy");  //display the dialog-form div as confirmation dialog.         $("#dialog-form").dialog({             autoOpen: false,             height: 300,             width: 350,             resizable: false,             modal: true,             closeOnEscape: true,             draggable: false,             show: 'slide',             stack: true,             buttons: { //the confirmation dialog will contain two button one is submit and other is cancel,if someone clicks on submit then will we post the data to specified url(in this case our action) and then receive the response and update the text inside myResult div.                 Submit: function() {                     var url = "/Home/GetTime/" + zone;                     $.post(url, function(data) {                         $('#myResults').html(data);                                            });                     $(this).dialog("close");                 },                 Cancel: function() {                     $(this).dialog("close");                 }             },             close: function() {             }         }); //this will use to detect wether "create-user" button has been clicked if so we need to display the div with Id "dialog-form"         $("#create-user")             .button()             .click(function() {                 zone = $("#zone").val();                 $("#dialog-form").dialog("open");                 return false;             });     });     </script> Here is the final screenshot which will appear when you click on submit button
















so when you click on Go button the confirmation dialog opens and when click on submit the content inside myresult div is updated with response given by the action using Ajax. Hope guys you enjoyed this article.

Unable to connect to Asp.Net Development Server

. Thursday, September 8, 2011
0 comments

Hi Guys, Cause of this problem is that your web server file of asp.net is corrupted.

Follow these steps to resolve this problem

1)download this file from here.


2)after downloading & unzipping ,overwrite this with existing corrupt webdev.webserver (an exe) file which is located at :
{your drive}:\Program Files\Common Files\Microsoft Shared\DevServer\9.0

XSS Problem with asp.net or in asp.net mvc

. Friday, September 2, 2011
0 comments

Hi Friends,

If you receive message like this :


A potentially dangerous Request.Form value was detected from the client


Whenever you write html or other scripting inside textbox or other html input field & when the form get posted on server the script is detected as security vulnerability(commonly known as XSS) and html inbuilt validation in applied on such scripts hence this message get generated which avoids script to run on server side.

but sometimes this could also be possible that you want to post such kind of script through input box.

so you can apply following things to Page directive in asp.net


validateRequest="false"


if you are using asp.net mvc then you can do by writing ValidateInput Attribute to "False" before your action as follows :


ValidateInput(false)
you action goes here...


also if you are using 3.5 or above framework then you need to specify version 2.0 in httpruntime inside web.config as follows:

<system.web>
    <httpruntime requestvalidationmode="2.0">
    </httpruntime>
</system.web>





dropdown list with datepicker in jquery

. Tuesday, August 30, 2011
0 comments

Hi Guys,
If you want to change drop down list values for month,day and year for chosen date from datepicket of jquery,
you can achieve this easily.

Here are the steps involve to do this

1) add the neccessary js and css files.
 in my case this was as follows :
<link rel="stylesheet" href="../../themes/base/jquery.ui.all.css">
    <script src="../../jquery-1.6.2.js"></script>
    <script src="../../ui/jquery.ui.core.js"></script>
    <script src="../../ui/jquery.ui.widget.js"></script>
    <script src="../../ui/jquery.ui.datepicker.js"></script>
    <link rel="stylesheet" href="../demos.css"> 

2) now write html for all these three drop downs in my case this was following :
  
month:
  <select id="Month">
  <option value="1">Jan</option>
  <option value="2">Feb</option>
  <option value="3">March</option>
  <option value="4">April</option>
  <option value="5">May</option>
  <option value="6">June</option>
  <option value="7">July</option>
  <option value="8">Aug</option>
  </select>

  Day:
  <select id="Day">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  and so on ...
  </select>

  Year:
  <select id="Year">
  <option value="2010">2010</option>
  <option value="2011">2011</option>
  <option value="2012">2012</option>
  <option value="2013">2013</option>
  <option value="2014">2014</option>
  <option value="2015">2015</option>
  <option value="2016">2016</option>
  <option value="2017">2017</option>
  </select>

3) now what we want to do is to change the value of all the three dropdowns whenever datepicket date changes to do this write the following in script section.

<script>
   $(function() {
        $( "#datepicker" ).datepicker({
            onSelect: function(dateText, inst) {
                    var startDate = new Date(dateText);
                    var selDay = startDate.getDate();
                    var selmonth=startDate.getMonth()+1;
                    var selyear=startDate.getFullYear();
                    $("#Day").val(selDay);
                    $("#Month").val(selmonth);
                    $("#Year").val(selyear);
                 }

        });
    });
</script>  

what we did here ....
first we read the selected date from datepicket and then change the selected value of all the three dropdowns accordingly so finally selected index will also changes and you will see changed date every time you change the value of datepicker.



Value Type Vs Reference Type a Simple Practical Study -c#

. Wednesday, August 24, 2011
1 comments

Hi Guys, Want to tell you today regarding some of my good experience about Value Type vs Reference Type.

Value Type :
Value Type is a memory allocation technique in which memory allocated to a separate memory block which finally get "pushed onto Stack.

Basic Example : Structure.
Type of Memory Allocation :Static

Reference Type 
Reference Type is another memory allocation technique is a memory management technique in which two things are comes into picture :
1.Stack
   used to store reference variable with its values.
2.Heap
   used to store object variable which stores the actual content.

Basic Example : Class
Type of Memory Allocation : Dynamic.

Now lets see this by an Example

1. I created one structure and one class as follows :


struct Strct
    {
        public int x, y;
    }

class Cls
    {
        public int p, q;
    }

And a Main class to call them.


 class Program
    {
        static void Main(string[] args)
        {
         
         }
   }


Now onwards I'll tell you the programming logic behind them

Scenario 1:

lets create one Instance for each of them as follows :
            Strct MainInstance = new Strct();

            Cls MainObject=new  Cls();
allocate some value for each of them as follows :
            MainInstance.x = 3;
            MainInstance.y = 4;
            MainObject.p = 3;
            MainObject.q = 4;

Now I Invoke a Test Function to check the actual situation

 Test(MainInstance,MainObject);

and This Test Function Defined as follows :


 public static void Test(ref Strct tmpstrc,ref Cls tmpcls)
        {
            tmpstrc.x = 1;
            tmpstrc.y = 2;
            tmpcls.p = 1;
            tmpcls.q = 2;
         
        }

My final code is something like this inside main


     static void Main(string[] args)
        {
            Strct MainInstance = new Strct();
            Cls MainObject=new  Cls();
            MainInstance.x = 3;
            MainInstance.y = 4;
            MainObject.p = 3;
            MainObject.q = 4;
            Test(MainInstance,MainObject);
            Console.Write("Value of Instances are {0}{1}", MainInstance.x, MainInstance.y);
            Console.Write("\n");
            Console.Write("Value of Objects are {0}{1}", MainObject.p, MainObject.q);
            Console.Read();
        }

So Guys What the Value you expect here ....

Output
Value of Instances are 3 4
Value of Objects are  1 2

B'caz Structure(Value Type) stores values separately for each variable where as Class(ReferenceType) there is allocated object reference variable which points to object of class.

so in this scenario two separate variables are created for Structure
MainInstance(3,4)
tmpstrc(1,2)

and two reference variables which references to Class
MainObject(3,4)
tmpcls(1,2)

but here we actually copied the reference of tmpcls to MainObject so this also holds the same reference now.

Scenario 2:

now I made a little bit changes inside Test function.


public static void Test(Strct tmpstrc,Cls tmpcls)
        {
              tmpcls=null;
        }


Well, what the output you expect now.

its


Value of Instances are 3 4
Value of Objects are  3 4

For Instance case its very clear b'caz each time a separate variable holds the values.
Incase of Objects this display 3 4 b'caz this time reference which is copied is null so the actual reference will works for MainObject reference variable and this will show those values which were allocated earlier.


Scenario 3: 

the last and the most important situation here occurs when we use "ref" keyword.

look at Test function Declaration
Test(ref MainInstance,ref MainObject);

and its Declaration


public static void Test(ref Strct tmpstrc,ref Cls tmpcls)
        {
            Console.Write("Copied Object{0}{1}", tmpcls.p, tmpcls.q);
            Console.Write("\n");
            Console.Write("Copied Instance{0}{1}", tmpstrc.x, tmpstrc.y);
            Console.Write("\n");
            tmpstrc.x = 1;
            tmpstrc.y = 2;
            tmpcls.p = 1;
            tmpcls.q = 2;
        }


Now What the output you expect


 Copied Object 3 4
 Copied Instance 3 4
 Value of Instances are 1 2
 Value of Objects are  1 2

In case of memory variable (Value Type) we have Interchange each values with each other.
eg: MainInstance now referes to tmpstrc and vice-versa.
In case of reference variable(Reference Type) we have Interchange their references with each other.
eg : MainObject now having reference of tmpcls and vice-versa.

but wait a minute If I set the following :
   tmpcls=null;
inside our Test Function defination then what will happend ?

This time this will executes upto displaying memory variable MainInstance but when the execution comes at
Console.Write("Value of Objects are {0}{1}", MainObject.p, MainObject.q);

this throws Null reference exception b'caz this time reference hold by MainObject(which was hold by tmpcls before sometime is null) and we are trying to display its values so this exception will be generated.

so Guys !!! Hope you enjoyed this article .catch you soon with some other stuff.