Custom container key for AWS beanstalk in Visual Studio

You can’t redeploy for just changing string SMTP credential or connection etc. In normal deployments we use appSetting in web.config, but when we use AWS beanstalk the we can’t change web.config, because these two reasons.

  1. Multiple Instances.
  2. Removed changes when machine upgrade.

For this problem AWS provide Container (environment configuration settings), In legacy hardware it provide only 5 predefined keys PARAM1 to PARAM5.

But in non-legacy hardware it support custom key, for creating deployment with non-legacy hardware you have to create deployment from AWS console. All keys can access through ConfigurationManager.AppSettings, so no need to any extra code to access AWS container keys.


string connstring = ConfigurationManager.AppSettings["ConnString"];

For adding these key in Visual studio project

  1. add a directory in root .ebextensions, and make sure it is part of project
  2. add a file with .config extension, eg. appSetting.config, and make sure it is content as build action (to set build action, right click on file and property)

this file can only contains YAML, so we have to write keys using YAML syntax,

option_settings:
  - option_name: ConnString
    value: Data Source = db.hostname ; Initial Catalog = MyDB ; User ID = myuser; Password = pass2123
  - option_name: IsLoggerOn
    value: 1

Note

option_settings: root (equivalent to >appSetting> in web.config)
option_name: Key (equivalent to key attribute of >add /> element)
value: Value of key (equivalent to value attribute of >add /> element)

Make sure you are writing valid YAML syntax, because Visual Studio auto format .config files. You can use YAMLLint to check valid YAML or not. You can add more keys in this.

Now when you will deploy your application these key will automatically added to Environment configuration settings. You can change these key any time from Visual Studio AWS plugin or AWS console.

for changing Container from Visual Studio : To access the Container/.NET Options panel for your AWS Elastic Beanstalk application

  1. In AWS Toolkit for Visual Studio, expand the AWS Elastic Beanstalk node and your application node.
  2. In AWS Explorer, double-click your AWS Elastic Beanstalk environment.
  3. Under ‘Advanced’ scroll to aws:elasticbeanstalkapplication:environment , you can configure container options.

Change value and click on ‘Apply changes’.

jQuery Ajax using Http Handler

Handlers makes life easier for using pure JavaScript or jQuery Ajax, I think it’s much cleaner way to use Handlers to call Ajax. jQuery is most popular JavaScript library in the world and it’s very easy to use.

We can create handlers in to ways one is Generic handler and second is custom handler. Generic handlers have pre mapping as *.ashx with custom handler we need to add handler mapping in web.config.

Handler are faster then ASP.NET WebPage, because of small life cycle (only one method for executing). Handlers never generate ViewState also.

Every handler must be implemented System.Web.IHttpHandler, and need to implement following method and property

    public class SampleHandler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            context.Response.Write(_jsserializer.Serialize(_productentity.GetProduct()));
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

I already mentioned that we can use handlers two types. let understand it.

Generic handler (.ashx) :

It is pre mapped handler and .ashx is a mark up file like .aspx. for adding Generic handler follow these steps.

Right click on Project > Add > New Item… > Web > Generic Handler (enter name of handler)

generic handler contains two file (one is mark and second is code behind), in markup file VS generate following directive

<%@ WebHandler Language="C#" CodeBehind="getproducts.ashx.cs" Class="IAnswerable.HttpHandlersTutorial.GenericHandler.getproducts" %>

we can remove code behind file and add code below directive (it is same as add runat server script on .aspx page)., but this will not be pre compiled, let understand with getproduct handler

<%@ WebHandler Language="C#" CodeBehind="getproducts.ashx.cs" Class="IAnswerable.HttpHandlersTutorial.GenericHandler.getproducts" %>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using IAnswerable.HttpHandlersTutorial.Entity;
using System.Web.Script.Serialization;

namespace IAnswerable.HttpHandlersTutorial.GenericHandler
{
    public class getproducts : IHttpHandler
    {
        ProductEntity _productentity = new ProductEntity();
        JavaScriptSerializer _jsserializer = new JavaScriptSerializer();

        public void ProcessRequest(HttpContext context)
        {
            context.Response.Write(_jsserializer.Serialize(_productentity.GetProduct()));
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

We can check result of this direct from browser just type url of this (on my end it is http://localhost:2312/GenericHandler/getproducts.ashx), we will use this handler in jQuery after Custom handler.

Custom handler :

for adding this kind of handler follow following steps

Right click on Project > Add > New Item… > Web > ASP.NET Handler

enter name according to your requirements, it will be looked like just simple class

My product handler is (I have coded same functionality as generic handler)

using System;
using System.Web;
using System.Web.Script.Serialization;
using IAnswerable.HttpHandlersTutorial.Entity;

namespace IAnswerable.HttpHandlersTutorial.CustomHandler
{
    public class Products : IHttpHandler
    {
        #region IHttpHandler Members
        ProductEntity _productentity = new ProductEntity();
        JavaScriptSerializer _jsserializer = new JavaScriptSerializer();

        public void ProcessRequest(HttpContext context)
        {
            context.Response.Write(_jsserializer.Serialize(_productentity.GetProduct()));
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
        #endregion
    }
}

We can’t access this handler without adding Handler mapping in web.config, open Web.config and add following mapping.

If you are using IIS6 then add following under system.web > httpHandlers

<add path="getproducts.pr" verb="*" type="IAnswerable.HttpHandlersTutorial.CustomHandler.Products"/>

and if using II7 or 7.5 then

<add name="getproducts" path="getproducts.pr" verb="*" type="IAnswerable.HttpHandlersTutorial.CustomHandler.Products"/>

in mapping

  • path : url of handler (don’t have added getproducts.pr)
  • verb : accepted http methods (GET, POST, HEAD etc.) * means all
  • type : Type of handler
  • name (in IIS 7 or above) : just unique name.

We can access this handler from browser directly (my end url is http://localhost:2312/getproducts.pr)

Handlers useful in REST api (not recommended) and in Ajax, Let we understand how to use Handlers through jQuery. jQuery is very easy to use and lightweight.

first add jQuery I recommend use google cdn for this

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

then use this jQuery ajax code, click event of a button

<script>
$(document).ready(function(){
     $("#loadpage").click(function(){
         $.getJSON("/getproducts.pr",function(products){
                $.each(products, function(key, val) {
                   items.push('<li id="' + key + '">' + val + '</li>');
                });
                // created list and append to products div.
                $('<ul/>', { 'class': 'my-new-list',html: items.join('')}).appendTo('#productsdiv');
         });
     });
});

</script>

You can use various ajax methods as your requirements.

Stackoverflow reference

Asp.net Web API and google chrome’s Postman plugin

MS introduced Asp.net web api with Visual studio 11 (Consumer preview, you can download from here), Its a good framework to create REST api, very clean and maintainable. I have created a sample project for learning purpose and I used Google chrome’s Postman plugin it is good plugin to consume REST services. You can add from here.

1. Open Visual Studio 11 create new project using “ASP.NET MVC 4 Web Application” and Click on OK button


MVC4 Project



2. Select “Web API” from Project template dialog box


ASP.NET Web Api



3. Solution will be ready in few seconds and its look like


Asp.net web api project



4. Open global.asax file and check “RegisterRoutes” method, in this by default “MapHttpRoute” (MapHttpRoute is responsible for routing of web api controller) map to “api/{controller}/{id}” means Web api controllers accessing through “api/{controller}/{id}” path you can change it according to your requirement.

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }




5. Now create a Employee class with following definition in Model

namespace SampleWebApi.Models
{
    public class Employee
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Department { get; set; }
    }
}




6. And Create following EmployeeModel. In this model I have created Add, UpdateEmploayee, DeleteEmployee, GetEmployees and and GetEmployee methods and for data storage I have used a static List, it store data unless App recycle. You can use database for storage. I have used static List for just showing example.

using System.Collections.Generic;
using System.Linq;

namespace SampleWebApi.Models
{
    public class EmployeeModel
    {

        public static List<Employee> _employees =new List<Employee>();

        public void Add(Employee employee)
        {
            //for getting next ID
            if (_employees.Count > 0)
            {
                employee.ID = _employees.Max(emp => emp.ID) + 1;
            }
            else
            {
                employee.ID = 1;
            }

            //add to _employee
            _employees.Add(employee);
        }

        public List<Employee> GetEmployees()
        {
            return _employees;
        }

        public Employee GetEmployee(int id)
        {
            return _employees.Where(employee => employee.ID == id).FirstOrDefault();
        }

        public int UpdateEmployee(int id, Employee employee)
        {
            var updatableemployee = _employees.Where(emp => emp.ID == id).FirstOrDefault();

            if (updatableemployee != null)
            {
                updatableemployee.Department = employee.Department;
                updatableemployee.Name = employee.Name;
                return updatableemployee.ID;
            }
            else
            {
                return 0;
            }
        }

        public bool DeleteEmployee(int id)
        {
            return _employees.Remove(_employees.Where(emp => emp.ID == id).FirstOrDefault());
        }
    }
}




7. And Following EmployeesController. In following code you are seeing that EmployeesController inherit ApiController and ApiController class is base class of web api controller. Mapping of HTTP methods and api controller’s methods is


GET ==> Get (used for getting resources)

POST ==> Post (used for Adding resource)

DELETE => Delete (used for deleting resource)

PUT ==> Put (used for Updating resource)

using System.Collections.Generic;
using System.Web.Http;
using SampleWebApi.Models;

namespace SampleWebApi.Controllers
{
    public class EmployeesController : ApiController
    {
        EmployeeModel employeemodel = new EmployeeModel();

        // GET /api/employees
        public IEnumerable<Employee> Get()
        {
            return employeemodel.GetEmployees();
        }

        // GET /api/employees/5
        public Employee Get(int id)
        {
            return employeemodel.GetEmployee(id);
        }

        // POST /api/employees
        public void Post(string name, string department)
        {
            Employee employee = new Employee();
            employee.Name = name;
            employee.Department = department;
            employeemodel.Add(employee);
        }

        // PUT /api/employees/5
        public void Put(int id, Employee employee)
        {
            employeemodel.UpdateEmployee(id, employee);
        }

        // DELETE /api/employees/5
        public void Delete(int id)
        {
            employeemodel.DeleteEmployee(id);
        }
    }
}




8. Run this project and open Google chrome’s postman plugin, in this we option to Enter Url, HTTP request type, Request Headers, Form collection, Url parameter etc, so it is very easy to test Web api with Postman plugin.


Google Chrome PostMman Plugin



9. Now I am consuming these requests through Google chrome’s postman plugin. It can used just for testing and debugging the web api’s before implementing.


1. HTTP POST : First I am adding some record to the data store, for I need to call HTTP POST request of web api endpoint.

for calling HTTP POST follow these steps

1. Input endpoint, my endpoint is http://localhost:2411/api/employees/.

2. Select ‘POST’ from drop down.

3. Select form type is “x-www-form-urlencoded”.

4. Add two key “name” and “department” and their values.

5. Click on “Send” button.

6. After few milliseconds api will respond, this request add a record.

I added two records for example following above steps again.


example http post request in postman plugin



2. HTTP GET : For getting Employees list I need to call HTTP post of web api endpoint

for calling HTTP GET follow these steps

1. Input endpoint, my endpoint is http://localhost:2411/api/employees/.

2. Select “GET” from drop down.

3. 5. Click on “Send” button.

6. After few milliseconds api will respond. It returns json array in response, you can see in following image.


example http get request in postman plugin

If you want to get specific Employee then use specific ID like

http://localhost:2411/api/employees/2

Response of this request is

{
     "Department" : "MBA",
     "ID" : 2,
     "Name" : "Ashok Bishnoi"
}



3. HTTP PUT : For updatting I need to call HTTP PUT request of web api endpoint.

for calling HTTP PUT follow these steps

1. Input endpoint, my endpoint is http://localhost:2411/api/employees/.

2. Add a employee at end of endpoint(http://localhost:2411/api/employees/) , I am updating employee of ID 2, so endpoint looks like http://localhost:2411/api/employees/2

3. Select ‘PUT’ from drop down.

4. Select form type is “x-www-form-urlencoded”.

5. Add two key “name” and “department” and their values.

6. Click on “Send” button.

7. After few milliseconds api will respond, this request update the record with ID 2. In my example just “1″ you can manipulate it.


http post using postman plugin

You can check updated records using HTTP GET request.



4. HTTP DELETE : For deleting record I need to call HTTP DELETE request of web api endpoint

for calling HTTP DELETE follow these steps

1. Input endpoint, my endpoint is http://localhost:2411/api/employees/.

2. Select ‘DELETE’ from drop down.

3. Select form type is “x-www-form-urlencoded”.

4. Add one key “id” and its value, I am deleting record with ID 2.

5. Click on “Send” button.

6. After few milliseconds api will respond, this request delete the record with ID 2.


http delete request using postman plugin

You can check deleted record using HTTP GET request.

Func, Action and Predicate

Func, Action and Predicate are predefined generic delegates which are included with .NET framework. Func refer method which always return a value, Action always refer a method which don’t return value and predicate which always take one argument and return always bool type value.

let understand their signature, I have decompiled the mscorlib and navigate to System namespace and found these signature for

1. Func : Func have nine kinds of signature in param are input type and out param is return type, maximum 8 input parameters

func

2. Action : Action have eight kind of signature, maximum 8 input parameters

action

3. Predicate : Predicate have only one input parameter and returns always boo type.

predicate

let understand with code example, I used Math delegate in my previous blob on delegate, Anonymous methods and Lambda notation that Math delegate is equivalent of

Func<int,int,int>
// delegate int Math(int value1, int value2);

now I can use this Func delegate to refer Add method , in this example I just refer Add method to math delegate. I am using Func with 2 int input param with int return type.

    class Program
    {
        static void Main(string[] args)
        {
            Func<int, int, int> math = Add;
            Console.Write(math(1, 1));
        }
        public static int Add(int a, int b)
        {
            return a + b;
        }
    }
    //output
    //2

we can also assign anonymous method, in this I have created a anonymous method through delegate

    class Program
    {
        static void Main(string[] args)
        {
            Func<int, int, int> math = delegate(int a, int b)
                                        {
                                            return a + b;
                                        };
            Console.Write(math(1, 1));
        }
    }
    //output
    //2

we can also assign anonymous method through lambda notation

    class Program
    {
        static void Main(string[] args)
        {
            Func<int, int, int> math = (a, b) => { return a + b; };
            Console.Write(math(1, 1));
        }
    }
    //output
    //2

or if anonymous method have single statement then

    class Program
    {
        static void Main(string[] args)
        {
            Func<int, int, int> math = (a, b) =>  a + b;
            Console.Write(math(1, 1));
        }
    }
    //output
    //2

Action never return value, following example I have created a delegate which takes one int input parameter and Print on console.

    class Program
    {
        static void Main(string[] args)
        {
            Action<int> Print = (a) => { Console.Write(a); };
            Print(10);
        }
    }
    //output
    //10

You can pass multiple input parameters up to 8 , in following example i am passing 3 input parameter 2 string type and 1 int type.

    class Program
    {
        static void Main(string[] args)
        {
            Action<string,string,int> PrintResult = (name,regNo,marks) => { Console.Write(string.Format("Name : {0} \nRegisteration No. : {1} \nMarks : {2} ",name,regNo,marks)); };
            PrintResult("Mark", "RJ24", 390);
        }
    }
    //output
    //Name : Mark
    //Registeration No. : RJ24
    //Marks : 390

And now finally predicate takes only one input parameter and return always bool type

    class Program
    {
        static void Main(string[] args)
        {
            Predicate<int> IsLessThenTen = (a) => { return a < 10; };
            Console.WriteLine(IsLessThenTen(10));
            Console.WriteLine(IsLessThenTen(2));
        }
    }
    //output
    //False
    //True

its equivalent to Func<int,bool> , check following example

    class Program
    {
        static void Main(string[] args)
        {
            Func<int,bool> IsLessThenTen = (a) => { return a < 10; };
            Console.WriteLine(IsLessThenTen(10));
            Console.WriteLine(IsLessThenTen(2));
        }
    }
    //output
    //False
    //True

You can pass Func, Action and Predicate as parameter also, check following example

class Program
    {
        static void Main(string[] args)
        {
            var namesstartwithm = GetNames(name => name.StartsWith("M"));
 
            Console.WriteLine("--- Name which are starts with M char ------");
            foreach (var name in namesstartwithm)
            {
                Console.WriteLine(name);
            }
 
            var names = GetNames(name => name.Count()<=3);
 
            Console.WriteLine("\n\n--- Name which are contains less then or equals to 3 chars ------");
            foreach (var name in names)
            {
                Console.WriteLine(name);
            }
 
            Console.ReadLine();
        }
 
        public static IEnumerable<string> GetNames(Func<String,bool> namecriteria)
        {
            List<string> names = new List<string>();
            names.Add("John");
            names.Add("Martin");
            names.Add("Tom");
            names.Add("Nick");
            names.Add("Geoge");
            names.Add("Matt");
 
            foreach (var name in names.AsEnumerable())
            {
                if (namecriteria(name))
                {
                    yield return name;
                }
            }
        }
    }
 
//output
//
//--- Name which are starts with M char ------
//Martin
//Matt
 
//--- Name which are contains less then or equals to 3 chars ------
//Tom

Linq to Asp.net controls

Some we use many controls on a page and we need to get their value we access them through ID and its very time consuming process, we can access through Linq , It is easy and much cleaner way. For querying on controls of page we need to create a function which can access all controls of page recursively. For this I am creating a extension method which get reference all controls recursively.


using System.Collections.Generic;
using System.Web.UI;

namespace IAnswearble.Utility
{
    public static class PageExtension
    {
        public static IEnumerable<Control> GetAllControls(this Control parent)
        {
            foreach (Control parentcontrol in parent.Controls)
            {
                yield return parentcontrol;
                foreach (Control childcontrol in parentcontrol.GetAllControls())
                {
                    yield return childcontrol;
                }
            }
        }
    }
}

Now I we can use it for any type query on controls of page, for querying we need use namespace IAnswearble.Utility

Example 1 : Get all check boxes which are selected

var selectedcheckboxes = this.GetAllControls().OfType<CheckBox>().Where(item => item.Checked);

Example 2 : Get value of all TextBoxes

using System;
using System.Linq;
using System.Web.UI.WebControls;
using IAnswearble.Utility;

namespace WebApplication1
{
    public partial class Default : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            var textoftextboxes = from textbox in this.GetAllControls().OfType<TextBox>()
                                     select new { ID = textbox.ID, Text = textbox.Text };

            foreach (var textoftextbox in textoftextboxes)
            {
                Response.Write(string.Format("Value of {0} is {1}", textoftextbox.ID , textoftextbox.Text));
            }
        }
    }
}

Example 3 : Get child controls of a specific control

 var textboxofdivform = this.GetAllControls().Where(item => item.Parent.ID == DivForm.ID).OfType<TextBox>();

Extension Methods

Extension methods enable you to “add” methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type. (Source MSDN)

For creating Extension method
1. Method should be in static class
2. Method should be static
3. Pass parameter (with this keyword) of type for which you are writing extension method.
4. Namespace (where extension method defined) should be added where you want to use it

let understand with example

public static class NumericExtension
{
    public static ToInt(this string value)
    {
        int number;
        if(int.TryParse(value,out number))
        {
            return number;
        }
        else
        {
          throw  new InvalidCastException();
        }
    }
}

We can use this on string object directly like

    class Program
    {
        static void Main(string[] args)
        {
            string strnumber ="1980";
            int number = strnumber.ToInt(); // call ToInt() directly like member methods
        }
    }

Extension method behave like public member so it is inherited to derived classes le understand one example.

public static class ObjectExtension
{
    public static bool IsNotNull(this object value)
    {
        return value!=null;
    }
}

In above example I attached a extension methods to Object and Object is parent class of all classes, so we can call IsNotNull method on any type.

    class Program
    {
        static void Main(string[] args)
        {
            string name = null;

            //on string type
            if (name.IsNotNull())
            {
                // do your stuff
            }

            //on string array type
            if (args.IsNotNull())
            {
                //do your stuff
            }

            List<int> series = new List<int>();

            //on generic list type
            if (series.IsNotNull())
            {
                //do your stuff
            }
        }
    }

Delegate, Anonymous method and Lambda notation

Definition : A delegate is a type that references a method. Once a delegate is assigned a method, it behaves exactly like that method. The delegate method can be used like any other method, with parameters and a return value. (source : MSDN )

delegate is defined by delegate keyword lets understand with example I am creating delegate with name Math

delegate int Math(int value1, int value2);

in this delegate 2 int argument and int return type so we can assign any function’s reference which takes 2 int arguments and returns int value, I created a method for sum two values.

       public static int Add(int a, int b)
        {
            return a + b;
        }

I can assign reference of this method to Math delegate, like

Math math = Add;

and call this delegate

math(1, 1);

it return 2 because this delegate call Add method. We can also assign anonymous methods to delegate

Math math = delegate(int a, int b) { return a + b; };

above I created a anonymous method and assign to  math delegate. we can also use lambda (=>) notation for creating anonymous functions.

Math math = (a, b) => { return a + b; };

We can also write if our anonymous method contains only one statement

Math math = (a, b) => a + b;

in above statement no need to write datatype, lambda notation widely used in C# these days for creating anonymous methods.

    class Program
    {
        delegate int Math(int value1, int value2);

        static void Main(string[] args)
        {
            Math math = (a, b) => a + b;

            Console.Write(math(1, 1));
        }

        public static int Add(int a, int b)
        {
            return a + b;
        }
    }

delegate allows to pass functions as arguments and its very powerful feature of .net with this we can create more generic method, lambda notation used for passing small methods to function.

Let understand a example in this I am passing method’s reference to method for creating more generic method.

class Program
    {
        public delegate bool NameCriteria(string name);

        static void Main(string[] args)
        {
            var namesstartwithm = GetNames(name => name.StartsWith("M"));

            Console.WriteLine("--- Name which are starts with M char ------");
            foreach (var name in namesstartwithm)
            {
                Console.WriteLine(name);
            }

            var names = GetNames(name => name.Count()<=3);

            Console.WriteLine("\n\n--- Name which are contains less then or equals to 3 chars ------");
            foreach (var name in names)
            {
                Console.WriteLine(name);
            }

            Console.ReadLine();
        }

        public static IEnumerable<string> GetNames(NameCriteria namecriteria)
        {
            List<string> names = new List<string>();
            names.Add("John");
            names.Add("Martin");
            names.Add("Tom");
            names.Add("Nick");
            names.Add("Geoge");
            names.Add("Matt");

            foreach (var name in names.AsEnumerable())
            {
                if (namecriteria(name))
                {
                    yield return name;
                }
            }
        }
    }

//output
//
//--- Name which are starts with M char ------
//Martin
//Matt

//--- Name which are contains less then or equals to 3 chars ------
//Tom

in above program I created a method GetNames (in this I create List of names for example) it returns list of names as IEnumerable and it takes one parameter NameCriteria (defined at first line of class Program) type, NameCriteria is a delegate this delegate takes one string parameter and return boolean value.In GetNames method I iterate the name list and pass name to the namecriteria delegate and check if it is true then return. (note yield used to return iterate values)

Then I used this method for two type

1. in first I passed following anonymous method, it check is name starts with ‘M’

name => name.StartsWith("M")

2. in second I passed following anonymous method, it check is name contains less then or equals 3 chars.

name => name.Count()<=3

ASP.NET Performance best practice

I am going to describe, how to gain good performance in asp.net website. I am explaining in two categories

1. On server Side : We should code which can take care of response time for this we can follow these following things

  1. Try to avoid ViewState : if you don’t need ViewState then Disable View state on page level.

    there are many levels of disabling of ViewState

    1. Control level : we can disable ViewState for specific control

                <asp:TextBox ID="TxtCustomerID" runat="server"  EnableViewState="false" />
                

    2. Page level : we can disable view state of whole page

                <%@ Page Title="Customer" Language="C#" EnableViewState="false" %>
                

    3. Directory level : we disable view state on directory level, just add location tag under configuration tag in web.config, in following example I am disabling ViewState for Docs directory.

                <location path="~/Docs">
                     <system.web>
                          <pages enableViewState="false"></pages>
                     </system.web>
                </location>
                

    4. Website level : for disabling ViewState on website level, set enableViewState property false of pages tag under system.web tag in web.config

                <pages enableViewState="false"></pages>
                
  2. Reduce DataBase calls

    Always try to merge database calls from application because more call make your site slower. Its make more slower when database server far from application server.

  3. Use Generic Collections instead of DataTable/DataSet :

    use generic collections instead of DataTable/DataSet both DataTable and DataSet consume more time, CPU power and Memory also. Generic collections have various features like Sorting, Searching help of Linq

  4. Try to use Repeater :

    try to use Repeater , because GridView / DataList are very heavy data controls.

  5. Don’t use  more session variables :

    Session store data on server side so more session variable consume more server memory, Store more sensitive data only otherwise try to store in cookie, hidden fields or other state

  6. Don’t send huge cookies :

    Because cookies always send with request by browsers and set expiry time also. even if you are requesting static js or css file cookie will send for these requests also.

  7. Use store procedures :

    Because calling of  store procedures we need to send only name of store procedure and arguments not whole query, if we are using huge query then we can transfer it in store proc so we need to call only store proc and pass variables and store proc make re-usability of sql query

  8. Use DataReader instead of SqlDataAdaptor :

    DataReader work in connected mode and fetch data very faster then SqlDataAdaptor.

  9. Use StringBuilder if you want to more append operation :

    If we using String object and append more time then it will create one object every time.

    following string example create 6 copies of string object

                 string param = "?id=32";
                 param += "&q=ianswerable";
                 param += "&val=2343";
                 param += "&pid=XWE";
                 param += "&sno=55624";
                 param += "&page=2";
            

    and this StringBuilder example create one copy only

                 StringBuilder param = new StringBuilder();
                 param.Append("?id=32");
                 param.Append("&q=ianswerable");
                 param.Append("&val=2343");
                 param.Append("&pid=XWE");
                 param.Append("&sno=55624");
                 param.Append("&page=2");
            

  10. Avoid Exception :

    Don’t wait of Exception check your Exception case and handle it in if statement, see example code first example throw exception and in catch number assigned by 0 but second example check in condition

    Example 1 :

                int number;
                try
                {
                    number = Convert.ToInt32(value);
                }
                catch(Exception ex)
                {
                    number = 0;
                }
            

    Example 2 :

                int number=0;
                if (int.TryParse(value, out number))
                {
                    // use int value
                }
            

  11. Use Caching :

    It is very awesome feature of asp.net for more detail click here

  12. Deploy released version on production.
  13. Disable tracing :

    when you publish site on production for more about tracing click here

  14. Stop repeated code run :

    Make sure your code doesn’t run more then one time on one call, always care of this matter otherwise your app perform very slow. use Page.IsPostBack for stopping running code again and again

  15. Use server side paging if data is huge :

    If your data is huge means large number of data then you should use server side paging and select only page record from sql server using ROW_NUMBER()

  16. Avoid use of regular expressions for server side validation Example :

    for float number validation you can use Double.TryParse() method.

  17. Use output buffering feature of asp.net.
  18. Use gzip compression.
  19. Remove unused HttpModules
You can visit these links these are really helpful for you.
2. On client side : 
  1. Make fewer http request :

    always try to combined external javascript and css files.

  2. Use CSS sprite :

    combined images into single images and show through css, this decrease http requests and make your website faster

  3. Minimize css and js :

    always minimize css and js on production, remove extra spaces tabs etc, you can use some tools for that my favorite is closure compiler

  4. Use .png images :

    .png can be used with transparent background intead of white or other, so .png are lightweight then other format of image

  5. Don’t scale images in html or css always use proper size images.
  6. Add expiry headers :

    Add expiry headers for all static contents so contents cache by browsers and not load every request just load from browser cache.

  7. Use CDN for static contents :

    You can use Google and Microsoft cdn for general js library like jQuery , jQuery UI etc. , CDN have some attributes which are provide static resources faster and parallel. CDN url should be cookie free.

  8. Add Css at top and Js at bottom :

    So page load faster because body never load unless load all resources of head section. css need for styling so use css files at top.

  9. Always put css and js in external files :

    External files save in browser cache so not load on every request just load from browser cache.

  10. Don’t use css expression :

    Js in css like

            .header
            {
               background-color: #CFCFCF;
               position: absolute;
               left:expression(document.body.clientWidth/2-oDiv.offsetWidth/2);
               top:expression(document.body.clientHeight/2-oDiv.offsetHeight/2);
            }
            

  11. Always try to reduce DOM elements :

    More Dom elements slow you website on client side, so try to reduce.

  12. Write reusable js and css code :

    Don’t repeat your logic in css and js because this logic increase size of code and it slow your site.

  13. Use ID selector instead of class selector in jQuery.
  14. Reduce DNS lookups :

    reduce http request , use IP for static content if possible etc.

  15. Don’t use duplicate script.
  16. You can use delay loading of page for more info click here
  17. Try to use GET requests.
  18. Reduce use of iframes.
  19. Avoid 404 :

    Remove all blank src and href property of any element

  20. Use cookie free domains for static contents.
  21. Optimize images , don’t use heavy images.
For Performance test on client side you can use two great tools 

Code Maintainability Best practices

Requirements never stay constants, every software will be changed so as a developer we must code carefully.  If we follow some kind of rules we can code better software for future.

    1. Always break you software in layers, most famous architecture is n-layer. Break your software in 4 layers
      1. Data Access Layer : Data from any data source should be directly fetch by this layer and fill the Business Object Layer, SQL queries fire from this layer.
      2. Business Object Layer : This Layer fill by Data Access Layer  and Transmit data to the Business Logic Layer
      3. Business Logic Layer : this layer manipulate data and send to UI layer and get data from UI layer validate that and sends to data access layer for saving , deleting etc.
      4. UI layer : its presentation layer  I recommended use MVC for this
        1. Model : this layer Transmit data between Controller and View & convert to business object layer.
        2. Controller : control the view and fills to model
        3. View : its just presents the model in visible format
      5. Utility layer : utility classes and methods should be included into this Layer, in this layer more general functions like conversion, input validation etc
      6. Every layer should be independent no layer will affect the other. Like UI specific things never used in Business logic layer and data specific things also never used in BLL and Logical task never completed by UI or DAL.
    2. Always Use strongly typed : I recommended strongly typed so we can handle things at compile time and Ignore mistakes , I always prefer to ignore magic string like session key etc. you should create a strongly typed session manager class.

      1. Possibly use  deserialization of  XML and JSON instead using parser and get them from key so it is good to manage and it is type safe also.

      2. Don’t fetch querystring value though magic string key, use strongly typed wrapper class for that.

      3. Use ORM like Nhibernate, Entity framework or Linq-To-Sql etc for data access layer , if you are worried about performance the you need to use micro ORM like Dapper, Massive or Peta Poco etc.

    3. Always  Interact through layers to any kind of service : Never interact direct to any kind of service , always interact through layers , let understand with examples
      1. If you are reading data from twitter api to read tweets always create bridge for this so you can anytime change your tweet service , you can consume RSS instead of Tweets or twitter change the api response type
      2. Using any kind of REST or SOAP service, create strongly typed wrappers and then use this services so always be regular programming.
      3. Reading app setting from webconfig don’t consume them directly so you if you are changing any kind of environment like hosted to cloud or any other you will never face any dependency issues.
      4. Consuming RSS feeds and presenting on you website.
    4. Logic , Code , Identifier and structure should be readable : Try to code clean and clean don’t compromise with coding standard.
      1. Use standard naming conventions
      2. Consistency is most valuable thing in project
      3. Teach you self core concepts Generics, design patterns, oops, language features all basics.
      4. Some code Attributes
    5. Some code Attributes
      1. Readability: Code should be readable every time code that you are trying to make code for others.
      2. Maintainability: Code should be maintainable,  Before start write code always think about extendibility of that module.
      3. Performance: write code which can perform better and better.
      4. Complexity: Code should be less complexity, if you in middle of that situation that where you need to write more complex codes then you should write more helpful comments.
      5. Reusability: Write more generic code so cab be reused in future.
    6. Always follow better design patter for more information read ‘head first’ and ‘GoF design pattern’ both are awesome described.
      1. Most useful factory design pattern for data access layer, also can be used Repository pattern.
      2. Strategy design pattern, I use this for Reading app key from IIS or Azure environment create strategies for Azure and IIS and strategy contains reading methods and then I assign strategies after checking Role Environment of azure.
      3. Proxy pattern for creating RESTfull or SOAP API or generating RSS feeds.
    7. Always keep in mind
      1. Never pass environment specific things to other layers , example
        1. Request object to BLL, BOL, or DAL should be limited to UI or Controller
        2. SqlCommannd object to BLL
        3. Validation object to DAL (email validation url)
      2. Never write huge LOC for single method or class
      3. Never repeat your logic again and again if are going to write method always try to make that generic 99.99 possibility it will be used in future for different purpose so no need to write this logic again
      4. Create extension methods for  framework classes so code look much cleaner,
        1. To check is string is valid emailID
        2. To get all session key for current session
        3. One I use for debugging object dumper method, I created a extension method for object class so I can anytime dump any object just using this method.
      5. Use int.TryParse double.TryParse like methods to convert data string to int or double these are more reliable.
      6. XML comment and write all information about parameters  and method summary
      7. Try to make things centralize like set you validation failure messages in one class and use it everywhere.
        1. Use Page Base or Base Controller for all controller or Code Behind files
        2. Make user control for same part using multiple time
        3. Master page – no need to tell more
      8. For more reusability you should separate code perfectly and assign Single responsibility to every function, class, enum etc.

.