<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="http://msdnbangladesh.net/utility/FeedStylesheets/rss.xsl" media="screen"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:wfw="http://wellformedweb.org/CommentAPI/"><channel><title>Shahed Khan</title><link>http://msdnbangladesh.net/blogs/shahed/default.aspx</link><description /><dc:language>en</dc:language><generator>CommunityServer 2008.5 SP1 (Debug Build: 31106.3070)</generator><item><title>Implement custom Claim based Authorization in ASP.NET MVC Web Application</title><link>http://msdnbangladesh.net/blogs/shahed/archive/2010/02/05/implement-custom-claim-based-authorization-in-asp-net-mvc-web-application.aspx</link><pubDate>Fri, 05 Feb 2010 06:01:21 GMT</pubDate><guid isPermaLink="false">019a604b-fb74-42d5-8a6d-7cedfb08f61c:156142</guid><dc:creator>shahed</dc:creator><slash:comments>0</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msdnbangladesh.net/blogs/shahed/rsscomments.aspx?PostID=156142</wfw:commentRss><comments>http://msdnbangladesh.net/blogs/shahed/archive/2010/02/05/implement-custom-claim-based-authorization-in-asp-net-mvc-web-application.aspx#comments</comments><description>&lt;div class="wlWriterEditableSmartContent" id="scid:fb3a1972-4489-4e52-abe7-25a00bb07fdf:d2e5e5ba-71e6-4da8-b396-6f62a9936a92" style="padding-right:0px;display:inline;padding-left:0px;float:none;padding-bottom:0px;margin:0px;padding-top:0px;"&gt;&lt;p&gt; &lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/Download_5F00_54410D20.zip" target="_blank"&gt;To download the source code please click here&lt;/a&gt;&lt;/p&gt;&lt;/div&gt;  &lt;p&gt;&lt;strong&gt;Introduction&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;Claim-based authorization is a new model of authorization introduced in Windows Communication Foundation. This model addresses more scenarios than the popular role based&amp;#160; security model (IIdentity, IPrincipal). This is useful when an application requires complex and fine grained control on expressing access control decisions. Role based security model may not be powerful or flexible enough and is often too coarse when we reach complex scenarios - where custom roles are often necessary to represent different combinations of permissions or rights. For example – if you wanted to build a simple patient list page and wanted to have access control on CRUD operations based on roles you will end up creating several roles to support different combinations of access rights i.e. Administration clerks can only Add and Edit a patient but not Delete. Where the Supervisor can Add, Edit and Delete Patients. However you may want to restrict a Supervisor from certain access rights and then – end up creating custom roles depending on particular use cases. Claim based authorization framework attempts to address these limitations by providing a more generic model capable of addressing heterogeneous credential types, the ability to specify authorization policies through configuration at deployment time, and the flexibility to express arbitrary access control decisions based on the available evidence. .NET Framework starting in version 3.0 introduced a new identity and access-control API and can be found in the System.IdentityModel assembly and namespace.&lt;/p&gt;  &lt;p&gt;Some of the terms and concepts that we need to get familiar with when we talk about claim based authorization - are: Claim, ClaimSet and IAuthorizationPolicy.&lt;/p&gt;  &lt;p&gt;&lt;em&gt;Claim&lt;/em&gt; : A claim is a piece of information that describes an individual right or action applicable to a particular resource. A claim consists of three pieces of information: a claim type, resources and right. The datastructure is represented by a class System.IdentityModel.Claims.Clam.&lt;/p&gt;  &lt;p&gt;&lt;em&gt;ClaimSet&lt;/em&gt;: A claim set is an enumeration of claims with a common issuer.&lt;/p&gt;  &lt;p&gt;&lt;em&gt;IAuthorizationPolicy&lt;/em&gt;: Authorization policyis an extensiblility point which allows new claim sets to be added to the context representing the web service or application. Claims are added to an EvaluationContext by authorization policies.&lt;/p&gt;  &lt;p&gt;For more information please check “&lt;a href="http://msdn.microsoft.com/en-us/library/ff359115.aspx"&gt;A Guide to Claims-Based Identity and Access Control&lt;/a&gt;” and “&lt;a href="http://www.theserverside.net/tt/articles/showarticle.tss?id=ClaimsBasedSecurityModel"&gt;Building a Claims-Based Security Model in WCF&lt;/a&gt;”. &lt;/p&gt;  &lt;p&gt;Claims are flexible and can be assigned based on authenticated users or authenticated user’s roles, although claims are guaranteed by a trusted issuer, which has added security benefits. The association between claim and the resources to which it grants rights seems to be more useful as it rarely changes, and the rules for how users and roles are assigned claims can freely change without impacting any authorization logics. For example one can design - Create, Read, Edit, Delete claims for Patients and can assign them to preferred list of users or roles freely.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;FictitiousHospital.com&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;Today we will look at building custom Claim based Authorization in a ASP.NET MVC application. For this discussion I will keep the application requirements simple – we will build a simple patient list page that lists inpatients and outpatients – however when an user is not authenticated the patient list page do not display the user the options to create, edit or delete patients. &lt;/p&gt;  &lt;p&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/fictitioushospital_5F00_40DD7A36.png"&gt;&lt;img title="fictitioushospital" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="378" alt="fictitioushospital" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/fictitioushospital_5F00_thumb_5F00_14596BB2.png" width="678" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;Fig 1 : FictitiousHospital.com&lt;/p&gt;  &lt;p&gt;To build this application we will use the ASP.NET Membership and FormsAuthentication - to authenticate users. Then we will implement a custom authorization policy (that implements the type IAuthorizationPolicy ) to serve a “Issuer” and the “set of claims” that can be attached to the securitycontext. Finally we will hook up the claim based security model within the ASP.NET MVC by extending different parts of the MVC Framework. &lt;a href="http://www.theserverside.net/tt/articles/showarticle.tss?id=ClaimsBasedSecurityModel"&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Authentication&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;The project template of ASP.NET MVC Web Application ships with some basic pages for authentication, e.g. Login, Registration, Change Password etc. including the web.config file configured with ASP.NET Membership provider and FormsAuthentication. This is handy as the application is already configured and ready to use with Authentication in place. Just a change of connectionstring that points to the correct aspnetdb database makes us ready to start Authenticating the users and we can start concentrate on the next step - Authorization.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/webconfig_5F00_558A05BA.png"&gt;&lt;img title="webconfig" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="429" alt="webconfig" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/webconfig_5F00_thumb_5F00_2FB67008.png" width="480" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;Fig 2: web.config&lt;/p&gt;  &lt;p&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/formauthentication_5F00_19F1A90D.png"&gt;&lt;img title="formauthentication" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="300" alt="formauthentication" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/formauthentication_5F00_thumb_5F00_469CF397.png" width="622" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;Fig 3: FormsAuthenticationService&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Authorization&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;The first thing to identify is to what types of claims make sense for our fictitioushospital.com website. Lets think of claims as permissions that are required to access the features. If we consider patients as resources we may have (CRUD) permissions like Patient Create, Patient View, Patient Edit and Patient Delete. So the possible list of claims may be:&lt;/p&gt;  &lt;p&gt;&lt;em&gt;1. Patient Create&lt;/em&gt;&lt;/p&gt;  &lt;p&gt;Right: &lt;a href="http://schemas.xmlsoap.org/ws/2005/05/identity/right/possessproperty"&gt;http://schemas.xmlsoap.org/ws/2005/05/identity/right/possessproperty&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;Claim Type: &lt;a title="" href="http://schemas.fictitioushospital.com/2010/02/identity/claims/create"&gt;http://schemas.fictitioushospital.com/2010/02/identity/claims/create&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;Resources: &lt;a href="http://schemas.fictitioushospital.com/2010/02/identity/resources/patients"&gt;http://schemas.fictitioushospital.com/2010/02/identity/resources/patients&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;&lt;em&gt;2. Patient View&lt;/em&gt;&lt;/p&gt;  &lt;p&gt;Right: &lt;a href="http://schemas.xmlsoap.org/ws/2005/05/identity/right/possessproperty"&gt;http://schemas.xmlsoap.org/ws/2005/05/identity/right/possessproperty&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;Claim Type: &lt;a title="" href="http://schemas.fictitioushospital.com/2010/02/identity/claims/read"&gt;http://schemas.fictitioushospital.com/2010/02/identity/claims/read&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;Resources: &lt;a href="http://schemas.fictitioushospital.com/2010/02/identity/resources/patients"&gt;http://schemas.fictitioushospital.com/2010/02/identity/resources/patients&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;&lt;em&gt;3. Patient Edit &lt;/em&gt;&lt;/p&gt;  &lt;p&gt;Right: &lt;a href="http://schemas.xmlsoap.org/ws/2005/05/identity/right/possessproperty"&gt;http://schemas.xmlsoap.org/ws/2005/05/identity/right/possessproperty&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;Claim Type: &lt;a title="" href="http://schemas.fictitioushospital.com/2010/02/identity/claims/update"&gt;http://schemas.fictitioushospital.com/2010/02/identity/claims/update&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;Resources: &lt;a href="http://schemas.fictitioushospital.com/2010/02/identity/resources/patients"&gt;http://schemas.fictitioushospital.com/2010/02/identity/resources/patients&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;&lt;em&gt;4. Patient Delete &lt;/em&gt;&lt;/p&gt;  &lt;p&gt;Right: &lt;a href="http://schemas.xmlsoap.org/ws/2005/05/identity/right/possessproperty"&gt;http://schemas.xmlsoap.org/ws/2005/05/identity/right/possessproperty&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;Claim Type: &lt;a title="" href="http://schemas.fictitioushospital.com/2010/02/identity/claims/delete"&gt;http://schemas.fictitioushospital.com/2010/02/identity/claims/delete&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;Resources: &lt;a href="http://schemas.fictitioushospital.com/2010/02/identity/resources/patients"&gt;http://schemas.fictitioushospital.com/2010/02/identity/resources/patients&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;To work with these claims in code we define list of representative constants as follows:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/resources_5F00_2854CD52.png"&gt;&lt;img title="resources" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="98" alt="resources" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/resources_5F00_thumb_5F00_2399559C.png" width="734" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;Fig 4: Resources&lt;/p&gt;  &lt;p&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/claimtypes_5F00_3C2B839D.png"&gt;&lt;img title="claimtypes" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="203" alt="claimtypes" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/claimtypes_5F00_thumb_5F00_6C7779B5.png" width="683" border="0" /&gt;&lt;/a&gt;     &lt;br /&gt;Fig 5: ClaimTypes&lt;/p&gt;  &lt;p&gt;We have already established our requirements for claims-based authorization for our fictitioushospital.com and now we are going to write an implementation of type System.IdentityModel.Policy.IAuthorizationPolicy interface (i.e. CustomAuthorizationPolicy). This interface requires us to implement properties, Id of type string, Issuer of type ClaimSet and the Evaluate() method that returns bool.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/IAuthorizationPolicy_5F00_14AC4379.png"&gt;&lt;img title="IAuthorizationPolicy" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="160" alt="IAuthorizationPolicy" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/IAuthorizationPolicy_5F00_thumb_5F00_41C3C0F8.png" width="238" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;Fig 6: IAuthorizationPolicy interface&lt;/p&gt;  &lt;p&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/CustomAuthorizationPolicy_5F00_6EDB3E77.png"&gt;&lt;img title="CustomAuthorizationPolicy" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="937" alt="CustomAuthorizationPolicy" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/CustomAuthorizationPolicy_5F00_thumb_5F00_0CDE6DCE.png" width="688" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;Fig 7: CustomAuthorizationPolicy&lt;/p&gt;  &lt;p&gt;The CustomAuthorizationPolicy implements necessary interface. The Id property returns an unique identifier. The issuer property returns ClaimSet describing the issuer associated with this authorization policy, note that we have used issuerName = &lt;a href="http://www.fictitioushospital.com/2010/02/issuer"&gt;http://www.fictitioushospital.com/2010/02/issuer&lt;/a&gt; here. Finally the Evaluate() method that is the most important part of this implementation is responsible to inspect the claims based on the credentials provided. &lt;/p&gt;  &lt;p&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/evaluate_5F00_7DCCB055.png"&gt;&lt;img title="evaluate" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="618" alt="evaluate" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/evaluate_5F00_thumb_5F00_0E002A62.png" width="698" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;Fig 6: Evaluate() method&lt;/p&gt;  &lt;p&gt;Here we have written some code that decides to attach Create, Read, Update and Delete claims to the evaluationContext when the user is authenticated otherwise only attaches the Read claim. We can implement different other ways to figure out the associated claims for the particular User.Identity e.g. based on roles or based on predefined access rights that is stored in database or xml. &lt;/p&gt;  &lt;p&gt;The hard part is quite done – now we have to hook up this CustomAuthorizationPolicy into our ASP.NET MVC pipeline to start performing claim based authorization. &lt;strong&gt;Step 1&lt;/strong&gt;: to do this we start by defining our custom IUser interface that extends IPrincipal interface and wraps an extra property named “Issuer” of type ClaimSet within, that is intended to carry the Issuer details returned from the CustomAuthorizationPolicy. &lt;/p&gt;  &lt;p&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/IUser_5F00_665ECF99.png"&gt;&lt;img title="IUser" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="112" alt="IUser" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/IUser_5F00_thumb_5F00_2A3594A2.png" width="309" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;Fig 8: IUser interface&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Step 2&lt;/strong&gt;: we implement the User class of our custom IUser interface.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/User_5F00_272336AD.png"&gt;&lt;img title="User" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="592" alt="User" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/User_5F00_thumb_5F00_714362F4.png" width="457" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;Fig 9: User&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Step 3&lt;/strong&gt;: we implement a custom authorization filter of type System.Web.Mvc.IAuthorizationFilter interface. OnAuthorization() we instantiate our custom User (that implements IPrincipal) using the information obtained from “filterContext.HttpContext.User.Identity”. Then we create a list of AutorizationPolicy and add our CustomAuthorizationPolicy to create a default instance of AuthorizationContext (authContext), this under the hood goes and call the Evaluate() method of CustomAuthorizationPolicy and populates the authContext.ClaimSets. Then we iterate through the authContext.ClaimSets and locate the issuer that we are interested in and assign the issuer to our custom User object. We then replace the HttpContext.User and Thread.CurrentPrincipal with our custom User. Please also note that we keep the customUser in Session() to avoid repeatative calls to retrieve the claimSet on every single request. A ClaimSet may be retrieved from database and this may be an expensive call to perform on every single request, populating it once and storing it in session seems feasible.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/AuthorizationFilter_5F00_52FB3CAF.png"&gt;&lt;img title="AuthorizationFilter" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="504" alt="AuthorizationFilter" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/AuthorizationFilter_5F00_thumb_5F00_58029BC0.png" width="895" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;Fig 10: AuthorizationFilter&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Step 4&lt;/strong&gt;: we add this custom AuthorizationFilter in the controllers AuthorizationFilters list&amp;#160; by extending the ControllerActionInvoker.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/CustomControllerActionInvoker_5F00_0E09AB7F.png"&gt;&lt;img title="CustomControllerActionInvoker" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="231" alt="CustomControllerActionInvoker" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/CustomControllerActionInvoker_5F00_thumb_5F00_7125A80B.png" width="712" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;Fig 11: CustomControllerActionInvoker&lt;/p&gt;  &lt;p&gt;The default implementation of IActionInvoker is ControllerActionInvoker and does quite a bit behind the scene. Firstly it obtains parameter values for the parameters on the action methods using the ModelBinder and then it executes various filters. There are different types of filters: &lt;/p&gt;  &lt;p&gt;Authorization Filter – IAuthorizationFilter interface    &lt;br /&gt;Action Filter – IActionFilter interface     &lt;br /&gt;Result Filter – IResultFilter interface     &lt;br /&gt;Exception Filter – IExceptionFilter interface&lt;/p&gt;  &lt;p&gt;and out of them Authorization filter is the first set of filters to be executed. This is where our custom AuthorizationFilter will get executed and that will replace the IPrincipal user identity with our custom custom User that we discussed above.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Step 5&lt;/strong&gt;: we extend the DefaultControllerFactory and implement CustomControllerFactory, that assigns the controller.ActionInvoder to an instance of CustomControllerActionInvoker instead of&amp;#160; the ControllerActionInvoker.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/CustomControllerFactory_5F00_4BBE454E.png"&gt;&lt;img title="CustomControllerFactory" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="333" alt="CustomControllerFactory" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/CustomControllerFactory_5F00_thumb_5F00_2514DA63.png" width="658" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;Fig 12. CustomControllerFactory &lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Step 6&lt;/strong&gt;: we tell our Mvc ControllerBuilder.Current.SetControllerFactory() to use the extended CustomControllerFactory insead of the default DefaultControllerFactory, and we normally do this once during the Application_Start as following.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/application_5F00_start_5F00_6645746B.png"&gt;&lt;img title="application_start" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="97" alt="application_start" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/application_5F00_start_5F00_thumb_5F00_3EA419A3.png" width="680" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;Fig 13: Application_Start&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Step 7&lt;/strong&gt;: finally we are ready to check for claims during our Action invocation. Consider the PatientController, Index() action that returns list of patients. However this checks whether callers are granted to the Create, Edit and Delete role using the issuer.ContainsClaim() method and populates the PatientViewModel s CanCreate, CanEdit and CanDelete property, and the viewModel object is passed to the View.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/PatientList_5F00_17002E2A.png"&gt;&lt;img title="PatientList" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="303" alt="PatientList" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/PatientList_5F00_thumb_5F00_5830C832.png" width="563" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;Fig 14: PatientController Index() action.&lt;/p&gt;  &lt;p&gt;Later on by checking the PatientViewModels properties in the View one can easily decide on what links to display or not. &lt;/p&gt;  &lt;p&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/PatientListView_5F00_20809EB3.png"&gt;&lt;img title="PatientListView" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="600" alt="PatientListView" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/PatientListView_5F00_thumb_5F00_73242A44.png" width="583" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;Fig 15: View&lt;/p&gt;  &lt;p&gt;I have mentioned earlier that the association between claim and resources are highly unlike to change frequently. Consider this example where the Create() action demands the PatientClaims.PatientCreate Claim before this allows to create a new Patient, and similar with Update() action where it demands the PatientClaims.PatientUpdate claim. And thus the rules for how users and roles are assigned claims can freely change without impacting any the authorization logics.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/PatientCreate_5F00_Update_5F00_042D798A.png"&gt;&lt;img title="PatientCreate_Update" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="449" alt="PatientCreate_Update" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/PatientCreate_5F00_Update_5F00_thumb_5F00_378BCD97.png" width="583" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;Fig 16 Create, Update example&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Claims-Based Permission Demands&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;You can take this further and implement Claims-Based Permission Demands, thus you will be able to write something like this:&lt;/p&gt;  &lt;p&gt;[CreatePatientsClaim(SecurityAction.Demand)]    &lt;br /&gt;public void Create()&lt;/p&gt;  &lt;p&gt;{    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; //protected code     &lt;br /&gt;}     &lt;br /&gt;    &lt;br /&gt;&lt;/p&gt;  &lt;p&gt;[UpdatePatientsClaim(SecurityAction.Demand)]    &lt;br /&gt;public void Update()&lt;/p&gt;  &lt;p&gt;{    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; //protected code     &lt;br /&gt;}     &lt;br /&gt;    &lt;br /&gt;&lt;/p&gt;  &lt;p&gt;[DeletePatientsClaim(SecurityAction.Demand)]    &lt;br /&gt;public void Delete()&lt;/p&gt;  &lt;p&gt;{    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; //protected code     &lt;br /&gt;}&lt;/p&gt;  &lt;p&gt;Permission demands are implemented with the PrincipalPermission or PrincipalPermissionAttribute and relies on the security principal attached to the executing thread to authorize calls. The idea is that when the permission demand is invoked the security principal attached to the request thread checks necessary values. Like with the PrincipalPermission type, you can write your own custom implementation of ClaimsPrincipalPermission that implements IPermission, ISecurityEncodable and IUnrestrictedPermission interface. This article “&lt;a href="http://www.theserverside.net/tt/articles/showarticle.tss?id=ClaimsBasedSecurityModel2"&gt;Building a Claims-Based Security Model in WCF – Part 2&lt;/a&gt;” by Michele Leroux Bustamente explains this in great detail.&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;Here we looked at how to implement claims-based security model in an ASP.NET MVC application. So how all this works in ASP.NET MVC according to the above implementation is,&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;OnApplication_Start we SetContollerFactory to use CustomControllerFactory. &lt;/li&gt;    &lt;li&gt;CustomControllerFactory assigns instance of CustomControllerActionInvoker to the controller.ActionInvoker property of every controller instances. &lt;/li&gt;    &lt;li&gt;CustomControllerActionInvoker adds our AuthorizationFilter to the controllers AuthorizationFilters list. &lt;/li&gt;    &lt;li&gt;OnAuthorization of AuthorizationFilter is always invoked as the first thing during “InvokeAction()”. This calls the CreateDefaultAuthorizationContext() passing the list of&amp;#160; IAuthorizationPolicies, i.e. the CustomAuthorizationPolicy. The CustomAuthorizationPolicy instantiates itself with an unique Id. &lt;/li&gt;    &lt;li&gt;The Evaluate method of the CustomAuthorizationPolicy is called and that retrieves the ClaimSet for particular issuer for a particular user. &lt;/li&gt;    &lt;li&gt;A custom user is created of type User (that implements IUser –&amp;gt; IPrincipal ). This custom user is assigned to the HttpContext.User and Thread.CurrentPrincipal. &lt;/li&gt;    &lt;li&gt;The controller gets the custom user ( of type User – that implements IUser –&amp;gt; IPrincipal ) in its context. &lt;/li&gt;    &lt;li&gt;The action methods decides on access rights using the User.Issuer.ContainClaims() method. &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;Claim based authorization model is not to replace the role based authorization model and in many cases role based authorization may turn out to be more than sufficient. Claim based authorization models definitely supports more complex scenarios and allows fine grained control on expressing access control decision. Thank you for being with me so far and I hope that this discussion will help you in some way during your implementation of claims based security model. Happy coding!&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msdnbangladesh.net/aggbug.aspx?PostID=156142" width="1" height="1"&gt;</description></item><item><title>Use IoC slash Dependency Injection framework to manage hierarchical object structure better</title><link>http://msdnbangladesh.net/blogs/shahed/archive/2010/01/24/use-ioc-slash-dependency-injection-framework-to-manage-hierarchical-object-structure-better.aspx</link><pubDate>Sat, 23 Jan 2010 21:47:11 GMT</pubDate><guid isPermaLink="false">019a604b-fb74-42d5-8a6d-7cedfb08f61c:156080</guid><dc:creator>shahed</dc:creator><slash:comments>0</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msdnbangladesh.net/blogs/shahed/rsscomments.aspx?PostID=156080</wfw:commentRss><comments>http://msdnbangladesh.net/blogs/shahed/archive/2010/01/24/use-ioc-slash-dependency-injection-framework-to-manage-hierarchical-object-structure-better.aspx#comments</comments><description>&lt;div class="wlWriterEditableSmartContent" id="scid:fb3a1972-4489-4e52-abe7-25a00bb07fdf:f8213a86-3c20-42a2-b73d-604f11973db6" style="padding-right:0px;display:inline;padding-left:0px;float:none;padding-bottom:0px;margin:0px;padding-top:0px;"&gt;&lt;p&gt; &lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/Source_5F00_7A674A29.zip" target="_blank"&gt;To download the sourcecode click here&lt;/a&gt;&lt;/p&gt;&lt;/div&gt;  &lt;p&gt;&lt;strong&gt;Introduction&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;Recently I have been working with some hierarchical object structures that are a composition of several other nested classes and elements, that we call “template objects”. To give you an idea of this, consider “Patient” class as a container that holds patient demographics in a hierarchical object structure. &lt;/p&gt;  &lt;p&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/hierarchicaltemplate_5F00_4CA13377.png"&gt;&lt;img title="hierarchical-template" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="241" alt="hierarchical-template" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/hierarchicaltemplate_5F00_thumb_5F00_777EB8EB.png" width="381" border="0" /&gt;&lt;/a&gt;     &lt;br /&gt;Fig: hierarchical template.&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;p&gt;These template objects are very robust and flexible, someone can go and design a template like above in a hierarchical structure with unlimited nesting and we have a tool that goes and generates these template objects automatically for us. e.g.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/NestedClass_5F00_63F3E9FB.png"&gt;&lt;img title="NestedClass" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="638" alt="NestedClass" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/NestedClass_5F00_thumb_5F00_5DD1BEC2.png" width="355" border="0" /&gt;&lt;/a&gt;     &lt;br /&gt;Fig: nested template objects.&lt;/p&gt;  &lt;p&gt;   &lt;br /&gt;&lt;strong&gt;Problem&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;I have been developing some web based CRUD interface pages with these template objects / container classes. However I faced some problem with the hierarchical nature of the template objects. Speaking of the above template as an example, two major problems that slowed down the development are&lt;/p&gt;  &lt;p&gt;1. If I wanted to populate current address of the Patient class I had to instantiate several nested classes of the template object and then finally was able to assign the value to the desired&amp;#160; address property. e.g.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/problem1_5F00_67BBD18F.png"&gt;&lt;img title="problem1" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="130" alt="problem1" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/problem1_5F00_thumb_5F00_489DD611.png" width="654" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;2. If I wanted to display the “current address” of the Patient to the page, I had to go through all sorts of null checking on several layers of the hierarchical object structure.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/problem2_5F00_031B6697.png"&gt;&lt;img title="problem2" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="228" alt="problem2" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/problem2_5F00_thumb_5F00_72395357.png" width="628" border="0" /&gt;&lt;/a&gt;&amp;#160;&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;p&gt;As you can realize, that any kind of get and set operation to a nested object turns into a big task for the developers and the more deeper nested the object is in the hierarchy the more codes has to be written to deal with it.&lt;/p&gt;  &lt;p&gt;Before I suggest a solution to this problem , lets look at different ways to maintain/represent hierarchical objects in C#.NET.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;General class&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;This is the most common approach that we take, we create different dependent classes in separate physical file under same namespace.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/generalclass_5F00_3369ED60.png"&gt;&lt;img title="general-class" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="97" alt="general-class" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/generalclass_5F00_thumb_5F00_40665E22.png" width="162" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;Fig: classes in separate physical files.&lt;/p&gt;  &lt;p&gt;However when we auto generate classes from templates there is high chances of class name conflicts. To overcome that scenario we can take one of the following approaches: Namespace separated class or Nested class.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Namespace separated class&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;In this approach every class can be maintained in separate physical files or all related classes can be dumped in one single physical file. However the key difference of this pattern to the above is every single class gets its own different namespace that also resembles the hierarchy. I made up the&amp;#160; Namespace conventions to be the parent class name suffixed by the string “Ns”.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/patientclass_5F00_4ABA1333.png"&gt;&lt;img title="patient-class" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="124" alt="patient-class" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/patientclass_5F00_thumb_5F00_77D190B2.png" width="490" border="0" /&gt;&lt;/a&gt;&amp;#160;&lt;/p&gt;  &lt;p&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/patientdemographicsclass_5F00_04CE0175.png"&gt;&lt;img title="patient-demographics-class" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="157" alt="patient-demographics-class" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/patientdemographicsclass_5F00_thumb_5F00_6619A83A.png" width="468" border="0" /&gt;&lt;/a&gt;&amp;#160;&lt;/p&gt;  &lt;p&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/patientaddressclass_5F00_274A4243.png"&gt;&lt;img title="patient-address-class" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="135" alt="patient-address-class" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/patientaddressclass_5F00_thumb_5F00_5EB574D3.png" width="643" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;Fig: namespace separated classes.&lt;/p&gt;  &lt;p&gt;When classes are stored in separate physical files, there is potential of physical filename conflict of the generated classes. This is easy to solve though, the related classes are sometimes grouped and stored in separate folders.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Nested class&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;The other approach is to create nested classes like we have seen above in “Fig : nested template objects”. Normally when one class is entirely dependent upon another, we decide to implement it using a nested class. Nested classes are declared within the scope of an existing class and receive special benefits when accessing private and protected members of their parent class.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Inversion of control (IoC) slash Dependency Injection&lt;/strong&gt;&amp;#160;&lt;/p&gt;  &lt;p&gt;Speaking about the problem that we identified earlier, here are some thoughts to solve the issues. I have some experiences with Inversion of control (IoC) slash Dependency Injection on test driven developments and I am aware the IoC frameworks provides simplified object creation, especially for hierarchical object structures and dependencies. I looked into this further to come up with a solution. For those who are new to DI and IoC, I would recommend you to read Martin Fowlers article : “&lt;a href="http://www.martinfowler.com/articles/injection.html"&gt;Inversion of Control Containers and Dependency Injection pattern&lt;/a&gt;”.&lt;/p&gt;  &lt;p&gt;In fact any of the following conditions justifies using the DI pattern.&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;&lt;em&gt;You want to decouple your classes from their dependencies so that these dependencies can be replaced or updated with minimal or no changes to your classes&amp;#39; source code.&lt;/em&gt; &lt;/li&gt;    &lt;li&gt;&lt;em&gt;You want to be able to write classes that depend on classes whose concrete implementation is not known at compile time.&lt;/em&gt; &lt;/li&gt;    &lt;li&gt;&lt;em&gt;You want to be able to test your classes in isolation, without using the dependencies.&lt;/em&gt; &lt;/li&gt;    &lt;li&gt;&lt;em&gt;You want to decouple your classes from being responsible for locating and managing the lifetime of dependencies.        &lt;br /&gt;&lt;/em&gt;&lt;em&gt;       &lt;br /&gt;source: &lt;/em&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/cc707845.aspx"&gt;&lt;em&gt;http://msdn.microsoft.com/en-us/library/cc707845.aspx&lt;/em&gt;&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;There are lots of IoC containers out there and some of the popular ones are &lt;a href="http://structuremap.sourceforge.net/"&gt;StructureMap&lt;/a&gt;, &lt;a href="http://www.codeplex.com/unity"&gt;Unity&lt;/a&gt;, &lt;a href="http://ninject.org/"&gt;Ninject&lt;/a&gt;, &lt;a href="http://code.google.com/p/autofac/"&gt;AutoFac&lt;/a&gt;, &lt;a href="http://castleproject.org/"&gt;Castle Windsor&lt;/a&gt; and &lt;a href="http://www.springframework.net/"&gt;Spring.NET&lt;/a&gt;.&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Solution&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;So by using the DI, we can inverse the dependencies on the template object classes and make them less coupled. e.g. by getting the PatienDemographics injected as a constructor parameter on the Patient class we can inverse the dependency and now Patient class depends on someone else to pass in the dependency. We can decouple and make this more flexible by declaring an interface for PatientDemographics and then pass the IPatientDemographics instead, something like this.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/refactoredclass_5F00_0D9D481A.png"&gt;&lt;img title="refactored-class" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="181" alt="refactored-class" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/refactoredclass_5F00_thumb_5F00_6EE8EEDF.png" width="503" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;Fig: refactored Patient class.&lt;/p&gt;  &lt;p&gt;We continue to inverse the dependencies for all other template objects in the hierarchy e.g.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/refactoredtdoclass_5F00_65261818.png"&gt;&lt;img title="refactored-tdo-class" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="1202" alt="refactored-tdo-class" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/refactoredtdoclass_5F00_thumb_5F00_1E61A070.png" width="662" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;Fig : refactored classes. &lt;/p&gt;  &lt;p&gt;The next thing to do, is to register all our dependencies in IoC container by passing the container an interface that the dependency implements, and the concrete class that will be instantiated for request of that interface. In other words during the registration we tell the IoC container what and how it should build or find or serve requested services. I will register my dependencies using &lt;a href="http://structuremap.sourceforge.net/"&gt;StructuredMap&lt;/a&gt; here. &lt;/p&gt;  &lt;p&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/structuremapregistry_5F00_183F7537.png"&gt;&lt;img title="structuremap-registry" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="177" alt="structuremap-registry" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/structuremapregistry_5F00_thumb_5F00_2948C47C.png" width="783" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;Fig : structuremap registry.&lt;/p&gt;  &lt;p&gt;By default, as long as an object is being created by invoking its constructor function, &lt;a href="http://structuremap.sourceforge.net/"&gt;StructureMap&lt;/a&gt; will try to create/resolve/find an object for non-primitive dependency in the requested concrete type. This is known as autowiring, IoC will take care of instantiating all necessary dependent objects automatically. If &lt;a href="http://structuremap.sourceforge.net/"&gt;StructureMap&lt;/a&gt; doesn’t know how to find a requested dependency it throws exception. This solves our problem, here is how: &lt;/p&gt;  &lt;p&gt;1. If I wanted to populate current address of the Patient class I do not need to worry about instantiatiating several nested classes of the template object, because that will be magically handled by the IoC and I will be able to assign the value to the desired&amp;#160; address property with one line of code like the following.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/solution1_5F00_7F6AE0F7.png"&gt;&lt;img title="solution1" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="257" alt="solution1" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/solution1_5F00_thumb_5F00_2AD42354.png" width="736" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;2. If I wanted to display the “current address” of the Patient to the page, I do not need to go through all sorts of null checking on several layers of the hierarchical object structure, because IoC will automatically instantiate all dependent objects. I can go to the desired property directly and display the value when available.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/solution2_5F00_1A5E430A.png"&gt;&lt;img title="solution2" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="632" alt="solution2" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/solution2_5F00_thumb_5F00_7F4A955D.png" width="662" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;You can see now clearly, how inversing dependencies and use of IoC container improves developers productivity significantly.&lt;/p&gt;  &lt;p&gt;Before I finish I must also introduce the &lt;a href="http://commonservicelocator.codeplex.com/"&gt;Common Service Locator library&lt;/a&gt; that contains a shared interface for service location which application and framework developers can reference. The library provides an abstraction over Ioc containters and service locators, which helps developers to use IoC without tying them down to a specific implementation. Currently service locator adapter implementations are available for StructureMap, Unity, Castle Windsor, Sprint.NET, Autofact, MEF and Linfu. The full list can be found &lt;a href="http://commonservicelocator.codeplex.com/"&gt;here&lt;/a&gt;.&lt;/p&gt;  &lt;p&gt;I hope this discussion will solve some programming nightmare with hierarchical object structure. Thank you for being with me so far and happy coding.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msdnbangladesh.net/aggbug.aspx?PostID=156080" width="1" height="1"&gt;</description></item><item><title>ASP.NET MVC, ASP.NET Tips: Provide immediate feedback to the browser on Long Running Tasks – using IFrame and web handlers</title><link>http://msdnbangladesh.net/blogs/shahed/archive/2009/10/28/asp-net-mvc-asp-net-tips-provide-immediate-feedback-to-the-browser-on-long-running-tasks-using-iframe-and-web-handlers.aspx</link><pubDate>Tue, 27 Oct 2009 16:28:13 GMT</pubDate><guid isPermaLink="false">019a604b-fb74-42d5-8a6d-7cedfb08f61c:46983</guid><dc:creator>shahed</dc:creator><slash:comments>0</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msdnbangladesh.net/blogs/shahed/rsscomments.aspx?PostID=46983</wfw:commentRss><comments>http://msdnbangladesh.net/blogs/shahed/archive/2009/10/28/asp-net-mvc-asp-net-tips-provide-immediate-feedback-to-the-browser-on-long-running-tasks-using-iframe-and-web-handlers.aspx#comments</comments><description>&lt;p&gt;&lt;a href="http://msmvps.com/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed.metablogapi/0042.Download_5F00_6E95956F.jpg"&gt;&lt;img title="Download" height="79" alt="Download" src="http://msmvps.com/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed.metablogapi/4152.Download_5F00_thumb_5F00_0D04F7BB.jpg" width="64" border="0" /&gt;&lt;/a&gt;&amp;#160;&lt;a href="http://msmvps.com/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed.metablogapi/4251.AspnetWetsite_5F00_3A88A82F.zip"&gt;to download the source code please click here&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;   &lt;br /&gt;The &amp;lt;iframe&amp;gt; tag defines an inline frame that contains another document and is supported in all major browsers.     &lt;br /&gt;&lt;img title="Internet Explorer" height="30" alt="Internet Explorer" src="http://www.w3schools.com/images/compatible_ie.gif" width="31" border="0" /&gt; &lt;img title="Firefox" height="30" alt="Firefox" src="http://www.w3schools.com/images/compatible_firefox.gif" width="31" border="0" /&gt; &lt;img title="Opera" height="30" alt="Opera" src="http://www.w3schools.com/images/compatible_opera.gif" width="28" border="0" /&gt; &lt;img title="Google Chrome" height="30" alt="Google Chrome" src="http://www.w3schools.com/images/compatible_chrome.gif" width="31" border="0" /&gt; &lt;img title="Safari" height="30" alt="Safari" src="http://www.w3schools.com/images/compatible_safari.gif" width="28" border="0" /&gt;&lt;/p&gt;  &lt;p&gt;The &amp;lt;iframe&amp;gt; can be placed anywhere in the document flow. The iframe properties such as&amp;#160; height and width can be easily modified by CSS and JavaScript. Data can be passed back and forth between the parent container and iframe using Javasrcipt. The document that is displayed inside an iframe can access the main window by the parent keyword. Iframe can have their own source URL that is distinct from the parent page and we are interested on this feature. We first declare an Iframe in the page and keep it hidden. We then point the Iframe to our preferred web handler, during page load iframe initiate a request to the server and the server start the lengthy task, and flushes state change information. The server flushes the response wrapped inside &amp;lt;script&amp;gt; tag to perform DOM manipulation on the parent container – similar technique that we have seen in &lt;a href="http://msmvps.com/blogs/shahed/archive/2009/10/27/asp-net-mvc-asp-net-tips-provide-immediate-feedback-to-the-browser-on-long-running-tasks-by-streaming-regular-asp-net-page.aspx"&gt;one of my post earlier&lt;/a&gt;. Here are the steps to follow.     &lt;br /&gt;&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;Declare Iframe in the page. &lt;/li&gt;    &lt;li&gt;Hide the Iframe. &lt;/li&gt;    &lt;li&gt;Point the src of the Iframe to the web handler. &lt;/li&gt;    &lt;li&gt;Get Iframe to initiate request from the the browser client to the web server when the page loads. &lt;/li&gt;    &lt;li&gt;Get the web handler to flush response on task state changes. &lt;/li&gt;    &lt;li&gt;Perform DOM manipulation on the parent container. &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;   &lt;br /&gt;&amp;#160;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/Iframe_5F00_1F3651F0.png"&gt;&lt;img title="Iframe" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="423" alt="Iframe" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/Iframe_5F00_thumb_5F00_36890874.png" width="716" border="0" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;Here I have declared two javascript functions in the parent page – “updateContent” and “hide”. “UpdateContent” replaces the data on “ReportDiv” element. “Hide” hides the loader image when lengthy task ends. Then down below on the same page I have declared the iframe tag, pointed the src of the iframe to a regular web handler “JsWrappedDataHandler.ashx”, and used the style elements to hide the iframe. Lets look at the web handler and what is cooking there.    &lt;br /&gt;&lt;/p&gt;  &lt;p&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/jswrappedhandler_5F00_4C08D880.png"&gt;&lt;img title="jswrappedhandler" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="930" alt="jswrappedhandler" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/jswrappedhandler_5F00_thumb_5F00_7A1AD68D.png" width="632" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;This is a regular web handler and you may be wondering why am I sending 256 dummy bytes. This is a workaround to make IE work properly because IE accepts a message from the server after the first 256 bytes. This technique is handy when we do not know about the message size and we can avoid any unexpected event by sending 256 dummy bytes before sending the original message. Next thing to look at is the script block – where it invokes the javascript functions that we defined in the parent container. Example window.paren.updateContent(data), window.paren.hide(). Finally the server is flushes the response directly to the browser. The Iframe receives the progressive flushed response chunk/script block and executes the javascript code - which invokes the javascript functions from of the parent container and updates the content of of “ReportDiv” element until the task completes. The end user gets immediate feedback on task state changes and do not need to wait until the entire response download. When the task is complete it invokes the hide() function to hide the loader image. This is what it looks like.    &lt;br /&gt;    &lt;br /&gt;&amp;#160;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/iframefeedback_5F00_4AEE0C58.png"&gt;&lt;img title="iframefeedback" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="443" alt="iframefeedback" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/iframefeedback_5F00_thumb_5F00_17B6F451.png" width="497" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Asynchronous web handlers&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;I discussed a little bit about asynchronous web handlers&amp;#160; in &lt;a href="http://msmvps.com/blogs/shahed/archive/2009/10/27/asp-net-mvc-asp-net-tips-provide-immediate-feedback-to-the-browser-on-long-running-tasks-using-regular-web-handler.aspx"&gt;earlier post&lt;/a&gt; and I promised that I will talk about it later – so I do so. It is recommended to use asynchronous web handlers for long/ lengthy tasks. An asyncchronous web handler implements IHttpAsyncHanddler – this means it implements two additional methods BeginProcessRequest and EndProcessRequest. The idea here is to spawn custom threads by hand to run the lengthy portion of the task and not block important ASP.NET work threads from the threadpool. I have discussed about why we should spawn an additional thread &lt;a href="http://msmvps.com/blogs/shahed/archive/2009/10/27/asp-net-mvc-asp-net-tips-provide-immediate-feedback-to-the-browser-on-long-running-tasks-in-asynchronous-asp-net-pages.aspx"&gt;in great length in this post&lt;/a&gt;, and I am not going to go through that again here, I am jumping straight in to the implentation of Asynchronous web handler. &lt;/p&gt;  &lt;p&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/IframeAsyncPage_5F00_6F61DEF3.png"&gt;&lt;img title="IframeAsyncPage" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="384" alt="IframeAsyncPage" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/IframeAsyncPage_5F00_thumb_5F00_7DC50338.png" width="751" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;This page is exactly same as the first one in this post where I declared 2 javascript function in the parent container such as “undateContent” and “hide”. The only difference is the iframe is now pointing to a different web handler and this time an asynchronous handler.    &lt;br /&gt;&lt;/p&gt;  &lt;p&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/jswrappedAsynchandler_5F00_112F868F.png"&gt;&lt;img title="jswrappedAsynchandler" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="595" alt="jswrappedAsynchandler" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/jswrappedAsynchandler_5F00_thumb_5F00_32FD2E2A.png" width="666" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;Here this asynchronous web handler implements the IHttpAsyncHandler. The BeginProcessRequest performs all the lengthy bits inside request.BeginProcessRequest method asynchronously and signals when the task is completed. This executes the EndProcessRequest method. The AsycWebHandlerRequest class is a custom hand written class and I paste the code below.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/AsyncwebhandlerRequest_5F00_7B080DBB.png"&gt;&lt;img title="AsyncwebhandlerRequest" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="978" alt="AsyncwebhandlerRequest" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/AsyncwebhandlerRequest_5F00_thumb_5F00_024BF589.png" width="626" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;Here I spawn custom Threads by hand to invoke the LongTask method. Long task has exact same code as we have seen in the regular web handler ProcessRequest method above, except the last line where it signals that the task is complete by invoking requestState.CompleteRequest method. Here the Response.Flush method does all the hard work to notify the connected browser about the task state changes and end user can enjoy immediate feedback from the server. You may be wondering about the AsyncRequestState class. I have used the exact same class during implementation of the Asynchrounous Page and can be &lt;a href="http://msmvps.com/blogs/shahed/archive/2009/10/27/asp-net-mvc-asp-net-tips-provide-immediate-feedback-to-the-browser-on-long-running-tasks-in-asynchronous-asp-net-pages.aspx"&gt;found here&lt;/a&gt;.&lt;/p&gt;  &lt;p&gt;I have indicated earlier that a web handlers is recommended for performance critical web pages. I have done some load tests to compare the result of regular web handler, asynchronous web handler and the asynchronous page that pretty much does the exact same operation. The test result of load tests that I have performed in exact same environment can be found below.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/IframeAsync_5F00_57983CCB.png"&gt;&lt;img title="IframeAsync" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="91" alt="IframeAsync" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/IframeAsync_5F00_thumb_5F00_6EE8629E.png" width="814" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Fig&lt;/strong&gt;: Load test of Iframe and asychronous web handler that uses custom thread&lt;/p&gt;  &lt;p&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/IframeRegular_5F00_3BB14A97.png"&gt;&lt;img title="IframeRegular" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="95" alt="IframeRegular" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/IframeRegular_5F00_thumb_5F00_4C4E66E7.png" width="812" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Fig&lt;/strong&gt;: Load test of Iframe and regular web handler&lt;/p&gt;  &lt;p&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/WebPageAsync_5F00_2204506E.png"&gt;&lt;img title="WebPageAsync" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="93" alt="WebPageAsync" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/WebPageAsync_5F00_thumb_5F00_39547641.png" width="827" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Fig&lt;/strong&gt;: Load test of asynchronous web page that implements custom thread&lt;/p&gt;  &lt;p&gt;You can see that the asynchronous web handler that spawns custom thread is the clear winner. And when you compare Asynchronous page with web handler – we see web handler is superior. &lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;Please note that the different techniques that I have been discussing&amp;#160; in last &lt;a href="http://msmvps.com/blogs/shahed/archive/2009/10/27/asp-net-mvc-asp-net-tips-provide-immediate-feedback-to-the-browser-on-long-running-tasks-using-regular-web-handler.aspx"&gt;several posts&lt;/a&gt;&amp;#160; is also known as Comet that describe the web application model in which a long-held HTTP request allows a web server to push data to a browser, without the browser expicitly requesting it. However holding a connection open for infinite period has negative impact on browser usability. The problem is the javascript will keep accumulating and the page will have to preserve them in the page itself, resulting in a unbound page size and memory implications – at worst the page becomes totally unresponsive and will crash the browser. These is ok to choose for long task that has a definite end, however we need to be a bit careful when it comes to a “real-time” applications that keeps running for indefinite period. For example an airlines time table, &lt;/p&gt;  &lt;p&gt;For a “real-time” application ( i.e. chat application, airline timetable ) a polling / long polling mechanism is more suitable where the server keeps looping for infinite period - produces the latest content and store it in a persistent layer – example a database/file, or in the application memory. The browser polls the latest response periodically, performs DOM manipulation to updates the page – and the user gets to see the latest record. Lets look at the polling techniques in my next post.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msdnbangladesh.net/aggbug.aspx?PostID=46983" width="1" height="1"&gt;</description></item><item><title>ASP.NET MVC, ASP.NET Tips: Provide immediate feedback to the browser on Long Running Tasks – using XMLHttpRequest call</title><link>http://msdnbangladesh.net/blogs/shahed/archive/2009/10/28/asp-net-mvc-asp-net-tips-provide-immediate-feedback-to-the-browser-on-long-running-tasks-using-xmlhttprequest-call.aspx</link><pubDate>Tue, 27 Oct 2009 16:23:46 GMT</pubDate><guid isPermaLink="false">019a604b-fb74-42d5-8a6d-7cedfb08f61c:46980</guid><dc:creator>shahed</dc:creator><slash:comments>0</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msdnbangladesh.net/blogs/shahed/rsscomments.aspx?PostID=46980</wfw:commentRss><comments>http://msdnbangladesh.net/blogs/shahed/archive/2009/10/28/asp-net-mvc-asp-net-tips-provide-immediate-feedback-to-the-browser-on-long-running-tasks-using-xmlhttprequest-call.aspx#comments</comments><description>&lt;p&gt;XMLHttpRequest (XHR) is a DOM API that can be used inside a web browser scripting language, such as JavaScript, to send an HTTP or an HTTPS request directly to a web server and load the server response data directly back into the scripting language. The technique that we are going to discuss here takes advantage of XMLHttpRequest objects readyState == 3 status (Interactive – Downloading) and responseText property to perform DOM manipulation in a browser. Here is how it works    &lt;br /&gt;&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;A request is initiated from the the browser client to the web server using the XMLHttpRequest object. &lt;/li&gt;    &lt;li&gt;The webserver flushes response during task state changes. &lt;/li&gt;    &lt;li&gt;XMLHttpRequest object holds partial data in responseText property when readyState is 3 ( Interactive – Downloading ). &lt;/li&gt;    &lt;li&gt;DOM manipulation is perfomed during readystate == 3 to interactively update the web content. &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;p&gt;&lt;a href="http://msmvps.com/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed.metablogapi/0042.Download_5F00_6E95956F.jpg"&gt;&lt;img title="Download" height="79" alt="Download" src="http://msmvps.com/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed.metablogapi/4152.Download_5F00_thumb_5F00_0D04F7BB.jpg" width="64" border="0" /&gt;&lt;/a&gt;&amp;#160;&lt;a href="http://msmvps.com/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed.metablogapi/4251.AspnetWetsite_5F00_3A88A82F.zip"&gt;to download the source code please click here&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;p&gt;Please note that XMLHttpRequest based technique will not work in all browsers. Microsoft clearly mentions in the &lt;a href="http://msdn.microsoft.com/en-us/library/ms534361(VS.85).aspx"&gt;specification&lt;/a&gt; that - “readyState =&amp;#160; 3, some data has been received. &lt;a href="http://msdn.microsoft.com/en-us/library/ms534369(VS.85).aspx"&gt;responseText&lt;/a&gt; is not available. &lt;a href="http://msdn.microsoft.com/en-us/library/ms534368(VS.85).aspx"&gt;responseBody&lt;/a&gt; is not available.” So this will not work in IE. However I found it working in Firefox and Chrome. Here is the code.     &lt;br /&gt;&lt;/p&gt;  &lt;p&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/XmlHttpRequest_5F00_4E439AD4.png"&gt;&lt;img title="XmlHttpRequest" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="1509" alt="XmlHttpRequest" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/XmlHttpRequest_5F00_thumb_5F00_3644DBCE.png" width="647" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;Here I have created a XmlHttpRequest object and configured it to perform a GET request to my DataHandler.ashx that I have &lt;a href="http://msmvps.com/blogs/shahed/archive/2009/10/27/asp-net-mvc-asp-net-tips-provide-immediate-feedback-to-the-browser-on-long-running-tasks-using-regular-web-handler.aspx"&gt;created earlier&lt;/a&gt;. The piece of code that does the magic to notify the browser on state changes is the part where I am updating the content of “ReportDiv” element with req.responseText when req.readyState == 3. The responseText dynamically loads the flushed response and this piece of code updates the content of the browser. Then finally I hide the loader image when the req.readyState turns 4 that means – loaded, all the data has been received. This entire process is initiated by the getData() method which is invoked during the pageload even, but you can do the same on onclick of a button or anchor tag or by raising some other event that suits your need. For a refresher on what is happening inside DataHandler.ashx here is the web handler codes.     &lt;br /&gt;&lt;/p&gt;  &lt;p&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/RegularHandler_5F00_2396D283.png"&gt;&lt;img title="RegularHandler" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="421" alt="RegularHandler" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/RegularHandler_5F00_thumb_5F00_1DC08EA5.png" width="640" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;The web handler simulates a long running task by putting the Thread to sleep. However it keeps flushing the response when the browser is connected to the server, until the task is complete. Please check my &lt;a href="http://msmvps.com/blogs/shahed/archive/2009/10/27/asp-net-mvc-asp-net-tips-provide-immediate-feedback-to-the-browser-on-long-running-tasks-using-regular-web-handler.aspx"&gt;earlier post&lt;/a&gt; where I have done detailed discussion on Response.IsClientConnected property, Response.Flush method etc.&lt;/p&gt;  &lt;p&gt;You may be wondering that this is still not the perfect solution that we are looking for as responseText is not available during readyState==3 in all browsers, we cannot do much about this however we can implement the IFrame Call that works in most of the browsers. &lt;a href="http://msmvps.com/blogs/shahed/archive/2009/10/27/asp-net-mvc-asp-net-tips-provide-immediate-feedback-to-the-browser-on-long-running-tasks-using-iframe-and-web-handlers.aspx"&gt;Lets look at that&lt;/a&gt;.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msdnbangladesh.net/aggbug.aspx?PostID=46980" width="1" height="1"&gt;</description></item><item><title>ASP.NET MVC, ASP.NET Tips: Provide feedback to the user on Long Running Tasks – using loader image - MS AJAX and JQuery</title><link>http://msdnbangladesh.net/blogs/shahed/archive/2009/10/28/asp-net-mvc-asp-net-tips-provide-feedback-to-the-user-on-long-running-tasks-using-loader-image-ms-ajax-and-jquery.aspx</link><pubDate>Tue, 27 Oct 2009 16:21:39 GMT</pubDate><guid isPermaLink="false">019a604b-fb74-42d5-8a6d-7cedfb08f61c:46973</guid><dc:creator>shahed</dc:creator><slash:comments>0</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msdnbangladesh.net/blogs/shahed/rsscomments.aspx?PostID=46973</wfw:commentRss><comments>http://msdnbangladesh.net/blogs/shahed/archive/2009/10/28/asp-net-mvc-asp-net-tips-provide-feedback-to-the-user-on-long-running-tasks-using-loader-image-ms-ajax-and-jquery.aspx#comments</comments><description>&lt;p&gt;It is quite common to display a loader-image or some kind of progress bar image in a browser when the server is busy serving the request. Before we go deep into page streaming techniques with XMLHTTPRequest call and IFrame, lets look into a simple loader icon implementation – the idea is to display “loading” image until the task completes, display the response in the browser when task ends and hide the loader image. &lt;/p&gt;  &lt;p&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/loading_5F00_18554ECC.png"&gt;&lt;img title="loading" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="256" alt="loading" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/loading_5F00_thumb_5F00_396ADC17.png" width="314" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;&lt;a href="http://msmvps.com/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed.metablogapi/0042.Download_5F00_6E95956F.jpg"&gt;&lt;img title="Download" height="79" alt="Download" src="http://msmvps.com/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed.metablogapi/4152.Download_5F00_thumb_5F00_0D04F7BB.jpg" width="64" border="0" /&gt;&lt;/a&gt;&amp;#160;&lt;a href="http://msmvps.com/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed.metablogapi/4251.AspnetWetsite_5F00_3A88A82F.zip"&gt;to download the source code please click here&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Invoke a long task and display loader image to notify task progress – using MS AJAX&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;Normally in a ASP.NET page we drop the ScriptManager control, put a reference of the webservice that we want to point to. The Scriptmanager goes and creates necessary proxy class for the webmethods. We can also add static methods to an ASP.NET page and qualify them as web methods and invoke them using javascript. This &lt;a href="http://www.asp.net/AJAX/Documentation/Live/tutorials/ExposingWebServicesToAJAXTutorial.aspx"&gt;tutorial&lt;/a&gt; shows how to do all these by configuring the ScriptManager easily. However I will play with the Sys.Net.WebRequest class directly here. The Sys.Net.WebRequest provides the script API to make Web request. It becomes handy when we need to partially update a little section of the page and it is quite straight forward to use the Web Request class anyway.&amp;#160; &lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;p&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/msajax_5F00_3D0E1856.png"&gt;&lt;img title="msajax" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="1240" alt="msajax" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/msajax_5F00_thumb_5F00_2B562FDE.png" width="652" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;It may look like a lots of code above but when you look closely you find that all I have done is setup a get request to asynchronously invoke my DataHandler.ashx web handler that I &lt;a href="http://msmvps.com/blogs/shahed/archive/2009/10/27/asp-net-mvc-asp-net-tips-provide-immediate-feedback-to-the-browser-on-long-running-tasks-using-regular-web-handler.aspx"&gt;created earlier&lt;/a&gt;. During page load the “PageLoad” method is called and this initiates the entire process. You can also do the same on the onclick event of an input button or anchor tag or by raising some other events that you prefer. The image that I used for the loader has been generated from this website &lt;a href="http://www.ajaxload.info/"&gt;Ajaxload.info&lt;/a&gt;,&amp;#160; this website has some nice loader image designs available. You can choose your indicator, background color, foreground color and generate your preferred loader. The webrequest invokes the web handler and the loader image is displayed until the full response is available. I populate the “ReportDiv” element with the completed response data, and hide the loader image with loader.style.display = “none”. There is also some codes above that handles timeout and abort situations.&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Invoke a long task and display loader image to notify task progress – using JQuery&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;The JQuery based implementation of the same above is even more simpler and is done with a lot less coding.    &lt;br /&gt;&lt;/p&gt;  &lt;p&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/Jquery_5F00_24C7D1B0.png"&gt;&lt;img title="Jquery" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="498" alt="Jquery" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/Jquery_5F00_thumb_5F00_3BAE553F.png" width="627" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;All I do here is I configure HTTP GET request call to my &lt;a href="http://msmvps.com/blogs/shahed/archive/2009/10/27/asp-net-mvc-asp-net-tips-provide-immediate-feedback-to-the-browser-on-long-running-tasks-using-regular-web-handler.aspx"&gt;DataHandler.ashx&lt;/a&gt; inside the “$(document).ready” function -this function is infact the first thing to learn about jQuery if you are new to JQuery. If you want an event to work on your page, you should call it inside the $(document).ready() function. Everything inside it will load as soon as the DOM is loaded and before the page contents are loaded. If you have not worked with &lt;a href="http://docs.jquery.com/Main_Page"&gt;JQuery&lt;/a&gt; yet I would strongly recommend to have a look at it. The getData() function makes the HTTP GET call to the web handler and on success I put the response to the “ReportDiv” element. Then I hide the loader icon with style display = “none”;     &lt;br /&gt;    &lt;br /&gt;Thats pretty much it, however this is not a robust solution and I am writing all the post in this series to render realtime states of a task in the browser. When we use this technique all we can display is the loader image to notify users that server is busy processing his/her request – we cannot display any real time update on the tasks state changes to the browser. The MS AJAX and JQuery web request calls do not allow to check XMLHttpRequest s readyState==3 status (will discuss about XMLHttpRequest object in the next post ). The web applications are stateless and request can only be initiated from the client, however XMLHttpRequest or a IFrame call can initiate a parallel request to the server and we can take advantage of that to stream contents to the browser. &lt;a href="http://msmvps.com/blogs/shahed/archive/2009/10/27/asp-net-mvc-asp-net-tips-provide-immediate-feedback-to-the-browser-on-long-running-tasks-using-xmlhttprequest-call.aspx"&gt;Lets look at them&lt;/a&gt;.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msdnbangladesh.net/aggbug.aspx?PostID=46973" width="1" height="1"&gt;</description></item><item><title>ASP.NET MVC, ASP.NET Tips: Provide immediate feedback to the browser on Long Running Tasks – in Asynchronous ASP.NET pages</title><link>http://msdnbangladesh.net/blogs/shahed/archive/2009/10/28/asp-net-mvc-asp-net-tips-provide-immediate-feedback-to-the-browser-on-long-running-tasks-in-asynchronous-asp-net-pages.aspx</link><pubDate>Tue, 27 Oct 2009 16:17:05 GMT</pubDate><guid isPermaLink="false">019a604b-fb74-42d5-8a6d-7cedfb08f61c:46969</guid><dc:creator>shahed</dc:creator><slash:comments>0</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msdnbangladesh.net/blogs/shahed/rsscomments.aspx?PostID=46969</wfw:commentRss><comments>http://msdnbangladesh.net/blogs/shahed/archive/2009/10/28/asp-net-mvc-asp-net-tips-provide-immediate-feedback-to-the-browser-on-long-running-tasks-in-asynchronous-asp-net-pages.aspx#comments</comments><description>&lt;p&gt;&lt;a href="http://msmvps.com/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed.metablogapi/0042.Download_5F00_6E95956F.jpg"&gt;&lt;img title="Download" height="79" alt="Download" src="http://msmvps.com/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed.metablogapi/4152.Download_5F00_thumb_5F00_0D04F7BB.jpg" width="64" border="0" /&gt;&lt;/a&gt;&amp;#160;&lt;a href="http://msmvps.com/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed.metablogapi/4251.AspnetWetsite_5F00_3A88A82F.zip"&gt;to download the source code please click here&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;In the &lt;a href="http://msmvps.com/blogs/shahed/archive/2009/10/27/asp-net-mvc-asp-net-tips-provide-immediate-feedback-to-the-browser-on-long-running-tasks-using-regular-web-handler.aspx"&gt;earlier post&lt;/a&gt; we have discussed little bit about the limited number of worker threads available in the thread pool of ASP.NET and we identified why we should always try to avoid to block those important worker threads. ASP.NET 2.0 introduces Asyn=”true” attribute in the page to handle asynchronous scenarios and under the hood this attribute tells ASP.NET to implement IHttpAsyncHandler in the page. There are more than one ways available in ASP.NET 2.0 and ASP.NET 2.0 (plus) to register asynchronous tasks in the page, &lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;by AddOnPreRenderCompleteAsync method. &lt;/li&gt;    &lt;li&gt;by declaring PageAsynTask tasks and register them by RegisterAsyncTask method. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;   &lt;br /&gt;However PageAsyncTask provides some extra flexibility over AddOnPreRenderCompleteAsync method, for example &lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;it offers a timeout option. &lt;/li&gt;    &lt;li&gt;allows to register more than one async task. &lt;/li&gt;    &lt;li&gt;allows to configure async tasks to be executed in parallel or sequentially &lt;/li&gt;    &lt;li&gt;RegisterAsyncTask passes HttpContext.Current to the End and Timeout methods &lt;/li&gt;    &lt;li&gt;RegisterAsyncTask allows to pass object state to the Begin methods.      &lt;br /&gt;&lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Lets look at how we can implement an asynchronous page to serve our scenario that we are focusing here, that is, to run long tasks asynchronously and at the same time provide immediate feedback to the browser.&amp;#160; &lt;br /&gt;    &lt;br /&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/AsyncPageAspx_5F00_2784F9FE.png"&gt;&lt;img title="AsyncPageAspx" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="57" alt="AsyncPageAspx" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/AsyncPageAspx_5F00_thumb_5F00_3A19A81B.png" width="705" border="0" /&gt;&lt;/a&gt;     &lt;br /&gt;Fig: aspx page     &lt;br /&gt;&lt;/p&gt;  &lt;p&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/AsyncPage_5F00_7E814B6D.png"&gt;&lt;img title="AsyncPage" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="641" alt="AsyncPage" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/AsyncPage_5F00_thumb_5F00_76B375C2.png" width="632" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;Fig: code behind    &lt;br /&gt;    &lt;br /&gt;Here in the above code block I have left the AddOnPreRenderCompleteAsync code commented which can be used alternative to PageAsyncTask object &amp;amp; RegisterAsyncTask method. I have registered a PageAsyncTask task using RegisterAsyncTask method.&amp;#160; The “task” object is configured to point to – BeginAsyncOperation, EndAsyncOperation and TimeoutAsyncOperation functions. The BeginAsyncOperation does all the lengthy bits inside request.BeginProcessRequest() method and signals when completed, this executes the EndAsyncOperation method. However if the lengthy task is not completed within the timeout period, the TimeoutAsyncOperation executes.&amp;#160; Lets look at the AsyncRequest class now.     &lt;br /&gt;&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/AsyncRequest_5F00_3C5D2143.png"&gt;&lt;img title="AsyncRequest" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="632" alt="AsyncRequest" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/AsyncRequest_5F00_thumb_5F00_0CC6B4CA.png" width="733" border="0" /&gt;&lt;/a&gt;     &lt;br /&gt;    &lt;br /&gt;The most important thing to note here in the above piece of code is, I spawn an additional custom thread by hand and I execute the lengthy bits i.e. the “Process” Method in the custom thread. The Process method simulates the lengthy task by putting the thread to sleep. However note that the Response.Flush() does the magic to notify the connected browser about the task state immediately. It is a good idea to always check the Response.IsClientConnected property we discussed this in length in one of our &lt;a href="http://msmvps.com/blogs/shahed/archive/2009/10/27/asp-net-mvc-asp-net-tips-provide-immediate-feedback-to-the-browser-on-long-running-tasks-using-regular-web-handler.aspx"&gt;earlier post&lt;/a&gt;. &lt;/p&gt;  &lt;p&gt;As soon as the lengthy task completes I call the CompleteRequest method of the requestState object.&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;p&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/AsyncRequestState_5F00_644CF417.png"&gt;&lt;img title="AsyncRequestState" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="522" alt="AsyncRequestState" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/AsyncRequestState_5F00_thumb_5F00_5DC1269A.png" width="549" border="0" /&gt;&lt;/a&gt;     &lt;br /&gt;The CompleteRequest singnals that the asynchronous task is complete and it invokes the the callback method if available. In this example the callback invokes EndAsyncOperation method that we have configured in our PageAsyncTask object.&lt;/p&gt;  &lt;p&gt;You may be wondering why I had to spawn a custom thread to run the lengthy operation where we can simply use asynchronous delegate invocation. You must know that Delegate.Invoke consumes worker thread from the ASP.NET thread pool. Even though the page releases a worker thread into the pool but immediately that thread ( or another worker thread ) is again taken from the thread pool. Now this precious thread is occupied until the long task finishes hence you gain nothing rather add overhead of switching thread from the pool.&amp;#160; &lt;br /&gt;    &lt;br /&gt;Fritz Onion in his popular article “&lt;a href="http://msdn.microsoft.com/en-us/magazine/cc164128.aspx"&gt;Use Threads and Build Asynchronous Handlers in Your Server-Side Web Code&lt;/a&gt;” mentioned the same, “&lt;em&gt;Asynchronous delegate invocation completely defeats the purpose of building an asynchronous handler because it draws from the same process-wide CLR thread pool that ASP.NET uses to service requests. While the primary request thread is indeed returned to the thread pool, another thread is taken out to perform the asynchronous delegate execution, which means that there is a net gain of zero threads for servicing additional requests, rendering the handler useless. You will run into the same problem if you use ThreadPool.QueueUserWorkItem to perform the asynchronous request processing because it also draws threads from the same process-wide CLR thread pool&lt;/em&gt;”.     &lt;br /&gt;    &lt;br /&gt;Jeff Prosise also quoted him in his &lt;a href="http://msdn.microsoft.com/en-us/magazine/cc163725.aspx"&gt;article&lt;/a&gt; by saying “&lt;em&gt;Asynchronous delegates, are counterproductive in ASP.NET applications because they either steal threads from the thread pool or risk unconstrained thread growth. A proper asynchronous page implementation uses a custom thread pool, and custom thread pool classes are not trivial to write.&lt;/em&gt;”     &lt;br /&gt;    &lt;br /&gt;He also warned about it in his conclusion “&lt;em&gt;A final point to keep in mind as you build asynchronous pages is that you should not launch asynchronous operations that borrow from the same thread pool that ASP.NET uses. For example, calling ThreadPool.QueueUserWorkItem at a page&amp;#39;s asynchronous point is counterproductive because that method draws from the thread pool, resulting in a net gain of zero threads for processing requests&lt;/em&gt;”.     &lt;br /&gt;&lt;/p&gt;  &lt;p&gt;After all these warnings if you were still implementing the frequently recommended asynchronous delegation invocation ( unfortunately, most of the google search result on this topic of asynchronous programming in ASP.NET will lead to an implementation of asynchronous delegation ) it would look something like this:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/asyncdelegate_5F00_1E4096BF.png"&gt;&lt;img title="asyncdelegate" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="1110" alt="asyncdelegate" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/asyncdelegate_5F00_thumb_5F00_35934D43.png" width="733" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;I do not want to discuss about delegate invocation because it completely defeats the purpose of implementing Asynchronous pages. I have done some load testing on the above two implementations and found the following result:    &lt;br /&gt;    &lt;br /&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/testresultdelegateinvocation_5F00_0EE9E258.png"&gt;&lt;img title="testresultdelegateinvocation" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="93" alt="testresultdelegateinvocation" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/testresultdelegateinvocation_5F00_thumb_5F00_6918DD56.png" width="700" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Fig&lt;/strong&gt;: Load test result of asynchronous handlers with a delegate.&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;p&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/testresultthread_5F00_1F1FED15.png"&gt;&lt;img title="testresultthread" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="92" alt="testresultthread" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/testresultthread_5F00_thumb_5F00_6B7A1167.png" width="618" border="0" /&gt;&lt;/a&gt;     &lt;br /&gt;    &lt;br /&gt;&lt;strong&gt;Fig&lt;/strong&gt;: Load test result of asynchronous handler with custom thread.     &lt;br /&gt;    &lt;br /&gt;Clearly we see that we gain significantly on asynchronous handler that uses custom thread in both cases, &lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;requests/sec_total and &lt;/li&gt;    &lt;li&gt;avg. Respons_Total. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;   &lt;br /&gt;I got distracted a bit from our original subject matter again, but it was worth doing this one. I have already discussed here how we can run long running task asynchronously and how to provide immediate feedback to the connected browser immediately. In this post and previous posts I was implementing solutions by taking advantage of &lt;a href="http://msmvps.com/blogs/shahed/archive/2009/10/27/asp-net-mvc-asp-net-tips-provide-immediate-feedback-to-the-browser-on-long-running-tasks-by-streaming-regular-asp-net-page.aspx"&gt;ASP.NET page&lt;/a&gt; and &lt;a href="http://msmvps.com/blogs/shahed/archive/2009/10/27/asp-net-mvc-asp-net-tips-provide-immediate-feedback-to-the-browser-on-long-running-tasks-using-regular-web-handler.aspx"&gt;web handlers&lt;/a&gt; however we can also give immediate feedback to clients using MS AJAX, JQuery, XMLHTTPRequest, IFrame etc. in ASP.NET pages. &lt;a href="http://msmvps.com/blogs/shahed/archive/2009/10/27/asp-net-mvc-asp-net-tips-provide-feedback-to-the-user-on-long-running-tasks-using-loader-image-ms-ajax-and-jquery.aspx"&gt;Lets look at them one by one&lt;/a&gt;.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msdnbangladesh.net/aggbug.aspx?PostID=46969" width="1" height="1"&gt;</description></item><item><title>ASP.NET MVC, ASP.NET Tips: Provide immediate feedback to the browser on Long Running Tasks – by streaming regular ASP.NET page</title><link>http://msdnbangladesh.net/blogs/shahed/archive/2009/10/28/asp-net-mvc-asp-net-tips-provide-immediate-feedback-to-the-browser-on-long-running-tasks-by-streaming-regular-asp-net-page.aspx</link><pubDate>Tue, 27 Oct 2009 16:13:06 GMT</pubDate><guid isPermaLink="false">019a604b-fb74-42d5-8a6d-7cedfb08f61c:46964</guid><dc:creator>shahed</dc:creator><slash:comments>0</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msdnbangladesh.net/blogs/shahed/rsscomments.aspx?PostID=46964</wfw:commentRss><comments>http://msdnbangladesh.net/blogs/shahed/archive/2009/10/28/asp-net-mvc-asp-net-tips-provide-immediate-feedback-to-the-browser-on-long-running-tasks-by-streaming-regular-asp-net-page.aspx#comments</comments><description>&lt;p&gt;Here in this &lt;a href="http://msmvps.com/blogs/shahed/archive/2009/10/27/asp-net-mvc-asp-net-tips-provide-immediate-feedback-to-the-browser-on-long-running-tasks-using-regular-web-handler.aspx"&gt;series of post&lt;/a&gt; I am discussing few techniques to give client instant feedback on task progress in ASP.NET page. In the &lt;a href="http://msmvps.com/blogs/shahed/archive/2009/10/27/asp-net-mvc-asp-net-tips-provide-immediate-feedback-to-the-browser-on-long-running-tasks-using-regular-web-handler.aspx"&gt;previous post&lt;/a&gt; I have discussed about displaying task progress - using regular handler, here I will discuss how to do the same in standard asp.net page.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://msmvps.com/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed.metablogapi/0042.Download_5F00_6E95956F.jpg"&gt;&lt;img title="Download" height="79" alt="Download" src="http://msmvps.com/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed.metablogapi/4152.Download_5F00_thumb_5F00_0D04F7BB.jpg" width="64" border="0" /&gt;&lt;/a&gt;&amp;#160;&lt;a href="http://msmvps.com/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed.metablogapi/4251.AspnetWetsite_5F00_3A88A82F.zip"&gt;to download the source code please click here&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Display task progress – in standard asp.net page&lt;/strong&gt; &lt;/p&gt;  &lt;p&gt;In this technique we write some regular ASP.NET script in the page itself, that performs streaming to the original page response directly. We put the lengthy task related code in the page and keep flushing the response when task state changes. The data is pushed to the the pages outgoing stream and the browser immediately displays the output. The connection to the browser is kept open until the task is complete.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/PageStream_5F00_12563B51.png"&gt;&lt;img title="PageStream" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="394" alt="PageStream" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/PageStream_5F00_thumb_5F00_7605A6D8.png" width="640" border="0" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;p&gt;You see above I have written a regular ASP.NET page with some C# scripts that simulated a long running task by forcing the thread to sleep. However before the thread goes to sleep it Flushes the response using Response.Flush method.&amp;#160; I discussed about the Flush method in &lt;a href="http://msmvps.com/blogs/shahed/archive/2009/10/27/asp-net-mvc-asp-net-tips-provide-immediate-feedback-to-the-browser-on-long-running-tasks-using-regular-web-handler.aspx"&gt;earlier post&lt;/a&gt;. It basically facilitates to send buffered output to the browser immediately. The other thing to note here is the the Response.IsClientConnected property which indicates the server whether the browser is still connected or not. The Response.IsClientConnected property can determine if the browser is still connected. So when we perform a lengthy operation it is a good idea to periodically test&amp;#160; whether the browser is still connected.     &lt;br /&gt;    &lt;br /&gt;You may have already noticed that I am writing embedded javascript codes that manipulates the DOM. In this case this the ReportDiv elements innerHTML is assigned to latest flushed response. However to keep this example simple, I have been flushing the “report” string over and over again to reflect the changes in the browser and the same data is sent across the wire over and over. This may not be a good idea when you are flushing out a large report with 1000 records. You can reduce the amount of response traffic just by sending the progressive latest content only. To do this you will need to change your DOM manipulation code to perform append instead of replacement. Something like below.     &lt;br /&gt;&lt;/p&gt;  &lt;p&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/PageStreamOptimized_5F00_2BA7740E.png"&gt;&lt;img title="PageStreamOptimized" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="443" alt="PageStreamOptimized" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/PageStreamOptimized_5F00_thumb_5F00_042AC49B.png" width="640" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;Note that I have changed the codes to flush progressing latest content only, I have also modified the rendered javascript codes that is now appending latest flushed content to the existing content instead of replacement.&lt;/p&gt;  &lt;p&gt;The above example is serving the long task in a regular synchronous manner however It is a good idea to implement long running tasks asynchronously, &lt;a href="http://msmvps.com/blogs/shahed/archive/2009/10/27/asp-net-mvc-asp-net-tips-provide-immediate-feedback-to-the-browser-on-long-running-tasks-in-asynchronous-asp-net-pages.aspx"&gt;lets look at that in the next post&lt;/a&gt;.     &lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msdnbangladesh.net/aggbug.aspx?PostID=46964" width="1" height="1"&gt;</description></item><item><title>ASP.NET MVC, ASP.NET Tips: Provide immediate feedback to the browser on Long Running Tasks – using regular web handler</title><link>http://msdnbangladesh.net/blogs/shahed/archive/2009/10/28/asp-net-mvc-asp-net-tips-provide-immediate-feedback-to-the-browser-on-long-running-tasks-using-regular-web-handler.aspx</link><pubDate>Tue, 27 Oct 2009 16:10:17 GMT</pubDate><guid isPermaLink="false">019a604b-fb74-42d5-8a6d-7cedfb08f61c:46962</guid><dc:creator>shahed</dc:creator><slash:comments>0</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msdnbangladesh.net/blogs/shahed/rsscomments.aspx?PostID=46962</wfw:commentRss><comments>http://msdnbangladesh.net/blogs/shahed/archive/2009/10/28/asp-net-mvc-asp-net-tips-provide-immediate-feedback-to-the-browser-on-long-running-tasks-using-regular-web-handler.aspx#comments</comments><description>&lt;p&gt;As an ASP.NET developer we frequently deal with long running tasks for example:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Making long-lasting webservice calls. &lt;/li&gt;    &lt;li&gt;Making prolonged calls to database that runs complex queries. &lt;/li&gt;    &lt;li&gt;Do lengthy file operation &lt;/li&gt;    &lt;li&gt;Calling remote objects etc. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;When the server is busy performing the lengthy time consuming task/tasks, the poor user has to wait for the response. The most common technique used to interact with user is to display a loader icon or show some kind of progress bar on the page until the task is complete. However we can provide user immediate feedback of the task progress/state while the task is running in the Server and make the page more interactive/informative. &lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/iframefeedback_5F00_55C4BFD6.png"&gt;&lt;img title="iframefeedback" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="443" alt="iframefeedback" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/iframefeedback_5F00_thumb_5F00_4646CF69.png" width="497" border="0" /&gt;&lt;/a&gt;     &lt;br /&gt;    &lt;br /&gt;Here we will discuss several techniques to give end user instant feedback on the browser about task progress in&amp;#160; ASP.NET pages.     &lt;br /&gt;    &lt;br /&gt;such as display:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;task progress - using regular web handler. &lt;/li&gt;    &lt;li&gt;&lt;a href="http://msmvps.com/blogs/shahed/archive/2009/10/27/asp-net-mvc-asp-net-tips-provide-immediate-feedback-to-the-browser-on-long-running-tasks-by-streaming-regular-asp-net-page.aspx"&gt;task progress – in standard ASP.NET page&lt;/a&gt;. &lt;/li&gt;    &lt;li&gt;&lt;a href="http://msmvps.com/blogs/shahed/archive/2009/10/27/asp-net-mvc-asp-net-tips-provide-immediate-feedback-to-the-browser-on-long-running-tasks-in-asynchronous-asp-net-pages.aspx"&gt;task progress – in asynchronous ASP.NET page&lt;/a&gt;. &lt;/li&gt;    &lt;li&gt;&lt;a href="http://msmvps.com/blogs/shahed/archive/2009/10/27/asp-net-mvc-asp-net-tips-provide-feedback-to-the-user-on-long-running-tasks-using-loader-image-ms-ajax-and-jquery.aspx"&gt;task progress - using JQuery&lt;/a&gt;. &lt;/li&gt;    &lt;li&gt;&lt;a href="http://msmvps.com/blogs/shahed/archive/2009/10/27/asp-net-mvc-asp-net-tips-provide-feedback-to-the-user-on-long-running-tasks-using-loader-image-ms-ajax-and-jquery.aspx"&gt;task progress - using MS Ajax&lt;/a&gt;. &lt;/li&gt;    &lt;li&gt;&lt;a href="http://msmvps.com/blogs/shahed/archive/2009/10/27/asp-net-mvc-asp-net-tips-provide-immediate-feedback-to-the-browser-on-long-running-tasks-using-xmlhttprequest-call.aspx"&gt;task progress - using XmlHTTP RequestState&lt;/a&gt;. &lt;/li&gt;    &lt;li&gt;&lt;a href="http://msmvps.com/blogs/shahed/archive/2009/10/27/asp-net-mvc-asp-net-tips-provide-immediate-feedback-to-the-browser-on-long-running-tasks-using-iframe-and-web-handlers.aspx"&gt;task progress - using IFrame and regular web handler&lt;/a&gt;. &lt;/li&gt;    &lt;li&gt;&lt;a href="http://msmvps.com/blogs/shahed/archive/2009/10/27/asp-net-mvc-asp-net-tips-provide-immediate-feedback-to-the-browser-on-long-running-tasks-using-iframe-and-web-handlers.aspx"&gt;task progress - using IFrame and asynchronous web handler&lt;/a&gt;. &lt;/li&gt;    &lt;li&gt;task progress - by polling a webservice. / web handler &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;&amp;#160; &lt;br /&gt;&lt;a href="http://msmvps.com/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed.metablogapi/0042.Download_5F00_6E95956F.jpg"&gt;&lt;img title="Download" height="79" alt="Download" src="http://msmvps.com/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed.metablogapi/4152.Download_5F00_thumb_5F00_0D04F7BB.jpg" width="64" border="0" /&gt;&lt;/a&gt;&amp;#160;&lt;a href="http://msmvps.com/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed.metablogapi/4251.AspnetWetsite_5F00_3A88A82F.zip"&gt;to download the source code please click here&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;     &lt;br /&gt;Display task progress using regular web handler:&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;This is very easy to code, all we need to do is write a regular web handler that runs the long running task and we have to keep flushing the response when state changes, in other words we decide to flush when the task reaches certain stage. The data is pushed to the the outgoing stream and the browser immediately displays the output. The connection to the browser is kept open until the task is complete.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/RegularHandler_5F00_26BCA0F6.png"&gt;&lt;img title="RegularHandler" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="486" alt="RegularHandler" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/RegularHandler_5F00_thumb_5F00_57775AB4.png" width="738" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;We have created a regular web handler that inherits from IHttpHandler and simulated a long running task by forcing the thread to sleep. However before the thread goes to sleep it Flushes the response using Response.Flush() method. The Flush method sends buffered output immediately. Normally all of the response is sent to the browser only when page completes its processing. This may be a issue for a long running task as the end user will not see anything until the page is complete. The Flush method comes handy in this situation and can send buffered output periodically to the browser. Imagine you will have to display 500 records and you can flush the buffer every 20 records until it is complete. The good thing of doing this is – user can see some data immediately, visualize the progress of the report and the server memory is also released on every Flush operation.    &lt;br /&gt;    &lt;br /&gt;One more thing to note is the Response.IsClientConnected property which indicates the server whether the browser is still connected or has already left.&amp;#160; A very common scenario is user starts the long expensive task but decided to close the browser before the task is complete. When a browser requests the page from the server but does not wait for the entire page to be downloaded, the server continues to process the request, wasting CPU cycles. The Response.IsClientConnected property can determine if the browser is still connected or not. So when we perform a long task it is always a good idea to periodically test&amp;#160; whether the browser is still connected or not.     &lt;br /&gt;    &lt;br /&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/UseHandler_5F00_2CC11146.png"&gt;&lt;img title="UseHandler" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="55" alt="UseHandler" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/UseHandler_5F00_thumb_5F00_20C1B1C3.png" width="497" border="0" /&gt;&lt;/a&gt;&amp;#160; &lt;br /&gt;A web handler file works just like a aspx page and can be directly browsed via a browser. The web handler above, returns response type text/html and we have pointed an anchor tag to the web handler. Please note a web handler is recommended for a performance critical web page.&lt;/p&gt;  &lt;p&gt;I have started with a regular synchronous web handler, however it is recommended to use asynchronous web handlers that implements IHttpAsyncHandler for long running tasks. ASP.NET has limited number of threads in the thread pool and a normal synchronous page holds on to the thread for the duration of the request, and this thread is prevented to be used to process any other request during that period. As a result the thread gets stuck until the lengthy request is complete. If all the threads are stuck doing lengthy tasks the subsequent additional requests starts to queue up and when the queue fill up ASP.NET starts spitting 503 “Server Unavailable” errors.    &lt;br /&gt;    &lt;br /&gt;ASP.NET provides a neater solution to this problem via Asynchrounous web handlers that implements the IHtttpAsyncHandler. The interface suggests to implement two additional methods BeginProcessRequest method and&amp;#160; EndProcessRequest. The idea is to spawn&amp;#160; an additional thread by hand in response to BeginProcessRequest, then perform the lengthy task in this additional thread and notify when the task is complete so the worker thread can return a response to the user.&amp;#160; We will look at Asynchronous web handlers in a later post in more details. Lets continue to look at &lt;a href="http://msmvps.com/blogs/shahed/archive/2009/10/27/asp-net-mvc-asp-net-tips-provide-immediate-feedback-to-the-browser-on-long-running-tasks-by-streaming-regular-asp-net-page.aspx"&gt;other techniques now&lt;/a&gt;.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msdnbangladesh.net/aggbug.aspx?PostID=46962" width="1" height="1"&gt;</description></item><item><title>Microsoft WebsiteSpark – Receive Windows Web Server and SQL Server Web Edition at no cost to host new websites</title><link>http://msdnbangladesh.net/blogs/shahed/archive/2009/09/25/microsoft-websitespark-receive-windows-web-server-and-sql-server-web-edition-at-no-cost-to-host-new-websites.aspx</link><pubDate>Fri, 25 Sep 2009 03:37:15 GMT</pubDate><guid isPermaLink="false">019a604b-fb74-42d5-8a6d-7cedfb08f61c:30010</guid><dc:creator>shahed</dc:creator><slash:comments>0</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msdnbangladesh.net/blogs/shahed/rsscomments.aspx?PostID=30010</wfw:commentRss><comments>http://msdnbangladesh.net/blogs/shahed/archive/2009/09/25/microsoft-websitespark-receive-windows-web-server-and-sql-server-web-edition-at-no-cost-to-host-new-websites.aspx#comments</comments><description>&lt;p&gt;Now help is on the way in the form of Microsoft WebsiteSpark, a program announced today that will empower Web site design and Web application development firms with 10 or fewer employees. WebsiteSpark provides development tools, production licenses for server products, technical support, business development support, and access to the expertise and services of Microsoft’s community of partners and hosters.   &lt;br /&gt;    &lt;br /&gt;visit &lt;a href="http://www.microsoft.com/web/websitespark"&gt;http://www.microsoft.com/web/websitespark&lt;/a&gt; to learn more&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msdnbangladesh.net/aggbug.aspx?PostID=30010" width="1" height="1"&gt;</description></item><item><title>ASP.NET, ASP.NET MVC Tips: JSON Handler, Aspx template, Asynchronous JQuery treeview with ashx generic handler and many more.</title><link>http://msdnbangladesh.net/blogs/shahed/archive/2009/08/23/asp-net-asp-net-mvc-tips-json-handler-aspx-template-asynchronous-jquery-treeview-with-ashx-generic-handler-and-many-more.aspx</link><pubDate>Sat, 22 Aug 2009 19:05:07 GMT</pubDate><guid isPermaLink="false">019a604b-fb74-42d5-8a6d-7cedfb08f61c:19120</guid><dc:creator>shahed</dc:creator><slash:comments>0</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msdnbangladesh.net/blogs/shahed/rsscomments.aspx?PostID=19120</wfw:commentRss><comments>http://msdnbangladesh.net/blogs/shahed/archive/2009/08/23/asp-net-asp-net-mvc-tips-json-handler-aspx-template-asynchronous-jquery-treeview-with-ashx-generic-handler-and-many-more.aspx#comments</comments><description>&lt;p&gt;In my &lt;a title="" href="http://msmvps.com/blogs/shahed/archive/2009/07/11/asp-net-tips-getting-asynchronous-jquery-treeview-to-work-with-asp-net-webservices.aspx"&gt;previous blog post&lt;/a&gt;, I have discussed about how to get asynchronous JQuery treevew to work with ASP.NET Webservices, and we identified that, to make a successful ASP.NET webservice call using JQuery the request must be POST request, the content type of the request must be “application/json; charset=utf-8”, and the data parameter of the the $.ajax() method must be passed as a string. We also looked at the tweaks that we need to do to the jquery.treeview.async.js file to get that working.     &lt;br /&gt;    &lt;br /&gt;However I found the JQuery, $.ajax() method can consume JSON objects straightway from the ASP.NET Generic Handler (ashx) that can be designed to serve a JSON response. If you are using ASP.NET MVC framework you will find that $.ajax() can also consume JSON response without hassle from MVC controller actions that returns a JsonResult. I will demonstrate both scenario with my FictitiousWebsite.com. &lt;/p&gt;  &lt;p&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/fictitiouswebsite_5F00_60251C93.png"&gt;&lt;img title="fictitiouswebsite" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="604" alt="fictitiouswebsite" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/fictitiouswebsite_5F00_thumb_5F00_5210705A.png" width="604" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Fig: FictitiousWebsite.com&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;Lets look at the ASP.NET MVC Fictitious website application first,    &lt;br /&gt;&lt;strong&gt;     &lt;br /&gt;ASP.NET MVC Application&lt;/strong&gt;&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;I have put together two classes (TreeService, TheTreeNode) that generates story categories and subcategories as seen in the screenshot above - [&lt;em&gt;categories&lt;/em&gt;: “.NET, ASP.NET MVC, AJAX, ADO.NET”, &lt;em&gt;subcategories&lt;/em&gt;: “Latest articles, Forum post”]. The TreeService class returns story catetories and subcategories as List&amp;lt;TheTreeNode&amp;gt;.       &lt;br /&gt;      &lt;br /&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/TreeService_5F00_54057176.png"&gt;&lt;img title="TreeService" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="545" alt="TreeService" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/TreeService_5F00_thumb_5F00_037E2307.png" width="516" border="0" /&gt;&lt;/a&gt;       &lt;br /&gt;&amp;#160; &lt;/li&gt;    &lt;li&gt;Then I have designed an MVC controller action to return JsonResult. This serves the Jquery treeview control with the list of story categories and subcategories as JSON response.      &lt;br /&gt;      &lt;br /&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/ControllerAction_5F00_763F4C06.png"&gt;&lt;img title="ControllerAction" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="283" alt="ControllerAction" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/ControllerAction_5F00_thumb_5F00_0DFBA4CF.png" width="390" border="0" /&gt;&lt;/a&gt;       &lt;br /&gt;I have used “d” variable here to replicate the security feature that has been added to ASP.NET 3.5 JSON serialization, you will notice the JSON response is encapsulated within a parent object to address a nasty vulnerability. You can read more about this vulnerability that Phil Haack has discussed in this post “&lt;a title="" href="http://haacked.com/archive/2009/06/25/json-hijacking.aspx"&gt;Json Hijacking&lt;/a&gt;”. Encapsulating the JSON response results the following response .       &lt;br /&gt;      &lt;br /&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/JsonResponse_5F00_63455B60.png"&gt;&lt;img title="JsonResponse" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="127" alt="JsonResponse" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/JsonResponse_5F00_thumb_5F00_6A1FA0E9.png" width="700" border="0" /&gt;&lt;/a&gt;&amp;#160;&amp;#160; &lt;br /&gt;&lt;/li&gt;    &lt;li&gt;The I have created a View - “LatestStories.aspx” that hosts the JQuery treeview control.      &lt;br /&gt;      &lt;br /&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/ViewPage_5F00_1A6E27B3.png"&gt;&lt;img title="ViewPage" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="451" alt="ViewPage" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/ViewPage_5F00_thumb_5F00_08B63F3B.png" width="607" border="0" /&gt;&lt;/a&gt;&amp;#160;&amp;#160; &lt;br /&gt;      &lt;br /&gt;Note that , the treeview control is communicating to my MVC controller discusssed in previous step, through this URL, “/Home/GetStoryList”. You will also notice that I have decoraded a fileClick event for the treeView. When user clicks the subcategories, it asynchronously/on demand gets the relevant list of stories from this URL “/Home/Stories” and renders to the right side panel. This fileclick event do not ship with treeview out of the box, I had to inject 2 lines of code to the original “jquery.treeview.async.js” file to get this happening.       &lt;br /&gt;      &lt;br /&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/asyncjs_5F00_692C10C7.png"&gt;&lt;img title="asyncjs" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="330" alt="asyncjs" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/asyncjs_5F00_thumb_5F00_0E4E7C96.png" width="495" border="0" /&gt;&lt;/a&gt;       &lt;br /&gt;      &lt;br /&gt;&lt;/li&gt;    &lt;li&gt;Finally I decorated a aspx template - “Stories.aspx” that serves the necessary html content for the right side panel.      &lt;br /&gt;      &lt;br /&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/template_5F00_687D7794.png"&gt;&lt;img title="template" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="670" alt="template" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/template_5F00_thumb_5F00_59FC9866.png" width="607" border="0" /&gt;&lt;/a&gt;       &lt;br /&gt;I prefer using templates as aspx files, as I can take full advantage of the intellisense and design support of the Visual Studio. Plus I have the entire ASP.NET MVC framework to back me up to produce and render dynamic contents on demand.       &lt;br /&gt;&lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;It is very straight forward to consume JSON response in the ASP.NET MVC framework, however the same is not as easy when we deal with ASP.NET Webservices as discussed in my &lt;a title="" href="http://msmvps.com/blogs/shahed/archive/2009/07/11/asp-net-tips-getting-asynchronous-jquery-treeview-to-work-with-asp-net-webservices.aspx"&gt;previous post&lt;/a&gt;. ASP.NET Webservices is not the only way we can serve JSON response, lets look at how we can design a ASP.NET Generic Handler (ashx) to serve the same. Plus you will also find in a moment that ashx can be more easily consumed by the JQuery $.ajax() method.     &lt;br /&gt;    &lt;br /&gt;&lt;strong&gt;ASP.NET 3.5 Website&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;I have created an exact replica of the FictitiousWebsite.com in an ASP.NET 3.5 website project. This website project has exact same files as the ASP.NET MVC application, with very minor differences.&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;Here look at the ASP.NET solution explorer snap to get a quick rundown of the similarities and the differences.      &lt;br /&gt;      &lt;br /&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/aspnet_5F00_32E98B37.png"&gt;&lt;img title="aspnet" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="356" alt="aspnet" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/aspnet_5F00_thumb_5F00_10B931C4.png" width="600" border="0" /&gt;&lt;/a&gt;       &lt;br /&gt;&lt;/li&gt;    &lt;li&gt;The (TreeService.cs, TheTreeNode.cs) files are exactly same as before and generates list of story categories and subcategories.      &lt;br /&gt;&lt;/li&gt;    &lt;li&gt;The ASP.NET Generic Handler (ashx) file “GetStoryListJsonHandler.ashx” serves JSON response to the Jquery treeview control with the list of story categories and subcategories.      &lt;br /&gt;      &lt;br /&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/GenericHandlerJson_5F00_2392D6D0.png"&gt;&lt;img title="GenericHandlerJson" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="525" alt="GenericHandlerJson" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/GenericHandlerJson_5F00_thumb_5F00_008CA824.png" width="629" border="0" /&gt;&lt;/a&gt;       &lt;br /&gt;      &lt;br /&gt;You may already recall that we have written similar code in the MVC controller that was invoking the TreeService and&amp;#160; returning JsonResult. I have decorated this Generic Handler (ashx) in the similar way. Note I have defined the ContentType = “application/json”, and serialized the data with JavaScriptSerializer. I have also used the “d” variable to replicate the security feature that has been added to ASP.NET 3.5 JSON serialization as before. This results exactly same output as we have seen in the MVC framework earlier. The best part is JQuery $.ajax() method can consume this without any hassle as we have faced earlier to communicate to the ASP.NET Webservice method.       &lt;br /&gt;      &lt;br /&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/ashxoutput_5F00_479A7676.png"&gt;&lt;img title="ashxoutput" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="142" alt="ashxoutput" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/ashxoutput_5F00_thumb_5F00_75AF0534.png" width="767" border="0" /&gt;&lt;/a&gt;       &lt;br /&gt;&lt;/li&gt;    &lt;li&gt;The “LatestStories.aspx” hosts the treeview control, the only difference you will note here is it now communicates with the ASP.NET Generic Handler (ashx) file, and the fileClick communicates to the “Stories.aspx” template.      &lt;br /&gt;      &lt;br /&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/latestStories_5F00_31FCEB81.png"&gt;&lt;img title="latestStories" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="476" alt="latestStories" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/latestStories_5F00_thumb_5F00_672E2606.png" width="633" border="0" /&gt;&lt;/a&gt;&amp;#160; &lt;br /&gt;&lt;/li&gt;    &lt;li&gt;The “Stories.aspx” file (template) serves the necessary html content to display the list of stories to the right side panel. This page is now backed up by the ASP.NET web forms framework, WYSIWYG designer support in Visual Studio and allows to render dynamic contents easily. &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;We have discussed, how we can serve JSON response in both ASP.NET MVC and ASP.NET 3.5 website framework. We have identified that consuming a JSON response from ASP.NET Webservice requires some extra steps in the JQuery world, we have demonstrated an alternative approach to serve JSON response using Generic Handler (ashx) and found it easier to consume via JQuery $.ajax() method. While designing the JSON response we used “d” variable to replicate the security feature that has been added to ASP.NET 3.5 JSON serialization. We also looked at rendering dynamic content asynchronously on demand, and identified the advantage of aspx templates as it can be designed using the WYSIWYG designer, intellisense, compilation, dubug, sourceview, splitview, codebehind and all the features of Visual studio and the the ASP.NET framework.    &lt;br /&gt;    &lt;br /&gt;The ficitiouswebsite.com demonstrates everything that we have discussed above and is available to &lt;/p&gt;  &lt;div class="wlWriterEditableSmartContent" id="scid:fb3a1972-4489-4e52-abe7-25a00bb07fdf:f5c12dee-f410-4376-b615-a4415512a2f0" style="padding-right:0px;display:inline;padding-left:0px;float:none;padding-bottom:0px;margin:0px;padding-top:0px;"&gt;&lt;p&gt; &lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/fictitiouswebsite.com_5F00_39D1B198.zip" target="_blank"&gt;download here&lt;/a&gt;&lt;/p&gt;&lt;/div&gt;  &lt;p&gt;Thank you for being with me so far, Happy Coding.    &lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msdnbangladesh.net/aggbug.aspx?PostID=19120" width="1" height="1"&gt;</description></item><item><title>ASP.NET Tips : Getting asynchronous JQuery treeview to work with ASP.NET Webservices</title><link>http://msdnbangladesh.net/blogs/shahed/archive/2009/07/11/asp-net-tips-getting-asynchronous-jquery-treeview-to-work-with-asp-net-webservices.aspx</link><pubDate>Fri, 10 Jul 2009 13:09:01 GMT</pubDate><guid isPermaLink="false">019a604b-fb74-42d5-8a6d-7cedfb08f61c:1441</guid><dc:creator>shahed</dc:creator><slash:comments>0</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msdnbangladesh.net/blogs/shahed/rsscomments.aspx?PostID=1441</wfw:commentRss><comments>http://msdnbangladesh.net/blogs/shahed/archive/2009/07/11/asp-net-tips-getting-asynchronous-jquery-treeview-to-work-with-asp-net-webservices.aspx#comments</comments><description>&lt;p&gt;Recently I had to display some hierarchical data in a treeview. I looked around and found &lt;a href="http://bassistance.de/jquery-plugins/jquery-plugin-treeview/"&gt;JQuery treeview&lt;/a&gt; can transforms an unordered list into an expandable and collapsable tree, and supports both location and cookie based persistence.     &lt;br /&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/treeview1_5F00_4.png"&gt;&lt;img style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="502" alt="treeview1" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/treeview1_5F00_thumb_5F00_1.png" width="689" border="0" /&gt;&lt;/a&gt;     &lt;br /&gt;&lt;strong&gt;Fig: JQuery Treeview&lt;/strong&gt;     &lt;br /&gt;    &lt;br /&gt;As I was dealing with a large amount of data I needed something that will allow me to navigate through the data asynchronously, and I found &lt;a href="http://bassistance.de/jquery-plugins/jquery-plugin-treeview/"&gt;jQuery Treeview&lt;/a&gt; fits well for my purpose. I found this &lt;a href="http://jquery.bassistance.de/treeview/demo/async.html"&gt;demo of Lazy Loading Tree&lt;/a&gt; and I needed to implement similar functionality where the JQuety Treeview communicates to a ASP.NET Webservice.     &lt;br /&gt;    &lt;br /&gt;&lt;strong&gt;Problem 1&lt;/strong&gt;: Unfortunately the codes that ships with the demo do not work with ASP.NET Webservice out of the box. First of all if you have downloaded the TreeView plugin from this link &lt;a title="http://bassistance.de/jquery-plugins/jquery-plugin-treeview/" href="http://bassistance.de/jquery-plugins/jquery-plugin-treeview/"&gt;http://bassistance.de/jquery-plugins/jquery-plugin-treeview/&lt;/a&gt; you will notice the &amp;quot;jquery.treeview.async.js&amp;quot; file uses $.getJSON method to make AJAX calls to the server. But this is no good for ASP.NET webservice or WCF which expect JSON POST , this function is only useful for simple JSON results returned from arbitrary services.     &lt;br /&gt;    &lt;br /&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/treeviewasync_5F00_2.png"&gt;&lt;img style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="479" alt="treeviewasync" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/treeviewasync_5F00_thumb.png" width="753" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Problem 2:&lt;/strong&gt; However if you download the jquery.treeview.async.js from &lt;a title="http://view.jquery.com/trunk/plugins/treeview" href="http://view.jquery.com/trunk/plugins/treeview"&gt;http://view.jquery.com/trunk/plugins/treeview&lt;/a&gt; you will notice the $.getJSON function is commented and an alternative $ajax() method has been used.     &lt;br /&gt;    &lt;br /&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/treeviewasync2_5F00_2.png"&gt;&lt;img style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="515" alt="treeviewasync2" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/treeviewasync2_5F00_thumb.png" width="632" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;but this one is still not good for ASP.NET Webservice calls, I am explaining this in a moment.    &lt;br /&gt;    &lt;br /&gt;There are several options available in JQuery to make AJAX calls to the server. They are     &lt;br /&gt;1. &lt;a href="http://docs.jquery.com/Ajax/jQuery.ajax"&gt;$.ajax(opt)&lt;/a&gt;,     &lt;br /&gt;2. &lt;a href="http://docs.jquery.com/Ajax/load"&gt;$(sel).load(url,data,callback)&lt;/a&gt;     &lt;br /&gt;3. &lt;a href="http://docs.jquery.com/Ajax/jQuery.get#urldatacallbacktype"&gt;$.get(url,data,callback,type)&lt;/a&gt;     &lt;br /&gt;4. &lt;a href="http://docs.jquery.com/Ajax/jQuery.post#urldatacallbacktype"&gt;$.post(url,data,callback,type)&lt;/a&gt;     &lt;br /&gt;5. &lt;a href="http://docs.jquery.com/Ajax/jQuery.getJSON#urldatacallback"&gt;$.getJSON(url,data,callback)&lt;/a&gt;     &lt;br /&gt;6. &lt;a href="http://docs.jquery.com/Ajax/jQuery.getScript#urlcallback"&gt;$.getScript(url,callback)&lt;/a&gt;     &lt;br /&gt;    &lt;br /&gt;The complete list of JQuery AJAX &amp;quot;Requests&amp;quot; and &amp;quot;Event&amp;quot; based functions are all &lt;a href="http://docs.jquery.com/Ajax"&gt;listed here&lt;/a&gt;. However to get JQuery working with ASP.NET Webservices we should be interested with $.ajax(opt) function, a low level Ajax function which offers to create any kind of Ajax request. This allow us to configure Ajax request with a set of key/value pairs, and all options are optional. We should be aware that ASP.NET AJAX 1.0 includes a number of default settings and built-in features to prevent from JSON hijacking attacks, ASP.NET AJAX webmethods do not enable HTTP GET requests by default. To make a successful call to the ASP.NET webservice using JQuery we need to make sure that the request must be a POST request, and the request&amp;#39;s content-type must be: &amp;quot;application/json; charset=utf-8. By now you have already realized that the above $.ajax() call do not fit any of these two requirements. So I attempted to fulfill these requirements and passed more option paramameters as part of the $.ajax() call.     &lt;br /&gt;    &lt;br /&gt;&lt;strong&gt;Problem 3&lt;/strong&gt;: I modified the script to fit the requirements     &lt;br /&gt;- the request must be a POST request     &lt;br /&gt;- the request&amp;#39;s content-type must be: &amp;quot;application/json; charset=utf-8     &lt;br /&gt;    &lt;br /&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/treeviewasync3_5F00_2.png"&gt;&lt;img style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="230" alt="treeviewasync3" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/treeviewasync3_5F00_thumb.png" width="576" border="0" /&gt;&lt;/a&gt;     &lt;br /&gt;    &lt;br /&gt;However this did not work either. now I started facing another problem, &amp;quot;Invalid JSON primitive: root.&amp;quot;     &lt;br /&gt;    &lt;br /&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/invalidJSON_5F00_2.png"&gt;&lt;img style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="248" alt="invalidJSON" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/invalidJSON_5F00_thumb.png" width="896" border="0" /&gt;&lt;/a&gt;&amp;#160; &lt;br /&gt;&lt;/p&gt;  &lt;p&gt;After googling on this issue for a while I found, as the data parameter is a valid JSON object, calling the webservice in this way do not throw any exception, but it also do not produce the desired result either. Instead of passing the data JSON object to the webservice, JQuery automatically serializes and sends it as root = source.    &lt;br /&gt;    &lt;br /&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/JSONserialize_5F00_2.png"&gt;&lt;img style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="135" alt="JSONserialize" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/JSONserialize_5F00_thumb.png" width="482" border="0" /&gt;&lt;/a&gt;     &lt;br /&gt;The solution is to make sure that we pass data parameter as a string instead of a JSON object. Encosia.com has a very good post on this subject &amp;quot;&lt;a href="http://encosia.com/2008/06/05/3-mistakes-to-avoid-when-using-jquery-with-aspnet-ajax/"&gt;3 mistakes to avoid when using JQuery with ASP.NET AJAX&lt;/a&gt;&amp;quot;, a must read. Finally I adjusted the script as follows and it started working as desired.     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/treeviewFinal_5F00_6.png"&gt;&lt;img style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="202" alt="treeviewFinal" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/treeviewFinal_5F00_thumb_5F00_2.png" width="567" border="0" /&gt;&lt;/a&gt;     &lt;br /&gt;&amp;#160; &lt;br /&gt;    &lt;br /&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;I have discussed how to get JQuery treeview working with ASP.NET Webservice. Out of the box treeview ships with &amp;quot;jquery.treeview.async.js&amp;quot; file that is not compatible with ASP.NET Webservices or WCF. To make a successful call to the ASP.NET webservice using JQuery we need to make sure    &lt;br /&gt;- the request must be a POST request, and     &lt;br /&gt;- the request&amp;#39;s content-type must be: &amp;quot;application/json; charset=utf-8.     &lt;br /&gt;- the data parameter of the $.ajax() method must be passed as a string.     &lt;br /&gt;    &lt;br /&gt;I hope this will save you some time. Thank you for being with me so far.     &lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msdnbangladesh.net/aggbug.aspx?PostID=1441" width="1" height="1"&gt;</description></item><item><title>ASP.NET MVC Tips: 301 Redirect non-www versions of URL to www.</title><link>http://msdnbangladesh.net/blogs/shahed/archive/2009/05/19/asp-net-mvc-tips-301-redirect-non-www-versions-of-url-to-www.aspx</link><pubDate>Mon, 18 May 2009 13:50:30 GMT</pubDate><guid isPermaLink="false">019a604b-fb74-42d5-8a6d-7cedfb08f61c:1019</guid><dc:creator>shahed</dc:creator><slash:comments>0</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msdnbangladesh.net/blogs/shahed/rsscomments.aspx?PostID=1019</wfw:commentRss><comments>http://msdnbangladesh.net/blogs/shahed/archive/2009/05/19/asp-net-mvc-tips-301-redirect-non-www-versions-of-url-to-www.aspx#comments</comments><description>  &lt;p&gt;Search Engine Optimization guides, recommends to have one version of a URL of the same content. Search engines may pickup www and non-www versions of URL as 2 separate URLs, i.e. &lt;a href="http://xyz.com/page1"&gt;http://xyz.com/page1&lt;/a&gt; may be considered different to &lt;a href="http://www.xyz.com/page1"&gt;http://www.xyz.com/page1&lt;/a&gt;. It is a good idea to pick on of these URLs as preferred and use 301 redirects to send traffic from the other URLS to the preferred URL. Today we will pickup www version of URL as our preferred URL and look at how we can redirect the non-www version of the URL to our preferred URL structure using ASP.NET MVC.     &lt;br /&gt;    &lt;br /&gt;    &lt;br /&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/Workflow_5F00_2.png"&gt;&lt;img style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="362" alt="Workflow" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/Workflow_5F00_thumb.png" width="607" border="0" /&gt;&lt;/a&gt;&amp;#160; &lt;br /&gt;    &lt;br /&gt;We can achieve the above by writing a custom handler that extends from the MvcHandler. We are basically interested in the ProcessRequest method where we can get hold of the non-www version of the URL to replace it to the www. version of URL.&lt;/p&gt;  &lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;    public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; The301GlobalHandler : MvcHandler
    {
        &lt;span class="kwrd"&gt;public&lt;/span&gt; The301GlobalHandler(RequestContext requestContext) : &lt;span class="kwrd"&gt;base&lt;/span&gt;(requestContext) { }

        &lt;span class="kwrd"&gt;protected&lt;/span&gt; &lt;span class="kwrd"&gt;override&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; ProcessRequest(HttpContextBase httpContext)
        {
            &lt;span class="rem"&gt;//We do not want this handler to process local requests&lt;/span&gt;
&lt;strong&gt;            &lt;span class="kwrd"&gt;if&lt;/span&gt; (httpContext.Request.IsLocal)&lt;/strong&gt;
                &lt;span class="kwrd"&gt;base&lt;/span&gt;.ProcessRequest(httpContext);
            &lt;span class="kwrd"&gt;else&lt;/span&gt;
                ProcessExternalRequest(httpContext);
        }

        &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; ProcessExternalRequest(HttpContextBase httpContext)
        {
            &lt;span class="kwrd"&gt;bool&lt;/span&gt; urlChanged = &lt;span class="kwrd"&gt;false&lt;/span&gt;;
            &lt;span class="kwrd"&gt;string&lt;/span&gt; url = RequestContext.HttpContext.Request.Url.AbsoluteUri;
            &lt;span class="rem"&gt;//Check for non-www version URL&lt;/span&gt;
&lt;strong&gt;            &lt;span class="kwrd"&gt;if&lt;/span&gt; (!RequestContext.HttpContext.Request.Url.AbsoluteUri.Contains(&lt;span class="str"&gt;&amp;quot;www&amp;quot;&lt;/span&gt;))&lt;/strong&gt;
            {
                urlChanged = &lt;span class="kwrd"&gt;true&lt;/span&gt;;
                &lt;span class="rem"&gt;//change to www. version URL&lt;/span&gt;
&lt;strong&gt;                url = url.Replace(&lt;span class="str"&gt;&amp;quot;http://&amp;quot;&lt;/span&gt;, &lt;span class="str"&gt;&amp;quot;http://www.&amp;quot;&lt;/span&gt;);  &lt;/strong&gt;                  
            }
            ProcessExternalRequest(url, urlChanged, httpContext);
        }

        &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; ProcessExternalRequest(&lt;span class="kwrd"&gt;string&lt;/span&gt; url, &lt;span class="kwrd"&gt;bool&lt;/span&gt; urlChanged, HttpContextBase httpContext)
        {
            &lt;span class="kwrd"&gt;if&lt;/span&gt; (urlChanged)
            {
                &lt;span class="rem"&gt;//mark as 301&lt;/span&gt;
                &lt;strong&gt;httpContext.Response.Status = &lt;span class="str"&gt;&amp;quot;301 Moved Permanently&amp;quot;&lt;/span&gt;;
                httpContext.Response.StatusCode = 301;
                httpContext.Response.AppendHeader(&lt;span class="str"&gt;&amp;quot;Location&amp;quot;&lt;/span&gt;, url);
&lt;/strong&gt;            }
            &lt;span class="kwrd"&gt;else&lt;/span&gt;
                &lt;span class="kwrd"&gt;base&lt;/span&gt;.ProcessRequest(httpContext);
        }
    }&lt;/pre&gt;

&lt;p&gt;The above code is self explanatory, we are checking if the Request is local or external, we are only interested on external URLs. Next we check, whether the RequestContext.HttpCOntext.Request.Url.AbsoluteUri contains a &amp;quot;www&amp;quot; or not. If it do not contain a &amp;quot;www&amp;quot; we go and inject a &amp;quot;www&amp;quot; to the URL to convert the non-www version of URL to a www. version URL. Then we mark the previous response to a 301, which indicates that the previous URL has been permanently removed and all future requests should be directed to the given new URL.&amp;#160; &lt;br /&gt;

  &lt;br /&gt;We have developed our core handler above, however we need a wrapper IRouteHandler class to get the above The301GlobalHandler to work within the MVC Framework. This wrapper class is responsible to return an instance of the The301GlobalHandler.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;    public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; Route301GlobalHandler : IRouteHandler
    {
        &lt;span class="kwrd"&gt;public&lt;/span&gt; IHttpHandler GetHttpHandler(RequestContext requestContext)
        {
            &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; The301GlobalHandler(requestContext);
        }
    }&lt;/pre&gt;

&lt;p&gt;
  &lt;br /&gt;We have got our Route301GlobalHandler ready, now we need all of our requests to go via this handler instead of the default. One easy way to do this, is to iterate through the route collection and&amp;#160; assign them to this Route301GlobalHandler during the Application_Start().&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;    protected&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Application_Start()
    {
        RegisterRoutes(RouteTable.Routes);
&lt;strong&gt;        Route301Global.ReAssignHandler(RouteTable.Routes);&lt;/strong&gt;
    }&lt;/pre&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;    public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; Route301Global
    {
        &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; ReAssignHandler(RouteCollection routes)
        {
            &lt;span class="kwrd"&gt;using&lt;/span&gt; (routes.GetReadLock())
            {
                AssignRoute301GlobalHandler(routes);
            }
        }

        &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; AssignRoute301GlobalHandler(IEnumerable&amp;lt;RouteBase&amp;gt; routes)
        {
            &lt;strong&gt;&lt;span class="kwrd"&gt;foreach&lt;/span&gt; (var routeBase &lt;span class="kwrd"&gt;in&lt;/span&gt; routes)&lt;/strong&gt;
            {
                &lt;strong&gt;AssignRoute301GlobalHandler(routeBase);&lt;/strong&gt;
            }
        }

        &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; AssignRoute301GlobalHandler(RouteBase routeBase)
        {
            var route = routeBase &lt;span class="kwrd"&gt;as&lt;/span&gt; Route;
            &lt;span class="kwrd"&gt;if&lt;/span&gt; (route == &lt;span class="kwrd"&gt;null&lt;/span&gt;) &lt;span class="kwrd"&gt;return&lt;/span&gt;;
            &lt;strong&gt;&lt;span class="kwrd"&gt;if&lt;/span&gt; (route.RouteHandler.GetType() != &lt;span class="kwrd"&gt;typeof&lt;/span&gt;(Route301Handler))
                route.RouteHandler = &lt;span class="kwrd"&gt;new&lt;/span&gt; Route301GlobalHandler();&lt;/strong&gt;
        }
    }&lt;/pre&gt;

&lt;p&gt;Note, if you have other custom RouteHandler in your application, you will need to tweak this code, I am assuming all routes that will be mapped in the RegisterRoutes(RouteCollection routes) method uses the MvcHandler. 
  &lt;br /&gt;

  &lt;br /&gt;&lt;strong&gt;Conclusion&lt;/strong&gt; 

  &lt;br /&gt;

  &lt;br /&gt;We have identified keeping one set of URL is important for SEO. Then we have looked at how we can 301 redirect non-www version of URL to www. version URL in ASP.NET MVC. Hope this saves you some time and thank you for being with me so far.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msdnbangladesh.net/aggbug.aspx?PostID=1019" width="1" height="1"&gt;</description></item><item><title>ASP.NET MVC Tips: Form POST, TryUpdateModel, unit test, Moq</title><link>http://msdnbangladesh.net/blogs/shahed/archive/2009/05/15/asp-net-mvc-tips-form-post-tryupdatemodel-unit-test-moq.aspx</link><pubDate>Fri, 15 May 2009 12:52:51 GMT</pubDate><guid isPermaLink="false">019a604b-fb74-42d5-8a6d-7cedfb08f61c:1004</guid><dc:creator>shahed</dc:creator><slash:comments>0</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msdnbangladesh.net/blogs/shahed/rsscomments.aspx?PostID=1004</wfw:commentRss><comments>http://msdnbangladesh.net/blogs/shahed/archive/2009/05/15/asp-net-mvc-tips-form-post-tryupdatemodel-unit-test-moq.aspx#comments</comments><description>&lt;p&gt;Recently I have started playing with the &lt;a href="http://code.google.com/p/moq/"&gt;Moq&lt;/a&gt; (pronounced &amp;quot;Mock-you&amp;quot; or just &amp;quot;Mock&amp;quot;) a Mocking Library for .NET Developers, that takes full advantage of .NET 3.5 (i.e. Linq expression trees) and C# 3.0 features. Here in this post I will discuss how I have used the TryUpdateModel method in the Form POST scenario and also share how I have written a test case using Moq mocking library to deal with the TryUpdateModel&amp;lt;TModel&amp;gt;(TModel model) method of the ASP.NET MVC controller.     &lt;br /&gt;&lt;/p&gt;  &lt;p&gt;I have a very simple user interface, that allows user to&amp;#160; enter data and submit, to add a new &amp;quot;User&amp;quot;.    &lt;br /&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/CreateUser_5F00_WebForm_5F00_2.png"&gt;&lt;img style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="296" alt="CreateUser_WebForm" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/CreateUser_5F00_WebForm_5F00_thumb.png" width="308" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;My View Page is:    &lt;br /&gt;    &lt;br /&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/CreateUser_5F00_View_5F00_2.png"&gt;&lt;img style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="597" alt="CreateUser_View" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/CreateUser_5F00_View_5F00_thumb.png" width="541" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;   &lt;br /&gt;and my &amp;quot;Action&amp;quot; is     &lt;br /&gt;    &lt;br /&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/CreateUser_5F00_Action_5F00_6.png"&gt;&lt;img style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="340" alt="CreateUser_Action" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/CreateUser_5F00_Action_5F00_thumb_5F00_2.png" width="634" border="0" /&gt;&lt;/a&gt;&amp;#160;&amp;#160; &lt;br /&gt;You may have already noticed that I have decorated my action without any parameters, and my POST related codes are executed by checking the request type.     &lt;br /&gt;    &lt;br /&gt;if (Request.RequestType == POST)     &lt;br /&gt;{     &lt;br /&gt;&amp;#160; //code     &lt;br /&gt;}     &lt;br /&gt;    &lt;br /&gt;As I have no parameters in my CreateUser(), I did not need to create separate action&amp;#160; with AcceptVerbs(&amp;quot;GET&amp;quot;) and AcceptVert(&amp;quot;POST&amp;quot;) attribute. I have created an empty instance of MembershipCreateViewModel object and passed it to the TryUpdateModel() method to get the values of the posted form into my viewmodel object. MVC framework takes care of the rest and populates the viewModel with the desired values. Also note the RedirectToAction() method has been on success, it is&amp;#160; very important to perform this client - redirect. It will ensure that&amp;#160; the form does not resubmit, and the user will never see a prompt like this, if he hits the browser refresh button.     &lt;br /&gt;    &lt;br /&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/IE_5F00_resubmit_5F00_2.png"&gt;&lt;img style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="223" alt="IE_resubmit" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/IE_5F00_resubmit_5F00_thumb.png" width="442" border="0" /&gt;&lt;/a&gt;&amp;#160; &lt;br /&gt;    &lt;br /&gt;My MembershipCreateViewModel class is as follows,     &lt;br /&gt;    &lt;br /&gt;    &lt;br /&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/CreateUser_5F00_ViewModel_5F00_2.png"&gt;&lt;img style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="181" alt="CreateUser_ViewModel" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/CreateUser_5F00_ViewModel_5F00_thumb.png" width="503" border="0" /&gt;&lt;/a&gt;&amp;#160; &lt;br /&gt;    &lt;br /&gt;I did not prefer passing four parameters to my CreateUser() Action such as,     &lt;br /&gt;    &lt;br /&gt;[AcceptVerbs[&amp;quot;POST&amp;quot;])     &lt;br /&gt;CreateUser(string username, string email, string password, string confirmPassword)     &lt;br /&gt;{     &lt;br /&gt;//code     &lt;br /&gt;}     &lt;br /&gt;    &lt;br /&gt;instead I kept the method simple by using the MembershipCreateUserViewModel to communicated between the Controller and the View.     &lt;br /&gt;    &lt;br /&gt;This is all good, but by now you may be wondering how would I test this Controller&amp;gt;Action. Lets explore that part. Here I will demonstrate my TestCase using the Moq framework, but you can do the same using other popular mocking frameworks like Rhino Mock, NMock, NMock2, NUnit.Mocks, EasyMock, TypeMock etc, or even with plain vanilla C# code. First of all I will need a FakeHttpContext to interact with my Controller from the test environment.     &lt;br /&gt;    &lt;br /&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/fakeContext_5F00_2.png"&gt;&lt;img style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="307" alt="fakeContext" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/fakeContext_5F00_thumb.png" width="676" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;It is very straight forward to create a mock of a class or interface in Moq, I have created mocks of HttpContextBase, HttpRequestBase, HttpResponseBase, HttpSessionStateBase, HttpServerUtility above and decorated methods and properties that I use in my test cases using the Setup and SetupGet method that is available in the Moq library.&amp;#160; &lt;br /&gt;    &lt;br /&gt;Note how easily with couple of lines of code I have a mockup of the HttpContextBase. The Mock&amp;lt;T&amp;gt; allows creation of custom value matchers that can be used on setups and verification, completely replacing the built-in It class with our own argument matching rules.&amp;#160; &lt;/p&gt;  &lt;p&gt;var httpContext = new Mock&amp;lt;HttpContextBase&amp;gt;();    &lt;br /&gt;var request = new Mock&amp;lt;HttpRequestBase&amp;gt;     &lt;br /&gt;httpContext.Setup(ctx =&amp;gt; ctx.Request(request.Object);     &lt;br /&gt;    &lt;br /&gt;This above code snippet is creating mock instances of HttpContexBase and HttpRequestBase classes, and then also setting up that httpContext.Request will return the mock instance &amp;quot;request&amp;quot;.     &lt;br /&gt;    &lt;br /&gt;Now lets look at how I have used this mock httpContext in a test case.     &lt;br /&gt;    &lt;br /&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/EhrAdmin.MvcApplication-_2D00_-Microsoft-Visual-Studio-_2800_10_29005F00_2.png"&gt;&lt;img style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="541" alt="EhrAdmin.MvcApplication - Microsoft Visual Studio (10)" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/EhrAdmin.MvcApplication-_2D00_-Microsoft-Visual-Studio-_2800_10_29005F00_thumb.png" width="600" border="0" /&gt;&lt;/a&gt;&amp;#160; &lt;br /&gt;I have created a test case here that tests our CreateUser() action. Note I have created an instance of the ControllerContext and passed the httpContext mock object as a parameter of its constructor. After that I have assigned this instance ( context ) to the controller.ControllerContext property.     &lt;br /&gt;    &lt;br /&gt;The Mock.Get() method is interesting it can retrieve a mock object for the given object instance. Here I have retrieved the request object and have modified it further. I have setup so that the request.Form returns NameValueCollection. You may be wondering why did I pass NamValueCollection. You may recall that I have used the TryUpdateModel() method in my action to get the form values into our viewmodel, and if you look what is happening under the hood of TryUpdateModel() method you will find that, &amp;quot;Form&amp;quot; is of type System.Collections.Specialized.NameValueCollection and a member of System.Web.HttpRequestBase, and     &lt;br /&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/valuedictionary_5F00_2.png"&gt;&lt;img style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="187" alt="valuedictionary" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/valuedictionary_5F00_thumb.png" width="608" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;the internals of TryUpdateModel() iterates through each item of the ContollerContext.HttpContext.Request.Form object and populates the matching properties of the viewmodel using reflection. The above code snippet from the ValueProviderDictionary class where we see that the keys are being read from the Form object to populate a dictionary.    &lt;br /&gt;    &lt;br /&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;     &lt;br /&gt;    &lt;br /&gt;Here in this post I have discussed a Form POST scenario and I have decorated my action method without any parameters as by default TryUpdateModel method looks at the submitted Form object and attempt to assign it to the viewmodel object that we pass. I have also demonstrated how I have used the Moq library to create fake/mock objects for my testcases, how I have setup some fake methods and properties. I have also demonstrated the handy Mock.Get method that can retrieve a mock object from a given object instance and allows us to modify the mock object further. Thank you for being with me so far and I hope this helps.     &lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msdnbangladesh.net/aggbug.aspx?PostID=1004" width="1" height="1"&gt;</description></item><item><title>ASP.NET MVC tips: Routing Engine to aid SEO / 301 Redirect / Tracking</title><link>http://msdnbangladesh.net/blogs/shahed/archive/2009/02/14/asp-net-mvc-tips-routing-engine-to-aid-seo-301-redirect-tracking.aspx</link><pubDate>Fri, 13 Feb 2009 18:03:14 GMT</pubDate><guid isPermaLink="false">019a604b-fb74-42d5-8a6d-7cedfb08f61c:115</guid><dc:creator>shahed</dc:creator><slash:comments>0</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msdnbangladesh.net/blogs/shahed/rsscomments.aspx?PostID=115</wfw:commentRss><comments>http://msdnbangladesh.net/blogs/shahed/archive/2009/02/14/asp-net-mvc-tips-routing-engine-to-aid-seo-301-redirect-tracking.aspx#comments</comments><description>&lt;p&gt;Routing Library resides in the System.Web.Routing Namespace of the .NET Framework 3.5, which provides us the flexibility to use URLs that has no mapping to a physical file. This means ASP.NET MVC framework provides flexible URL mapping engine and enables us to write SEO (&lt;a href="http://en.wikipedia.org/wiki/Search_engine_optimization"&gt;Search Engine Optimization&lt;/a&gt;) friendly URLs with very little effort. No one can deny the importance of SEO, to be successful in search based marketing. What better way to analyze a business than from what customers are looking for on the Internet through keyword research. SEO is the way to go. &lt;br /&gt;&lt;br /&gt;SEO friendly URL Format for an e-commerce application may be&lt;br /&gt;/Products/List/ProductCategory&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;br /&gt;/Products/Detail/ProductName&lt;/p&gt; &lt;p&gt;URL Example&lt;br /&gt;/Products/List/CareCare&lt;br /&gt;/Products/Detail/MiracleCarDuster&lt;br /&gt;&lt;br /&gt;In ASP.NET MVC world the URL Routing System maps the incoming URLs to the relevant Controller and Action, in the above example our Contoller is Products and Action is List or Detail. We normally go and define a Route object and add it to the RouteCollection and register the RouteCollection during Application_Start(). Out of the box System.Web.Mvc library ships with the RouteCollectionExtensions which allows us to define routes easily using the the different overloads of MapRoute method.&lt;br /&gt;&lt;br /&gt;Example:&lt;/p&gt; &lt;p&gt;public static void RegisterRoutes(RouteCollection routes)&lt;br /&gt;{&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; routes.IgnoreRoute(&amp;quot;{resource}.axd/{*pathInfo}&amp;quot;);&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;p&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;strong&gt; routes.MapRoute&lt;/strong&gt;(&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;quot;Default&amp;quot;,&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; // Route name&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;quot;{controller}/{action}/{id}&amp;quot;,&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; // URL with parameters&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; new { controller = &amp;quot;Home&amp;quot;, action = &amp;quot;Index&amp;quot;, id = &amp;quot;&amp;quot; }&amp;nbsp; // Parameter defaults&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; ); &lt;p&gt;}&lt;br /&gt;&lt;br /&gt;If you look under the hood you will find, a Route object is created and added to the RouteCollection.&lt;br /&gt;&lt;br /&gt;Route route = new Route(url, new MvcRouteHandler()){};&lt;br /&gt;.....&lt;br /&gt;.....&lt;br /&gt;routes.Add(name, route);&lt;br /&gt;&lt;br /&gt;note that &amp;quot;MvcRouteHandler&amp;quot; have been passed as a parameter by default, when we use the routes.MapRoute() method. The overloads of MapRoute() extension methods are just helper methods to make things easy for us, it is not mandatory that we will have to always use this. We can define a Route object in plain .NET code and assign necessary properties to it, we can also pass our preferred IRouteHandler. This gives superb flexibility with handling URLs. For instance In a practical world of web marketing / search marketing we always need to support Legacy URLs. In the web marketing world ad hoc campaigns are launched, and what may have worked last week may not work this week any more, as a result the URL structure changes frequently and we face the need to start redirecting to the new URLs. &lt;br /&gt;&lt;br /&gt;On Top of that during this transformation of URLs we need to implement &amp;quot;301 Moved Permanently&amp;quot; redirections, which means the previous URL has been permanently removed and all future requests should be directed to the given new URI. Handling this scenario has become very easy with the Routing Engine. All we need to do is add a new Route or modify the existing Route to fit our need. Matt Hawley has an excellent post on &lt;a href="http://blog.eworldui.net/post/2008/04/ASPNET-MVC---Legacy-Url-Routing.aspx"&gt;Legacy Url Routing&lt;/a&gt; which describes how to route existing aspx file based URLs to the appropriate MVC Controller and Action. This article also gives directions on how to implement custom Route and custom RouteHandler.&lt;br /&gt;&lt;/p&gt; &lt;p&gt;public static void RegisterRoutes(RouteCollection routes)&lt;br /&gt;{&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; routes.IgnoreRoute(&amp;quot;{resource}.axd/{*pathInfo}&amp;quot;);&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;p&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;strong&gt; &lt;/strong&gt;routes.MapRoute(&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;quot;Default&amp;quot;,&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; // Route name&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;quot;{controller}/{action}/{id}&amp;quot;,&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; // URL with parameters&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; new { controller = &amp;quot;Home&amp;quot;, action = &amp;quot;Index&amp;quot;, id = &amp;quot;&amp;quot; }&amp;nbsp; // Parameter defaults&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; );&lt;br /&gt; &lt;blockquote&gt; &lt;p&gt;&amp;nbsp; routes.Add(&amp;quot;&amp;quot;, new LegacyRoute(&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;quot;Users/Login.aspx&amp;quot;,&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;quot;Login&amp;quot;,&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; new &lt;strong&gt;LegacyRouteHandler&lt;/strong&gt;())); // Defined a Custom Route class and have passed a custom IRouteHandler. &lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;}&lt;br /&gt;&lt;/p&gt;&lt;pre&gt;&lt;/pre&gt;
&lt;p&gt;&lt;br /&gt;As you can see in the above code, how easily we can add a custom route and pass a custom IRouteHandler (in this case LegacyHandler). &lt;br /&gt;&lt;/p&gt;
&lt;p&gt;Tracking - is another common task performed, we want to track everything, every single clicks a consumer performs on the site. This has also becomes easy in the world of ASP.NET MVC. By design we define separate actions for each functionality and we Route to the Controller - Action to get anything done. So tracking would be a viable option to do centrally just before creating the Controller object or just before delegating to the Action. &lt;br /&gt;&lt;br /&gt;You will notice the implementation of IRouteHandler requires to implement only one method &amp;quot;GetHttpHandler&amp;quot; which returns a IHttpHandler&lt;br /&gt;&lt;/p&gt;
&lt;p&gt;public interface IRouteHandler&lt;br /&gt;{&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; IHttpHandler GetHttpHandler(RequestContext requestContext);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;You will find the MvcRouteHandler implements IRouteHandler like this&lt;br /&gt;&lt;br /&gt;
&lt;p&gt;public class MvcRouteHandler : IRouteHandler {&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; protected virtual IHttpHandler GetHttpHandler(RequestContext requestContext) {&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; return new MvcHandler(requestContext);&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }
&lt;p&gt;}&lt;br /&gt;&lt;br /&gt;The real delegation of a Route to a Controller and Action happens in the ProcessRequest(HttpContext context); method of the MVCHandler class which is the implementation of IHttpHandler. The ProcessRequest(HttpContext contxt) method may be a be a good place to centrally control tracking in one of our custom Handlers. The implementaiton of MVCHandler is as follows, where you can see how a controller is created by the IControllerFactory factory, and then Execute() method is called. We can do our tracking somewhere before calling the Execute() method.&lt;br /&gt;
&lt;p&gt;protected internal virtual void ProcessRequest(HttpContextBase httpContext) {&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; AddVersionHeader(httpContext); 
&lt;p&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; // Get the controller type&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; string controllerName = RequestContext.RouteData.GetRequiredString(&amp;quot;controller&amp;quot;); 
&lt;p&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; // Instantiate the controller and call Execute&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; IControllerFactory factory = ControllerBuilder.GetControllerFactory();&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; IController controller = factory.CreateController(RequestContext, controllerName);&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; if (controller == null) {&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; throw new InvalidOperationException(&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; String.Format(&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; CultureInfo.CurrentUICulture,&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; MvcResources.ControllerBuilder_FactoryReturnedNull,&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; factory.GetType(),&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; controllerName));&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; try {&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; controller.Execute(RequestContext);&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; finally {&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; factory.ReleaseController(controller);&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }
&lt;p&gt;&lt;br /&gt;Did you know, Routes in the ASP.NET Mvc are matched and executed on a first match bases! It may be important to order the routes so that the correct pattern is matched first before a more general pattern matches and executes it. It is sometimes hard to figure out which particular pattern will be caught first when we have a lot of routes, ASP.NET Routing Debugger comes in to rescue, Phil Hack has put together this nice little &lt;a href="http://haacked.com/archive/2008/03/13/url-routing-debugger.aspx"&gt;route tester utility&lt;/a&gt; which can save a lot of time. This utility quickly displays in Red and Green color what Route patterns have matched for a particular URL. So we can type in various URLs in the addressbar to see which routes matches.&lt;br /&gt;&lt;br /&gt;Lets now looks at a different problem, we normally define all the routes in the global.aspx.cs file, this causes a problem when Routes changes frequently, every single time a new route is added or an existing one is modified we need to recompile web application and upload the new dll to the server, again it is not mandatory to write Routing rules in the global.aspx.cs file, we can easily store the routing rules to a Xml file and use a combination XML related .NET libraries and .NET Reflection APIs to read from the Xml file and create/deserialize Route Objects to add them to the RouteCollection during the Application_Start(). But still we haven&amp;#39;t overcome the limitations of restarting the application as the RouteCollection gettting registered during Application_Start. I think we have to live with that, unless we go and implement some kind of&amp;nbsp; FileSystemWatcher to monitor the Xml file and force to refresh the RouteTable.Routes object when the xml file changes. I haven&amp;#39;t tried implementing this yet but this would work I think.&lt;br /&gt;&lt;br /&gt;We have discussed here, how ASP.NET Routing engine eases writing SEO friendly Url, maitaining Url redirections and tracking centrally. Hope this helps.&lt;br /&gt;&lt;br /&gt;Thank you for being with me so far. &lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msdnbangladesh.net/aggbug.aspx?PostID=115" width="1" height="1"&gt;</description></item><item><title>ASP.NET tips: Display resultset from Multiple DataTable</title><link>http://msdnbangladesh.net/blogs/shahed/archive/2009/02/11/asp-net-tips-display-resultset-from-multiple-datatable.aspx</link><pubDate>Tue, 10 Feb 2009 17:06:52 GMT</pubDate><guid isPermaLink="false">019a604b-fb74-42d5-8a6d-7cedfb08f61c:85</guid><dc:creator>shahed</dc:creator><slash:comments>0</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msdnbangladesh.net/blogs/shahed/rsscomments.aspx?PostID=85</wfw:commentRss><comments>http://msdnbangladesh.net/blogs/shahed/archive/2009/02/11/asp-net-tips-display-resultset-from-multiple-datatable.aspx#comments</comments><description>&lt;p&gt;I normally do not use DataSet and prefer Objects instead generated by the ORM frameworks, but recently I had to produce a ASP.NET page that displayed a list of records from multiple DataTables. Lets look at a similar example.    &lt;br /&gt;    &lt;br /&gt;Lets assume we consume this DataSet which has two DataTables &amp;quot;Agent&amp;quot; and &amp;quot;RealEstateProperty&amp;quot;. The task is to display, what properties belongs to which agent, in a GridView.     &lt;br /&gt;    &lt;br /&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/RealEstateDataset_5F00_2.png"&gt;&lt;img style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="291" alt="RealEstateDataset" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/RealEstateDataset_5F00_thumb.png" width="307" border="0" /&gt;&lt;/a&gt;&amp;#160; &lt;br /&gt;    &lt;br /&gt;There are different ways to accomplish this task, lets look at them one by one.     &lt;br /&gt;    &lt;br /&gt;&lt;strong&gt;Method 1: Bind DataTables to&amp;#160; a single GridView      &lt;br /&gt;&lt;/strong&gt;    &lt;br /&gt;To bind these multiple DataTables to a single GridView control, we can quickly create a new temporary DataTable, with the required fields and populate the Rows and then bind the new DataTable Rows to the GridView.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/BindSingleGrid_5F00_2.png"&gt;&lt;img style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="524" alt="BindSingleGrid" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/BindSingleGrid_5F00_thumb.png" width="651" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;The above code is self explanatory, where I have created a temporary DataTable, populated its rows by iterating through the original DataTables and then binded the Grid to the new DataTable.Rows. The interesting piece of code to note here is the row.GetChildRows(), which respects the relationship and automatically returns the related child rows. The aspx part looks like the following, where we have a GridView with three columns.    &lt;br /&gt;    &lt;br /&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/SingleGridView_29005F00_2.png"&gt;&lt;img style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="144" alt="SingleGridView)" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/SingleGridView_29005F00_thumb.png" width="584" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;and the RowDataBound code is    &lt;br /&gt;    &lt;br /&gt;&amp;#160;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/SingleGridRowBound_5F00_4.png"&gt;&lt;img style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="242" alt="SingleGridRowBound" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/SingleGridRowBound_5F00_thumb_5F00_1.png" width="604" border="0" /&gt;&lt;/a&gt;     &lt;br /&gt;&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Method 2: Bind DataTables to a nested GridView&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;If we want to avoid creating temporary dummy DataTable as described in method 1, we can use the technique of nested list control. Now we can do this by using    &lt;br /&gt;    &lt;br /&gt;two GridView, or     &lt;br /&gt;two DataList, or     &lt;br /&gt;two Repeaters or     &lt;br /&gt;a combination of Repeater and GridView, or     &lt;br /&gt;a combination of Repeater and DataList, or     &lt;br /&gt;a combination of GridView and DataList.     &lt;br /&gt;    &lt;br /&gt;We are going to look at a combination of 2 GridViews here, where one GridView is nested inside another, you can do any of the above combinations. For this case the the aspx code is,&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/nestedgridview_5F00_2.png"&gt;&lt;img style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="299" alt="nestedgridview" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/nestedgridview_5F00_thumb.png" width="708" border="0" /&gt;&lt;/a&gt;     &lt;br /&gt;&lt;/p&gt;  &lt;p&gt;Notice the parent and nested GridViews has different onrowdatabound methods. In this technique the parent grid is binded to the the Agent DataTable Rows and the nested GridView is binded to the child RealEstateProperty DataTable Rows. Here is the code.    &lt;br /&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/nesteddatagridbind_5F00_2.png"&gt;&lt;img style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="580" alt="nesteddatagridbind" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/nesteddatagridbind_5F00_thumb.png" width="707" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Method 3: Convert the DataSet to Objects and then bind to GridView      &lt;br /&gt;&lt;/strong&gt;    &lt;br /&gt;We can generate csharp class from the dataset schema using Xsd.exe and then bind the GridViews to the objects. I have discussed similar technique in one of my previous &lt;a href="http://msmvps.com/blogs/shahed/archive/2008/03/23/datatable-to-json-and-tojson-extension.aspx"&gt;blog post&lt;/a&gt;, where you will find how we can use the Xsd.exe that ships with the .NET Framework.     &lt;br /&gt;    &lt;br /&gt;Example     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; C:\temp&amp;gt;xsd propertyDataSet.xsd /l:cs /c     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Microsoft (R) Xml Schemas/DataTypes support utility     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; [Microsoft (R) .NET Framework, Version 2.0.50727.42]     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Copyright (C) Microsoft Corporation. All rights reserved.     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Writing file &amp;#39;C:\temp\propertydatasetclass.cs&amp;#39;.&lt;/p&gt;  &lt;p&gt;I also demonstrated a handy DataTableToT() method to assist in converting DataTable to strongly typed object. And when we have the DataTable converted to a stronglytyped object/list/collection it is very easy to bind to the bind to the GridView.&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Other Tips&lt;/strong&gt;     &lt;br /&gt;1. DataSet also comes with handy Merge Method, &lt;a href="http://msdn.microsoft.com/en-us/library/system.data.dataset.merge.aspx"&gt;check here&lt;/a&gt;, we could have also used this method.     &lt;br /&gt;2. When we load a DataSet from xml schema if we do not provide the strongly typed DataSet it will not preserve the Relationship automatically.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/QuickWatch_5F00_2.png"&gt;&amp;#160;&lt;/a&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/QuickWatch_5F00_2.png"&gt;&lt;img style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="97" alt="onlydataset" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/onlydataset_5F00_thumb.png" width="435" border="0" /&gt;&lt;img style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="394" alt="QuickWatch" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/QuickWatch_5F00_thumb.png" width="640" border="0" /&gt;&lt;/a&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;Note: The Relations Count = 0;    &lt;br /&gt;    &lt;br /&gt;3. To preserve Relations automatically during a DataSet load from xml, provide strongly typed DataSet. Both of the following methods will automatically preserve the parent child relationship. Also even if you consume them from a webservice client application they will preserve the Relations.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/stronglytypeddataset_5F00_2.png"&gt;&lt;img style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="249" alt="stronglytypeddataset" src="http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/shahed/stronglytypeddataset_5F00_thumb.png" width="439" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;4. DataSet.WriteXml() method serializes the DataSet content and writes XML data.    &lt;br /&gt;5. DataSet.WriteXmlSchema() method writes the DataSet structure as XML Schema (xsd file).&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;     &lt;br /&gt;We have discussed different techniques to bind multiple DataTables to GridView, we have also discussed some handy tips about the DataSet. Hope this helps.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msdnbangladesh.net/aggbug.aspx?PostID=85" width="1" height="1"&gt;</description></item></channel></rss>
