Ehsan Ghanbari

Experience, DotNet, Solutions

Asp.net: Don't do that, do this!

This blog post is about what I learned from the presentation by @DamianEdwards on here. As it was so interesting so I decided to write a blog post about that. It seems that Most of the points are about using Asp.net web form techniques.

 

Standard compliance

Control Adapters: Try to Avoid control adapters in asp.net web form as they are originally designed to support mobile devices. instead try to use standard html and CSS and mobile specific design if you want to make it responsive. And also Try to Avoid using style properties in asp.net web form in code behind, instead try to use CSS style sheets as they are maintainable in CSS classes.

Page and control callbacks: try to avoid using page callback or any control with callback in asp.net web form and try to use Ajax, Web Api, SignalR, MVC actions instead.

Capability detection: Try avoid BrowserCaps feature in asp.net and use client-side detection such as modernizer to determine the capability of the browser.

 

 

Security

Request validation: Try to use @foo (in MVC razor) and <%foo %>(in web form) and JavaScriptStringEncode and overall client checks to protect your site against XSS attacks.(although in my opinion It's better to have server side check for more security but client side checks is required to reduce the requests for server)

Cookies and Session authentication: Do not use cookies and session authentication because it's not safe for hijacking attacks. Instead use require cookies and SSL cookies.

EnableViewStateMac: Do not make EnableViewStateMac as false because it will provides the Cross Sire Scripting attack.

Medium trust: If you are running two application in a server, don’t use medium trust and place untrusted applications into their own application pools and run each application pool under its own unique identity.

<appSettings>: Do not make <appSettings> as disable

UrlPathEncode: Don't use it to encode arbitrary use-provided strings, Use UrlEncode to encode meant to appear as a query string parameter in a URL.

 

Reliability and performance

PreSendRequestHeaders and PreSendRequestContent: Don't use these methods within IHttpModule instances and use native IIS modules instead.

Asynchronous page events: Try to avoid async void methods for page lifecycle events. (for example Page_Load in web form) and try to use Page.RegisterAsyncTask() instead.

Fire-and-forget work: Don't use Timers and ThreadPool from asp.net and try to move them to a windows service(you can use WebBackgrounder to do that)

The request entity body: Try to not to use Request.Form and InputString before the HandlerExecute event. instead you Can use Request.GetBufferlessinputStream() and GetBufferedInputStream()

Response.Redirect & end: By default Response.Redirect(string) calls Response.End(), which abort the current thread in asynchronous request. but for asynchronous handlers, Response.End() does not abort the current thread. so try to avoid using Response.Redirect

EnableViewState & ViewStateMode: Try to avoid using EnableViewState, instead you can set ViewStateMode as "Disabled" and "Enabled" instead

SqlMembershipProvider: Use UniveralProviders instead of sqlMembershipProvider to work with all databases that entity framework supports. (it's available in NugetPackage manager)

Long-Running request: Try to avoid asp.net session as asp.net release the session object lock. Instead Try to use WebSocket or signalR for long-running requests if you can.

 

For more detail about the exact reason of above quotes you can see the presentation. 



In process session state mode in asp.net

You know a session is just a period of time for a specific user interaction in a web application. And the Session state is feature in Microsoft asp.net for maintaining the same time for the user stored locally the Web server. InProc is the default session state mode and specified In-process mode to values and variables in memory on the local Web server. In comparison to other modes (state server and SQL server), InProc is faster as they both spend some time to serializing and desterilizing while reading and writing the data.

 

Usages and Disadvantages:

If your application is running on a single server and you are not dealing with lot's or online users, the best choice is InProc. Notice that in InProc mode, more session data are stored in memory and that can affect performance so you can't store more data in InProc mode because it stores your data in the memory. InProc is much much faster, has less requirements (serialization), but it's not a good idea to use it when the application is running on several web servers. It's obvious that data in InProc model will be lost if domain restart. When using InProc session state, the session will be stored locally on the server which served the request and therefore using the same Machine Key on both servers won't serve the purpose, so using it multiple servers is not recommended.



ASP.NET Intrinsic Objects

When I heard about Intrinsic objects I thought that it’s a collection of objects and something newly added in .Net framework! And that's because I have no experience working with asp classic. in classic ASP, the framework would take care of instantiating a number of objects such as RequestResponseServer and Application. In asp.net, the framework creates all of these objects as well But they are not simply global variables named "Request" or "Response". Rather, they are properties exposed by classes. as All web forms in asp.net are basically instances of the ASP.Net Page class, it exposes all of this intrinsic objects for you. So naturally when you create a pure class in your asp.net application you don't have these intrinsic objects unless you go through HttpContext.Current. So the asp.net framework define all of these objects (Request, Response, Server, Session, Application , User, cache, Trace) in System.Web namespace for you and  They are the core objects neccesary for working in the asp.net.

 

 For more information take a look at these articles:

  1. http://www.pearsonitcertification.com/articles/article.aspx?p=31275&seqNum=3
  2. http://www.tutorialspoint.com/asp.net/asp.net_server_side.htm



Different Kinds of Caching in asp.net MVC4

When your web site has so many users it means your server has so many recieved requests, there is no need to query for every request Made by users because it will make some performance issues, for example there are some static content in your web site that you don’t update them for several months, in these cases you can cache those content and don't force your server to get them from data base in every request. there are different kinds of caching in asp.net 

 

OutPutChaching: ASP.net has a build-in caching mechanism called OutputCache, it's too easy to use.

  1.         [OutputCache(Duration = 6000)]
  2.         public ActionResult ActionResult()
  3.         {
  4.             return View();
  5.         }

This means you cache this action for 6000 seconds in your website's server. Also you can create different cache for different values passed to the action by using VaryByParam:

  1.         [OutputCache(Duration = 6000, VaryByParam = "id")]
  2.         public ActionResult Action2(int id)
  3.         {
  4.             return View();
  5.         }

In this case you cache Action2 for 6000 second for parameter named "id", and also it's possible to cache the action for every parameter

  1.         [OutputCache(Duration = 6000, VaryByParam = "*")]
  2.         public ActionResult action3(int Id)
  3.         {
  4.             return View();
  5.         }

You can also declare the location of the caching within this attribute, take a look

  1.         [OutputCache(Duration = 6000, VaryByParam = "*", Location = OutputCacheLocation.Client, NoStore = true)]
  2.         public ActionResult action4(string Name, int id)
  3.         {
  4.             return View();
  5.         }

This means you are caching the action to client.

OutputCacheProfiles Is an interesting  feature that you can define your caching plans in Web.Config and then use it in you controller or actions, like this

  1. <caching>
  2. <outputCacheSettings>
  3.     <outputCacheProfiles>
  4.         <add name="TwoHours" duration="7200" varyByParam="none"/>
  5.         <add name="OneDay" duration="86400" varyByParam="none"/>
  6.         <add name="OneWeek" duration="604800" varyByParam="none"/>
  7.     </outputCacheProfiles>
  8. </outputCacheSettings>
  9. </caching>

After that you can use your plans, for example

  1.         [OutputCache(CacheProfile = "OneDay")]
  2.         public ActionResult action5()
  3.         {
  4.             return View();
  5.         }
  1.         [OutputCache(CacheProfile = "OneWeek")]
  2.         public ActionResult action6()
  3.         {
  4.             return view();
  5.         }
 

Donut caching: if you want to cache the entire of page except one or a few parts, donut caching is the best choice. For example you have a static page which has a dynamic part (partial view) you can use donut caching in this case, unfortunately! There is no any built in mechanism for donut caching like outoutcaching,then you have get the package by Nuget 

donut caching

And then call use the DonutOutputCache in an action like this

  1.        [DonutOutputCache(Duration = 6000)]
  2.         public ActionResult action8(int id)
  3.         {
  4.             return View();
  5.         }

That's it, you have defined donut caching for this action, now when you call this action in your View you can make donut caching off or on , like this :

  1. @html.action("action8","SampleController",true)   

This means that action8 is not include the donut cash, if you change the true to false it will be cached! I'd prefer to use donut caching instead of caching multiple actions by outputcahing if I want to cache the whole page. BTW You can also use cache profile in Donut caching too.

Donut Hole caching: donut caching is about caching the entire page but a little part, now donut hole caching is about cashing a part of a dynamic page like tags of this blog that you can see in the right side(at the time of writing this post!) , fortunately! asp.net MVC4 has built in mechanism for donut hole caching and you don't need to use any external package. I've cached the tags of this blog like this:

  1.         [ChildActionOnly]
  2.         [OutputCache(Duration = 600)]
  3.         public PartialViewResult TagSidebar()
  4.         {
  5.             var tags = _tagRepository.GetAllTag();
  6.             return PartialView("_TagsSidebar", tags);
  7.         }

 

You can call PartialViewResult only inside a View and it's not accessible from URL, when you use ChildActionOnly attribute you implement the Donut Hole caching in the background too!

Caching webApi in MVC4 I searched about that and it seems there is no any way to cache WebAPI in MVC4 and you have to write your own custom caching, this article could be helpful!



How many types of cookies are there in Asp.net?

What is a Cookie?

A cookie is a small text file that can be remembered between pages or web server and browser. web application read that file information whenever the user refers to the web site. Cookie is one of the several ways to store data in the user's browser when the user is not connect to the web server which is sent by web server to the browser.

 

What are the usages?

Cookies could be used for authentication, identification, shopping cart information, or any text data. One of the most usage of Cookies is travelling of data from one page to another. when a user visits your site, you can use cookies to store his/her information. Your Web server can retrieve the stored information whenever the user visits the web site again If the cookie exists. Cookies are associated with a Web site, not with a specific page, so the browser and server will exchange cookie information. As a user when you visit different web sites, all of them could send cookie to your browser and store them separately. Cookies are also useful a web server which wants to know when the users visit the web page. Cookies also can be used in a poll system, For example you recognize that which user has voted something in your web site or not. Because of small limit of storage, it's better to store small amounts of data in cookies. Most browsers allow only 20 cookies per site; if you try to store more cookies in user's browser, the oldest cookies are discarded.

 

How cookie works?

When the server sends a page to a browser, it also sends the cookie to the browser via the HttpResponse object that exposes a collection. Cookies are saved in a folder in the hard drive of user's machine. The browser is responsible for managing cookies. You can access the HttpResponse object as the Response property of your Page class. Any cookies that you want to send to the browser must be added to this collection(as you will see in the implementation). When creating a cookie, you specify a Name and Value. Each cookie must have a unique name so that it can be identified later; Because cookies are stored by name. All cookies are sent to the server with any request to that site. In other words, every page in a site gets all of the cookies for that site. You cannot directly modify a cookie. but you can create a new one with the same value and send to the user's browser, it will be replaced with the existing cookie.

 

Security in cookie

Cookies are purely text Not a software program which can be included a virus or something like that. but a cookie could be stolen by hackers and get used. some information like account, credit card information or etc. in a cookie could be stolen.

 

Kinds of cookie

There are two main types of cookies: session cookies and persistent cookies. When a user closes the web browser, session cookie information is automatically removed from the computer. but Persistent cookie will be expired as soon as the application is closed or when the expire time will ended. Persistent cookies(aka permanent cookies)are stored by the user's browser even when the browser has been closed. Persistent cookies have an expiry date and can be anything from a few minutes to several years. session cookies(also called Non-persistent and temporary Cookies) have expiry date and stored in browser memory.

 

How to implement cookie? 

Take a look at these implementation, you can see the descriptions as comments

 

    1.            //How to create a cookie via HttpCookie Class, this is a persistent cookie because it has a expire date
    2.             var httpCookie = new HttpCookie("Form") {Expires = DateTime.Now.AddHours(3)};
    3.             Response.Cookies.Add(httpCookie);
    4.  
    5.             //how to read this Cookie
    6.             var cookie = Request.Cookies["Form"];
    7.             if (cookie != null)
    8.             {
    9.                 string form = cookie.Value;
    10.             }

 

    1.             //how to create cookie via Response , Non Persistent
    2.             var ResponseCookies = Response.Cookies["Form"];
    3.             if (ResponseCookies != null) ResponseCookies.Value = "A value";
    4.  
    5.             //Persistent
    6.             var httpCookie1 = Response.Cookies["Form"];
    7.             if (httpCookie1 != null) ResponseCookies.Expires = DateTime.Now.AddHours(4);
    8.         
    9.             //how to read 
    10.             string responseCookie = Request.Cookies["httpCookie1"].Value;
 
    1.             //How to Delete a cookie before it's expiration time
    2.             ResponseCookies.Expires = DateTime.Now.AddHours(-4);
 
    1.             //how to create Multiple Values in a cookie
    2.             Response.Cookies["MyCookie"]["CustomerName"] = "Ehsan";
    3.             Response.Cookies["MyCookie"]["CustomerFamily"] = "Ghanbari";
    4.             Response.Cookies["MyCookie"]["CustomerAge"] = "24";
    5.             Response.Cookies["MyCookie"].Expires = DateTime.Now.AddHours(20);

 

Also Take a look at these two nice articles for more information

  1. http://msdn.microsoft.com/en-us/library/ms178194(v=vs.100).aspx
  2. http://www.codeproject.com/Articles/31914/Beginner-s-Guide-To-ASP-NET-Cookies



About Me

Ehsan Ghanbari

Hi! my name is Ehsan. I'm a developer, passionate technologist, and fan of clean code. I'm interested in enterprise and large-scale applications architecture and design patterns. I spend a lot of time on software architecture. Since 2008, I've been as a developer for different companies and organizations and I've been focusing on Microsoft ecosystem all the time. During the past years, Read More

Post Tags
Pending Blog Posts
using Elmah in asp.net MVC4
Using FluentSecurity in MVC
Strategic design
Factory Pattern
time out pattern in ajax
Redis as a cache server
How to use PagedList In asp.net MVC
Multiple submit buttons in asp.net MVC
Domain driven design VS model driven architecture
What's the DDD-lite?