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.










Restful urls in asp.net mvc with simple steps

. Monday, August 22, 2011
0 comments

Hi Friends,

What is REST ?
Rest is a principle followed by nowadays application architecture like MVC. its stands for representational state transfer which means
a)URL should be Identity to Operation which is Performing in Application.
b)URL should be in Human readable format so that anyone can get the idea of operation easily.

Example of Restful Urls 


Basically there are verbs associated with each operation for a particular url

eg:
I am going to explain about my practical example nowonwards which is really easy to understand.
Suppose I am Having a Controller Named Server.
Now for there could be following Scenario :

Server/ServerList   //displays List of all available servers.

Server/id/ClientList //displays List of all available clients for a particular server using its id i.e. serverid.

Server/id/DeleteServer //deletes a particular server using its id.

Server/id/DeleteClient //deletes all those clients which are associated with server for its id.

Here is how my controller is looking for all its actions with parameters,verbs they are accepting.



















Now For these action to execute we need to add views.

I used Model binding concept of Asp.net MVC to do this task and bind ServerList and ClientList with
IEnumerable<T> and AddServer/AddClient with <T>

for ServerList  Iterate through records as follows :

















same Model binding for ClientList View Page.

For AddServer Bind view with <T> as follows :

















same done for AddClient.

Benefit of doing so is you  need not to pass each parameter in function when POST is used to Create new Item,and need not to add namespace for particular model and add its fields in view,Just Iterate through ViewData.Model.

You are almost done with Rest Now Take a look into one of the great feature of MVC Architecture
Routing 
you need to specify route for above urls.

so I added the following routing in my global.asax file.


 routes.MapRoute(
           "Default", // Route name
           "Server/{id}/{action}", // URL with parameters
           new { controller = "Server",id=UrlParameter.Optional ,action = "ServerLists" } // Parameter defaults
       );

by doing so this will accepts all request for above urls.

Trick with routing : Specify More Specific Routes above Less Specific

consider a scenario : 

Suppose I am having a doubt in above urls and I added a route for AddServer,AddClient as follows :

  routes.MapRoute(
           "CustomRouteFirst", // Route name
           "Server{action}", // URL with parameters
           new { controller = "Server",action = "AddServer" } // Parameter defaults
       );
now this will match Server/AddServer and Server/AddClient but what about my other routes ?
my others urls will be treated according to this routes and consider my DeleteServer Url would be now.
Server/DeleteServer?Id=(myserverid)
which i really don't want. I need this to be Server/id/DeleteServer.

Consider another example : 

Take a look into this route first :

//[Priority]:First


routes.MapRoute(
           "SpecialRoute", // Route name
           "Category/{categorytype}", // URL with parameters
           new { controller = "Product",action = "List" } // Parameter defaults
       );

// [Priority]:Second

routes.MapRoute(
           "CustomRouteSecond", // Route name
           "{controller}/{action}/{id}", // URL with parameters
           new { controller = "Product",action = "Index",id=UrlParameter.Option } // Parameter defaults
       );


so when one request for  Category/mobilephone //this will display all mobile phone lists.
and when someone request for Product/id/Delete //in this case First route won't match and hence its comes to down for second route and transfer the state to appropriate action.

 if you swap these routes priorities  then what would be scenario.

a)for Product/id/Delete url this will go for appropriate action.
b)for Category/mobilephone this will again match with the first route(ie. generic route) and trying to go for appropriate action which is not there & hence page not found error message will appear.
Hope ! you enjoyed this article.

Connect Nokia C2-01 as USB Modem

. Wednesday, August 17, 2011
2 comments

Hi Friends, If you stuck in issue with connection Nokia C2-01 as USB Modem,I'll provide very simple steps to configure this task.

1)Download Nokia Ovi Suite 3.1.1.85
(hardware requirement displayed there is just a enclosure,just ensure that you have sufficient space in your operating system drive.)

2)After Successfull Installation,Connect Nokia C2-01 from USB Cable.
(this will detects your phone as new hardware device)

3)Before Connecting to internet please do check following things.
   a)you have set Access point in both of the side on your mobile phone and on Software on PC
     (as in my case this was bsnlnet so I used same for both of the sides.)
     i)for mobile device its inside settings->configuration->Preferred access point.
     ii)for Ovi Suite on PC its inside Tools->InternetConnection->Choose Manual and Enter AccessPoint as  
       bsnlnet
   b)leave blank for username and password,this won't required.
   
4)Connect using Connect Now Link,and enjoy 3G speed on your

asp.net vs asp.net mvc

. Sunday, July 10, 2011
0 comments

Difference between Asp.net and Asp.net mvc
HI guys, Today I will discuss some of the major differences between asp.net and asp.net mvc

1)in asp.net each control on page is associated with its code behind so all time you have to
  take care of its code behind with UI,whereas in asp.net MVC view is completely independent from
  its source code so view can be implemented separately this thing known as soc(separation of concerns).

2)whenever httprequest is made for asp.net it passes through its UI and then to code behind( ie .aspx then .aspx.cs)
  whereas in asp.net mvc each request first passes through controller and then its associated action's view loaded.

3)asp.net is good to develop applications which uses lots of asp.net controls(easily drag & drop) whereas asp.net MVC
  separates each implementation logic so its good for large apps in which each developer can work on model,view,controller
  separately.

4)asp.net is fast to develop but less in terms of testability and maintainability where as mvc requires time to develop
  its apps but very much better in testability and maintainability.

5)asp.net is good to develop small and middle level apps whereas asp.net MVC is made for large aps with higher level of implementation
  logic. 

State Management Technique-View State

. Monday, May 16, 2011
0 comments


Hi Guys today i am going to tell you about view state.

What is a View State in asp.net ?

View state is a mechanism to preserve data across postbacks.

where Viewstate resides ? 

view state resides within a page in hidden field with value equals to _VIEW_STATE,and its in encoded string.
whenever you request for a page the web server proceeds the request and send response with aspx page and during this process view state is view state decoded and sent to client's browser.

why to use a view state ? 

it want to preserve your information on certain postback,then you need to use viewstate.let me explain how?suppose you bind a drop down with items fetched from database.Now if you do this activity on each time when the page is post back means on each fresh http request then you will slow down your page speed because each time you will interact with db and retrieve all records and bind them.Instead of doing so,just bind the records for the first httprequest and then for all other request use view state of this instead.you can do this as follows:

if (!Page.IsPostBack)
{

//your db stuff here.

}

now if your page is post back again & again you don't need to perform db stuff.

enableviewstate ? in page directive if you set this attribute to true then viewstate will be enabled for whole page,for control specific you can change this to false or true.

What is the role of enableViewStateMac ? well MAC  tends to message authentication code,lets understand use of enableviewstateMac with an example,suppose you have filled a form and its asked for ccnumber,if someone has enabled viewstate on this field and you fill the form in a usual way. after filling up form and checkout but someone decoded this viewstate string and fill the form again,now he is having you creditcard number because he decoded the string,now other field are set to his own. now message authentication code compare both of the string and then if the difference found(as in our case) then all the viewstate is replaced with the older one and this attach will not affect the transaction.

Can we allow viewstate to be encrypted ? yes. setting validation to 3DES(Encryption algo.)  in machine key(inside system.web element in web.config) you can allow you view state to be encrypted.benefit of this is that this won't be decrypted without decryption key.

an example of machine key

<machine key validation="3DES|SHA1|MD5" decryption key=.... validation key=..... />
validation key is used to validate the view state and determines is view state has been tempered.

  • (SHA1 and MD5 are encoding algo. but SHA1 generates long encoded string so more preferable.)


Persistent Machine key : suppose you are in a web farm scenario where apps is maintained on more than one server.suppose there are two server A,B. now user are not aware of whether this response is coming from web server A or B. so when ViewState is decrypted on server A its served to user but when some part of apps served from server B the dynamically generated decryption key/validation key will not decrypt/validate the view state and hence ViewState_Error will be occur. to avoid this error use a persistent machine key.

Extension methods -asp.net mvc

. Wednesday, May 4, 2011
0 comments


Extension Methods in asp.net mvc

why to use extension method ?

well, in a simple statement I would say extension methods are used to get rid of writing html source code for views in asp.net mvc

let's take an example

suppose you are building a html table with several rows and cols in view
eg:

<table><tr><td>...</td></tr></table>
now you need to use table structure in various places in your application so without re writing this just create one extension method and put you structure over there
like this :

namespace ExtensionMethods.Common
{
public static class Helpers
    {

        public static string table(this HtmlHelper helper, string itemfirst, string itemsecond)
        {
            return String.Format("<table><tr><td>{0}</td></tr><tr><td>{1}</td></tr></table>", itemfirst, itemsecond);
        }
      
}
}
note:static class only can have static functions.
so now when you implement table structure into your view,you just need to add appropriate namespace for my case this was
"ExtensionMethods.Common".

as shown below :

















Now whenever you need this structure just imports the appropriate namespace and then call extension method by passing parameters within it.

and you will see items witin table structure in your application.


outputcaching with authorize filter

.
0 comments


Hi guys,after a long time I am back to blogging,today I am going to explain about how to use outputcaching with authorizefilter.

for outputcaching you can refer by previous blog.
(outputcaching is also a kind of filter)

Filters in asp.net mvc : 

Authorize filter
Raises before any action execute and authorize the current user.
Action filter
two method overridden from actionfilterattribute class
onactionexecuting : before action get executed.
onactionexecuted : after action get executed.
Result Filter
two method overriden from actionfilterattribute class
onresultexecuting : before result get executed,
eg: when you return view() from any action this method executed before this.
onresultexecuted : after result get executed.

Exception filter
whenever action throws any exception.
class for this filter is HandleErrorAttribute.

Note: controller inherited from controllerbase class in which it implements filter attribute so ultimately your controller can also implement these attributes.
Eg:

[Athorize]
your action..

Using outputcaching with Authorize filter :

Problem : 

if we use both of these filters in the worst case the unauthorize users even can view the cached content of authorize users,to avoid we need to use a custom class which

implements authorizefilterattribute class.

public class EnhancedAuthorizeAttribute : AuthorizeAttribute
{
public bool AlwaysAllowLocalRequests = false;
protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext)
{
if (AlwaysAllowLocalRequests && httpContext.Request.IsLocal)
return true;
// Fall back on normal [Authorize] behavior
return base.AuthorizeCore(httpContext);
}
}

[EnhancedAuthorize(Roles = "admin", AlwaysAllowLocalRequests = true)]
Now, this will grant login only for admin roles and not to any other role.

but I achieve this wtih athorize attribute

eg:
 [Authorize(Roles="admin")]
 [OutputCache(Duration=30,VaryByParam="None")]

note : order is a property of filter base class which defines the order of filter execution but by default filter are put on stack for execution which means the last one will be executed first.

using delegates and events in c#

. Thursday, April 7, 2011
3 comments


What is a delegate ? 
Delegate is a function pointer means it can point to those function which are having identical signature with delegate.
you can also call delegate as a interface of methods as this acts same as interface in c# but that implemented for classes and this is implemented for methods.

Process to create a delegate:
1)declaration
2)instantiation
3)invocation

Example :

Consider the following code:

  delegate string StrDelegate();//declaration
   public class Custom
    {
        public string strmethod()
        {
            return "This is string ";
        }
    }
    class Program
        {
        static void Main(string[] args)
        {
            Custom objcustom = new Custom();
            StrDelegate strdelegate = new  StrDelegate(objcustom.strmethod); //instantiation
            string message=strdelegate(); //invocation
            Console.Write(message);
            Console.Read();
        }
       }
so what happened in this above code,well first we define a delegate with its signature,in this case its return type is string and no arguments. then we create instance of delegate which is strdelegate now this can point to (reference to) all those function which having same signature as in our case function is strmethod() and at the last we invoke this and receive this in message.

Advantages:
The main advantage of delegate is multi cast.
you can call number of function with matching singature with single instance of delegate but point to remember is that its return type should be void because there are many

methods and if we pass return type then each one will return some value and finally delegate instance will hold the last one method's value.

example

in our previous example i added the following :

        public void strmethodmulticast()
        {
           console.write("This is string multicast");

        }

in set of methods and

StrDelegate strdelegate = null;
            strdelegate += new StrDelegate(objcustom.strmethod);
            strdelegate += new StrDelegate(objcustom.strmethodmulticast);

this in Static Void Main

also changed the return type of delegate to void.


What are events 
event is a way for a class to provide notifications to clients of that class when some interesting thing happens to an object of that class.
you can also consider events as variable type of delegates ? why lets look at event declaration.

public event StrDelegate customevent;

Just need to put event keyword before delegate name and your event created.
events are handled by delegates which are called event handlers.

consider the following code:

 btnsubmit.Click+=new EventHandler(custommethod);

I created a button on form and its object 'btnsubmit' now avaiable on code behind as you know, now when click event raises in above it is being handled by EventHandler
delegate and method  'custommethod'  do the desire operation which is having the same signature as in EventHandler delegate (object sender//to raise event,Eventargs e// to receive other information)

public void custommethod(object sender, EventArgs e)
    {
        txtsubmit.Text = "This is called on button click";

    }

and hence on click event of button the above method is called which changes the text of txtsubmit.

dropdown not working in ie7 and ie8

. Tuesday, April 5, 2011
0 comments

If you have created dropdownlist and either its not visible or not visible onchange event of other dropdown
Then one of possible solution this is as follows:

Possible Cause :
if you use firebug and see html for dropdown you will notice that 'option' is not well formed in html for this dropdown.

One of Solution to Resolve this Problem:

If you have used something like this

for (i = 1; i <= day_length; i++)
{

doc.innerHTML += "<OPTION value=\"" + i + "\">" + i + "</OPTION>";
}
and adding items to dropdown (doc) dynamically with some values(eg: i in this case) replace this with


addOption(doc, i, i);

function addOption(selectbox,text,value )
{
var optn = document.createElement("OPTION");
optn.text = text;
optn.value = value;
selectbox.options.add(optn);
}

this add option adds all of those values which you want (eg: i ) and this will event work in ie 7 ,ie8.

It worked for me hope same would for you..
Cheers...

Error 3205 Too Many Backup Devices Specified.

. Thursday, March 31, 2011
0 comments

Cause:
This error occured because of you sqlserver is not compatiable with current backup version



Solution:

1)first run SELECT @@version and find the version

2)exit from current sqlserver and connect with other server for which your backup file(.bak) is compatiable.

RouteExistingFiles and IgnoreRoute in asp.net mvc

. Thursday, March 24, 2011
0 comments


How to Use RouteExistingFile and IgnoreRoute in asp.net mvc.

RouteExistingFile is a property of Routecollection class Which is True or false.
eg: routes.RouteExistingFiles = true

as you can see all css have been acting as route and hence no longer available for Home/
whenever you write this it routes the files present on your harddisk which in turns acts as a route.
for example if you have css in /content/file.css and you make RouteExistingFiles true then it will match
{controller}/{action} url for file.css and this will no longer available for existing pages.

Only two cases are possible to get file.css
1)if you directly hit that file eg:/content/file.css
2)if you use routes.Ignore route.

Case 1 is quite simple

Case 2 routes.IgnoreRoute is and extended method which accepts routes to be ignored and below will
ignore the route matching for css.
eg:
routes.IgnoreRoute("{Content}/{file.css}")
as shown in above figure now those files present on hard drive not acting as route and available for pages.

Thanks friends see you soon

Avoid css,Html errors-Asp.net

. Sunday, March 13, 2011
0 comments

Do you receiving css+ html errors when compiling asp.net application,and want to remove these validation errors its quite easy do following:

Goto Tools>options>css specific now uncheck the show errors
&      Tools>options>validations uncheck show errors for (netscape7,opera7,ie6) from dropdown.


Thanks

Interesting role of Polymorphism,Interface in C#

. Wednesday, February 23, 2011
2 comments

 Hi Guys This post is about implementing poylmorphism in c# and role of interface in c#

Polymorphism

Why?

Lets see by an example

public class Abstract
    {
    public  void  myfunction()
    {
    Console.Write("This is Abstract");
    }
  
}
 public class Inherited : Abstract
    {
        public override void myfunction()
        {
        Console.Write("This is Function Class");  
        }
}

 class Program
    {  
    
        static void Main(string[] args)
        {
            Abstract Abs = new Abstract();
            Abs = new Inherited();
            Abs.myfunction();
            Console.Read();
          }
  }

Now when you call this you will see the following  Output
"This is Function Class"

But with a warning:
Warning 1
'TestConsole.Function.myfunction()' hides inherited
member 'TestConsole.Abstract.myfunction()'. Use the
new keyword if hiding was intended. C:\Documents
and Settings\vivek\My Documents\Visual Studio
2008\Projects\TestConsole\TestConsole\Program.cs
23 22 TestConsole

which stated that if you inherit child class from parent class with having function of same signature the child
class function will be hided by parent class function.To avoid this hide of child class function by parent
class we need to use polymorphism.as follows:
in the abstract class use the following signature of function:
public virtual void  myfunction()

in the inherited class use the following singature of function:
public override void myfunction()

and now if you instantiate any of the class with abstract class's object it will override by inherited class function.

What is a interface in c# lets try it with example
I create a interface as follows:

interface Iabstract
    {
         void myfunction();
  
    }

Now i implement this with Inherited class as follows:
public class Inherited : Abstract, Iabstract
    {
        public override void myfunction()
        {
        Console.Write("This is Function Class");  
        }
    }

and call an instance of interface which references to inherited class in Main() as follows:
Iabstract objabc = new Inherited();

What should be the output?

"This is Function Class"

if you even remove the polymorphism mechanism from this still the interface instance will show the same output.

Why is it so? because interface is contract which calls functions of those classes on which its being implemented neither more nor less than that.

Hope you will enjoy this article...Thanks

425 data connection Error

. Monday, February 21, 2011
0 comments


If you stuck in issues like
*425 data connection can not be opened
*failed to display directory listing
or if you are unable to connect with ftpserver from ftpclient then try the following solution it will work.
1)Open settings from ftp server
2)then go into passive mode settings in left pane.
3)Now if radiobutton of default is checked then check
the next radio button to this asking for Insert the IP


Address and insert the localhost address(127.0.0.1) as shown above
4)Now click on Ok
5)your settings has been updated now
6)Now goto you ftp client and connect and it will work
Enjoy....

Note: This is understood that you have already configure users in ftp server and using its credentials and server ip address from your ftp client to connect.

OutputCache-asp.net mvc

. Saturday, February 19, 2011
0 comments


This post describes details about OuputCache

Caching : caching is mechanism in which you can store information on client side or server side or both for specified amout of time,can be understand by example that suppose you go to shop to purchase shirt now you try different different shirts and from which you only purchase one or two and checkout from shop.Nowshopkeeper has two options with shirts either he can put them back to their location or put them on customers desk from where they can choose again.benifit of the second option is that shopkeeper need not to go to take shirts which customers like and hence  shopkeeper roundtrip time reduces.The disadvantage is that if shopkeeper not put all those shirts back after a specifed amount of time then there would be burden on customer desk .Same happends with cache if you store information in cache for specified amount of time then there would be benifit that you don't need to pick the relative information again and again and hence your application's performance increases.
To use output caching in asp.net mvc use OutputCache attribute as show below with specified parameters



VaryByParams : suppose you have two pages one displays the Category and other displays its details.Now you if cache both of the pages with VaryByParams as "None",Even you click on any of the category you will see the exact same content as previous one but if you specify VaryByParams then your detail page will cache the different different selected category not that one which is being clicked first.

Location: specify the location for caching either on server side or client side or both.

As you can see i have added the Duration for 10 secs so the page will cached for 10 secs.

Note: asp.net mvc it is recommended to use this before respective action as OutputCache directive seems to bleeding over web forms. 

adding twitter feeds on blogger

.
0 comments

If you want to add twitter feeds on blogger then it is very simple just login to your tweet account and then go to this link
http://twitter.com/badges/blogger
which will look like as follows


after that click on add to blogger button and next click on add to widget button to add twitter widget as a gadget in blogger thanks so simple ...


Adding facebook like button on your blog or website

.
0 comments

Hi Guys, If you want to add Facebook Like button on your Blogger its easy just copy/paste thing.first login to your blogger account click on design and then click on edit HTML in this way you will find all of your blog's source html then find the following

in this way you are at the position where you have to put the following code to display Facebook's Like button
Paste the Facebook button code immediately below (after) it:



1<!-- Facebook Like button Start -->
2<b:if cond='data:blog.pageType != &quot;static_page&quot;'>
3<div style='float:left;padding:5px 5px 5px 0;'>
4<iframe allowTransparency='true' expr:src='&quot;http://www.facebook.com/plugins/like.php?href=&quot; + data:post.url + &quot;&amp;layout=standard&amp;show_faces=false&amp;width=450&amp;action=like&amp;font=verdana&amp;colorscheme=light&amp;height=35&quot;'frameborder='0' scrolling='no' style='border:none; overflow:hidden; width:440px; height:35px;'/>
5</div>
6</b:if>
7<!-- Facebook Like button End -->
Now you need to adjust position of button as you want the below table describes that 




Like button typeQueryValueWidth & Height
 standard like buttonlayoutstandard
W: 450px
H: 35px (80px w photos)
facebook like button countbutton_count
W: 90px
H: 20px
facebook like box countbox_count
W:55px
H: 65px
standard like button darkcolorschemedark
n.a.
standard like button recommendactionrecommend
n.a.