Asp.NET MVC Performance Tuning Guidelines

In today’s world, every application is expected to perform faster & smoother, its a part of overall user experience(UX). With the advancement of technology and the infrastructure it widely expected that application will not only do the job perfectly but also within a reasonable time. No one now wants to wait 5 mins to load a page, or complete a job while using a system. When we are in such phase of UX evolution performance tuning is common software development practice.

In a simple description performance tuning is to identify the issues that slow down the application and apply few tricks to improve performance.
In this particular post, I will only focus performance tuning at web application. To tune any web application there is 3 Steps.

  1. Insight
  2. Tune client end
  3. Tune server end

Insight

In order to make your move, you need to know first what is the problem with your application. Where you need to optimize, what are your priorities. To get these insights you need tools. Some tools will provide you the insights for client end, rest is for server end performance. Selecting right set of tool and using them is the first step of performance tuning.

Tune client end

Speed up the response time is crucial for UX and impacts the satisfaction of the user. Few tips/tricks can help you speed up your web application’s response time. Most of this time is tied up in downloading all the components in the page, minimize this time is the key to faster response.

Tune server end

Server side tuning mainly focus on low latency. How we can speedup the job that application is doing now at server end. This may involve database calls, file operations or make an external API call or may be few complex but poorly constructed business logic is the culprit. Newer Asp.Net framework s (4.5/5) is shipped (or to be shipped) with lots of performance improvement techniques or features, question is how efficiently we can utilize them.

Tools To Get Insight

Glimpse : For client end insight

Visual Studio Profiling : Visual Studio tool for performance diagnosis.

Client Side Tuning

  • Use cookies for frequently accessed non sensitive information
  • Use HTML5 async attribute for script files, to enable async loading

Scripts.RenderFormat(@"", "~/bundles/jquery")

  • Use a Content Delivery Network (CDN)
  • Minify JavaScript and CSS
  • Avoid CSS expressions
  • Remove duplicate scripts
  • Make Ajax calls cacheable
  • Choose <link> over @import
  • Optimize images
  • Don’t scale images in HTML
  • Don’t put empty image src
  • Make favicon.ico small and cache-able

Server Side Tuning

  • Run your site in Release mode, not Debug mode
  • Reducing the number of requests to the server by bundling
  • Use Base64 Data URIs
  • Avoid passing null models to views
  • Do not use Sessions or tempdata – which uses sessions
  • Add gzip (HTTP compression) and static cache (images, css, …) in your web.config

<system.webServer>

<urlCompression doDynamicCompression="true" doStaticCompression="true" dynamicCompressionBeforeCache="true"/>

</system.webServer>

  • Tells the webserver to set the “Expires” header to a far future date, effectively telling the browser to cache things forever.
<staticContent>
 <clientCache httpExpires="Sun, 29 Mar 2020 00:00:00 GMT" cacheControlMode="UseExpires" />
</staticContent>
  • If you use Razor, add the following code in your global.asax.cs, by default, Asp.Net MVC renders with an aspx engine and a razor engine. This only uses the RazorViewEngine.

ViewEngines.Engines.Clear();

ViewEngines.Engines.Add(new RazorViewEngine());

  • Replace foreach/for loop with linq wherever possible.
  • Avoid multiple database calls to load related data that serves one request. Say you are to make 2 separate db calls to get chunk of users and total number of users for a request that do paging, marge those two request as one.
  • Use in-memory cache for non cloud application and distributed cache for cloud one’s.

Optimizing or improving performance is a continuous effort. Monitor the application regularly, think about user behavior/interaction and the responses to gain max result. And as a note….load testing is excellent way to find out your application behavior before clients find those.

Good Read

Embrace reflection and export collection to csv

Introduction

Its became very common request in recent data driven apps to able to export some certain data as csv format. CSv format became widely used and acceptable. And its very common that a individual app contains several such export feature that take different object collection respect to different needs and export to csv, so here is the problem lies. Goal of this post is to provide a generic solution using .net Reflation and Generics so same export can be reusable though entire application disrespect to object type and save our (programmers: most hardworking creature in this planet after ant 😎 ) effort.

Problem Statement

I have seen programmers invest several hours to build such export features satisfy different needs. So what happens for different object collection programmers write different export method that address particular export feature. Why is that? answer is simple each object has different property so csv will contains different column name for each object. So programmers write different export functions that address a specific object type and arrange the csv column name statically.

How Reflection can Help

To address this issue we can use .net Generics and Reflection. I will not discuss about theses wonderful feature instead of that I will utilize those feature to find a solution. If you navigate to msdn to see what reflection can do, you will see PropertyInfo (Humm this is all we need) .

Use PropertyInfo to discover information such as the name, data type, declaring type, reflected type, and read-only or writable status of a property, and to get or set property values.

So idea is we will use a Generic collection to export and use Reflection to iterate all property via PropertyInfo, thus we can get all property name/type all that whatever the object collection is provided. Once we have property name/ type we can do whatever data formatting  or processing we need according to our needs. Say for a particular app specification is whatever date time is exports to csv it should be formatted like ddMMYYY. As we have property type now , its a piece of cake right? 🙂

Solution

Here is the method that take Generic List<t> as parameter and use reflection to iterate the type and export accordingly.

/// <summary>
 /// Take object List as input and export to csv 
///which will be prompt save as dialog
 /// </summary>
 /// <typeparam name="T">Type of object</typeparam>
 /// <param name="listToExport">Object list to export</param>
 /// <param name="seperateChar">character to use as scv separator</param>
 public static void ExportListToCSV<T>(List<T> listToExport, string seperateChar)
 {
 Int32 success = 0;
 StringBuilder export = new StringBuilder();
 try
 { 
 string seperator = "";
 StringBuilder builder = new StringBuilder();
 PropertyInfo[] fieldInfo = listToExport[0].GetType().GetProperties();
 foreach (PropertyInfo col in fieldInfo)
 {
  if (col.PropertyType != typeof(EntityKey) 
&& col.PropertyType != typeof(EntityState))
 {
 builder.Append(seperator).Append(col.Name);
 seperator = seperateChar;
 }
 }
 export.AppendLine(builder.ToString());
 foreach (T dataItem in listToExport)
 {
 PropertyInfo[] allProperties = dataItem.GetType().GetProperties();
 seperator = "";
 StringBuilder builderTmp = new StringBuilder();
 foreach (PropertyInfo thisProperty in allProperties)
 {
 if (thisProperty.PropertyType != typeof(EntityKey) 
&& thisProperty.PropertyType != typeof(EntityKey))
 {
 object value = thisProperty.GetValue(dataItem, null);
 String propetyValue = (value == null ? String.Empty : value.ToString());
 builderTmp.Append(seperator).Append(propetyValue);
 seperator = seperateChar;
 }
 }
 ++success;
 export.AppendLine(builderTmp.ToString()); 
 }
 }
 catch (Exception ex)
 {
 throw ex;
 }
// finally { if (sr != null) { sr.Close(); } }
HttpContext.Current.Response.Clear();
 HttpContext.Current.Response.Buffer = true;
 HttpContext.Current.Response.ContentType = "application/CSV";
 HttpContext.Current.Response.AppendHeader("content-disposition", 
                                "attachment;filename=FileName.csv");
 HttpContext.Current.Response.Charset = "";
 HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
 HttpContext.Current.Response.Write(export.ToString());
 HttpContext.Current.Response.End();
}

One thing might you notice above

if (thisProperty.PropertyType != typeof(EntityKey) 
&& thisProperty.PropertyType != typeof(EntityKey))

Why we need this checking? you see if you are using Entity Framework in your app, all entity has these two additional property type predefined and we don’t what them to be exported to csv and confuse end user, do we? So additional checking is required to remove them. If you do not use Entity Framework you don’t need to worry about this checking.

So you can see a simple trick can save lots of development effort, enjoy the free time 🙂

Software Architecture Cheat Blog 3: Open Closed Principle

Define Principle

Open Closed Principle (OCP) states that software entities (classes, modules, functions, etc.) should be open for extension but closed for modifications.

Violation Example

Lets consider a simple banking module that is responsible for calculating interest of accounts respect to account type. Say app owner bank offers to their client three types of accounts : savings accounts, basic checking accounts, money market deposit account. Each of the account type has different interest rate, and interest is calculated on different other factors such as amount deposited, average balance per month and so on. Thus based on this business rules we designed this class Accounts which calculates interest based on account types.

public enum AccountTYpe
    {
        Savings,
        Checking,
        MoneyMarket 
    }

    public class Accounts
    {
        private AccountTYpe accountType { get; set; }

        public Decimal CalculateInterest()
        {
            Decimal interest = 0;
            if (accountType == AccountTYpe.Savings)
            {
                //consider business rules and calculate interest of savings account
                interest = 2.50m;
            }
            else if (accountType == AccountTYpe.Checking)
            {
                //consider business rules and calculate interest of checking account
                interest = 3.50m;
            }
            else
            {
                //consider business rules and calculate interest of money market account
                interest = 5.00m;
            }

            return interest;
        }
    }

Above solution work perfectly for our client bank and app went to live and every one is happy. Few months later bank realize other banks are making money from certificates of deposit account , so we should do that, lets change our system to accommodate that. Now our revised system looks like this,

public enum AccountTYpe
    {
        Savings,
        Checking,
        MoneyMarket,
        CertificatesOfDeposit
    }

    public class Accounts
    {
        private AccountTYpe accountType { get; set; }

        public Decimal CalculateInterest()
        {
            Decimal interest = 0;
            if (accountType == AccountTYpe.Savings)
            {
                //consider business rules and calculate interest of savings account
                interest = 2.50m;
            }
            else if (accountType == AccountTYpe.Checking)
            {
                //consider business rules and calculate interest of checking account
                interest = 3.50m;
            }
            else if (accountType == AccountTYpe.CertificatesOfDeposit)
            {
                //consider business rules and calculate interest of certificates of deposit account
                interest = 6.35m;
            }
            else
            {
                //consider business rules and calculate interest of money market account
                interest = 5.00m;
            }

            return interest;
        }
    }

Considering the above scenario its not hard to guess, it will go through same process each time bank wants to launch another account type or made change on existing account types business rules. This is where open closed principle violates.

Resolution

To solve this We can create an common Interface which will be implemented by all classes represent account types. Benefit is later change can be accommodate better without modifying other corresponding class.

public interface IAccount
    {
        Decimal CalculateInterest();
    }

    public class SavingsAccounts:IAccount
    {
        public decimal CalculateInterest()
        {
            return 2.50m;
        }
    }

    public class CheckingAccounts : IAccount
    {
        public decimal CalculateInterest()
        {
            return 3.50m;
        }
    }

    public class MoneyMarketAccounts : IAccount
    {
        public decimal CalculateInterest()
        {
            return 5.00m;
        }
    }

Through approach we can add as many account type is needed, all we need is add another class for that account type. Also modification of business logic resides in respective account type class. Hence IAccount interface implement the idea of open for extension but closed for modifications.

Software Architecture Cheat Blog 2: Single Responsibility Principle

Define Principle

Single Responsibility Principle (SRP) states that there should never be more than one reason for class to change.

Violation Example

Lets consider this sample class Customer

public class Customer
    {
        public String Name { get; set; }
        public String Address1 { get; set; }
        public String City { get; set; }
        public String State { get; set; }
        public String Zip { get; set; }
        public String Email { get; set; }

        //Responsibility # 1 : save customer information
        public bool SaveCustomer()
        {
            if (ValidateCustomer())
            {
                //Save customer data
                SendWelcomeEmail();
            }

            return true;
        }

        //Responsibility # 2 : send email
        private void SendWelcomeEmail()
        {
            //send welcome email to customer
        }

        //Responsibility # 3 : validate customer data
        private bool ValidateCustomer()
        {
            //Check if the emaill is already registered

            return true;
        }
    }

While SRP principle states no class should contains more then one responsibility. Customer class itself  carries three responsibility, save data/validate data/email.  If further we want to add additional validation rule, or need to update email function to facilitate admin email we have to change the Customer class, thus violates SRP.

Resolution

To solve this We have to break down each class respect to responsibility.

    public interface ICustomerInfo
    {
        String Name { get; set; }
        String Email { get; set; }
    }

    public class Customer: ICustomerInfo
    {
        public String Address1 { get; set; }
        public String City { get; set; }
        public String State { get; set; }
        public String Zip { get; set; }
        public String Name { get; set; }
        public String Email { get; set; }        
    }

    public class Emailer
    {
        public void SendWelcomeEmail(ICustomerInfo customerInfo)
        {
            //send welcome email to customer
        }
    }

    public class CustomValidator
    {
        public bool ValidateCustomer(ICustomerInfo customerInfo)
        {
            //Check if the emaill is already registered
            return true;
        }
    }

    public class CustomerManager
    {
        ICustomerInfo _custInfo;
        public void SaveCustomer()
        {
            _custInfo = new Customer();
            if (new CustomValidator().ValidateCustomer(_custInfo))
            {
                new Emailer().SendWelcomeEmail(_custInfo);
            }
        }        
    }

This makes ICustomerInfo independent of the Customer class which makes it easier to maintain and extend. Emailer and Validation is now handle single responsibility and do not depend on entire customer object.Further we can modify validation rules, emailer logic’s as needed without effecting core Customer class.

Software Architecture Cheat Blog 1: Design Principles

This blog series will gather summary of all the software architecture design principles under one roof. Intention is to keep in touch with these principles.
First one is called “SOLID”, which is combination of five basic designing principles,

Single Responsibility Principle

Example: http://blog.sanaulla.info/2011/11/16/solid-single-responsibility-principle/
There should never be more than one reason for class to change.

Open – Closed Principle

Example: http://blog.sanaulla.info/2011/11/19/solid-open-closed-principle/

Software Entities (Classes, Modules, Functions, etc.) should be open for extension but closed for modifications.

Liscov Substitution Principle

Example: http://lassala.net/2010/11/04/a-good-example-of-liskov-substitution-principle/
Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it.

Interface Segregation Principle

Clients should not be forced to depend upon interfaces that they don’t use.

Dependency Inversion Principle

A. High level modules should not depend on low level module. Both should depend on abstraction. Both should depend on Abstraction.
B. Abstraction should not depend on details. Details should depend on Abstraction.
Other important principles are

DRY (Don’t Repeat Yourself)

Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.
Aimed at reducing repetition of information of all kinds, especially useful in multi-tier architectures.

YAGNI – You ain’t gonna need it

Always implement things when you actually need them, never when you just foresee that you need them.

KISS – Keep it simple, Stupid!

Most systems work best if they are kept simple rather than made complex, therefore simplicity should be a key goal in design and unnecessary complexity should be avoided.

Seven Principles Of Software Development

  1. The Reason It All Exists
  2. KISS (Keep It Simple, Stupid!)
  3. Maintain the Vision
  4. What You Produce, Others Will Consume
  5. Be Open to the Future
  6. Plan Ahead for Reuse
  7. Think

REF: http://csharpsimplified.wordpress.com/2010/10/01/design-principle/

Royce initial Waterfall model an investigation.

Preface:
The waterfall model is a sequential software development model in which development is seen as flowing steadily downwards (like a waterfall) through several phases.
History of the Waterfall Model:
In 1970 Royce proposed what is now popularly referred to as the waterfall model as an initial concept. The waterfall model maintains that one should move to a phase only when it’s proceeding phase is completed and perfected. Phases of development in the waterfall model are thus discrete, and there is no jumping back and forth or overlap between them. Figure-1 shows initial waterfall model.

Figure-1

The model maintains that one should move to a phase only when its preceding phase is completed and perfected. However, there are various modified waterfall models (including Royce’s final model) that may include slight or major variations upon this process.

Figure-2 shows the waterfall model as purely sequential process which is widely and highly regarded by many today.

Figure-2


Figure-2 states that the phases are organized in a linear order. A project begins with feasibility analysis. On the successful demonstration of the feasibility analysis, the requirements analysis and project planning begins and so on. Once a phase is completed there is no moving back because output of one phase works as an input of next phase, so modification in previous phase can make the process unstable and leads to failure.

Findings:
Royce’s paper explored how the initial model could be developed into an iterative model, with feedback from each phase influencing previous phases, similar to many agile methods used widely and highly regarded by many today.
Despite Royce’s intentions for the waterfall model to be modified into an iterative model, use of the “waterfall model” as a purely sequential process is still popular, and, for some, the phrase “waterfall model” has since come to refer to any approach to software creation which is seen as inflexible and non-iterative.