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 the callback in asp.net web form and try to use Ajax, Web API, SignalR, MVC actions instead.

Capability detection: Try to 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 are 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 provide the Cross Site 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 user-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 the 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 NuGet package 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 for the above quotes, you can see the presentation. 



Introducing book: Pro Asp.net 4.5 in C#

About two years ago, I read some chapters of Pro asp.net 3.5 (it was the second edition of the book). I remember that I didn't dig in some chapter like lifecycle and Context, Modules, Handlers, Caching, Managing paths, Configurations, …  but now as I really need to know what's exactly going on the behind of asp.net I've decided to read this book in detail. In my opinion it's necessary to every asp.net developer as it really convers more about asp.net and it's frameworks. 

This book is in my books queue and will start reading of this book soon. I think the most important part of the book is part2 as it discusses on basics of asp.net, core architecture of the framework. although readers could jump over this part as it's for guys who want to know the main scenario behind asp.net

 

Pro asp.net

 

This is the definition of Apress about the book:

Pro ASP.NET 4.5 in C# is the most complete reference to ASP.NET that you will find. This comprehensively revised fifth edition will teach you everything you need to know in order to create well-designed ASP.NET websites. Beginning with core concepts the book progresses steadily through key professional skills. You'll be shown how to query databases in detail, consider the myriad applications of XML, and step through all the considerations you need to be aware of when securing your site from intruders. Finally, you'll consider advanced topics such as using client-side validation, jQuery and Ajax.



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 a 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 fewer 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. 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 defines all of these objects (Request, Response, Server, Session, Application, User, cache, Trace) in System.Web namespace for you and  They are the core objects necessary 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 received 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 website 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 database 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.

 

        [OutputCache(Duration = 6000)]
        public ActionResult ActionResult()
        {
            return View();
        }

 

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

 

        [OutputCache(Duration = 6000, VaryByParam = "id")]
        public ActionResult Action2(int id)
        {
            return View();
        }

 

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

 

        [OutputCache(Duration = 6000, VaryByParam = "*")]
        public ActionResult action3(int Id)
        {
            return View();
        }

 

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

 

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

 

This means you are caching the action to the client.

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

 

<caching>
<outputCacheSettings>
    <outputCacheProfiles>
        <add name="TwoHours" duration="7200" varyByParam="none"/>
        <add name="OneDay" duration="86400" varyByParam="none"/>
        <add name="OneWeek" duration="604800" varyByParam="none"/>
    </outputCacheProfiles>
</outputCacheSettings>
</caching>

 

After that, you can use your plans, for example

 

        [OutputCache(CacheProfile = "OneDay")]
        public ActionResult action5()
        {
            return View();
        }
        [OutputCache(CacheProfile = "OneWeek")]
        public ActionResult action6()
        {
            return view();
        }
 

Donut caching: if you want to cache the entire of the page except for 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 to get the package by Nuget 

donut caching

And then call use the DonutOutputCache in an action like this

 

       [DonutOutputCache(Duration = 6000)]
        public ActionResult action8(int id)
        {
            return View();
        }

 

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 :

 

@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:

 

        [ChildActionOnly]
        [OutputCache(Duration = 600)]
        public PartialViewResult TagSidebar()
        {
            var tags = _tagRepository.GetAllTag();
            return PartialView("_TagsSidebar", tags);
        }

 

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!



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 and I'm spending a lot of my time on architecture subject. Since 2008, I've been as a developer for companies and organizations and I've been focusing on Microsoft ecosystem all the time. During the&nb Read More

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