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.