About Hasmukh patel

My Photo
Harrow, London, United Kingdom
Dot-Net developer with expertise in Web, WPF, Win-form applications. Have worked on Asp.net,mvc , WPF and Win-forms projects in c#.net language having Sql-Server/Oracle as database with service oriented architecture using test driven development. Having complete knowledge of SDLC and have successfully worked and implemented it on projects.

Enhancing Web Application Performance

Enhancing Web Application Performance

Every one wants to perform fast their web application. While developing and testing with debug mode looks perfect even when QA team test with release build, works fine because all servers were internal, of course internal networks are always faster. When system goes on internet then it gradually slows down.

Important note about web browser: most of the web browser support only 6 web requests to same domain, as result next all requests will be in queue and will be send as soon as processing request get the response.



Few tricks to increase web application:

Enabling Client Caching with Web.config:

This one is the easy way to increase speed up of loading static content like CSS file, javascript files, images and Templates (jQuery templates). Just you need to add Web.config file into Content and Scripts folder and its sub folders with following settings.



<?xml version="1.0" encoding="UTF-8"?> 
<configuration
  <system.webServer
    <staticContent>
      <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="30.00:00:00" />
    </staticContent
  </system.webServer
</configuration>
 
Note: this Web.config not for root of your web application
Enabling Client Caching with OutputCacheAttribute attribute in MVC:
public class HomeController : Controller
{
    [OutputCache(Duration = 60)] //for a minute
    public ActionResult Index()
    {
         //your code
    } 
    [OutputCache(Duration = 86400)] //for a day
    public ActionResult About()
    {
         //your code 
    }
 
    [OutputCache(Duration = 86400)] //for a day
    public ActionResult Contact()
    {
         //your code 
    } 
} 

Using a CDN

If your application is on internet or if it is on intranet and user has access of internet then there is a another way to increase the performance of your web application to use of a CDN (Content Delivery Network). As I said in my Web Browser note, web browser can process only 6 request from same domain, if use CDN then CDN domain is another domain like google or jquery or something else, so your web browser can process more than limited request and if those are the common file which might be used with another web site or application, as result file may be already in your local cache so no need to load from CDN server again.

Example of CDN:

<link href="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.css" rel="stylesheet" /> 
<link href="http://code.jquery.com/mobile/1.1.0/jquery.mobile.structure-1.1.0.min.css" rel="stylesheet" /> 
<script src="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.js" type="text/javascript"></script> 
<script src="http://code.jquery.com/jquery-1.6.4.min.js" type="text/javascript"></script>
<script src="http://ajax.aspnetcdn.com/ajax/mvc/3.0/jquery.unobtrusive-ajax.min.js" type="text/javascript"></script> 
<script src="http://ajax.microsoft.com/ajax/jQuery.Validate/1.6/jQuery.Validate.min.js" type="text/javascript"></script> 
<script src="http://ajax.aspnetcdn.com/ajax/mvc/3.0/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>
 

Pre load page with jQuery.Mobile’s Prefetch Tag

If your application based on next & previous or displaying images, you can use jQuery.Mobile prefetch to preload the content into memory while user reading or viewing current content.

<a href="nextpage" data-prefetch>Next Page</a>
 
When user request for nextpage, the content of next page will load instantly because the page was already loaded in background. This content only for single load, when user moves to next page all content will be removed from memory. If you want to keep in memory, you can use data-dom-cache=”true” on the page evement, it will not be unloaded, so next time it will load faster.

MVC 4 Bundles

MVC 4 has a new great feature called Bundles, which allows you to create a bundle of static content files in a single bundle. So bundle feature will reduce number of individual content file request to 1 or 2 requests. The bundle feature put all files together, compress and removes species and remove commented code from the bundle.


 
Code:
        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/jquery-{version}.js"));
 
            bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include(
                        "~/Scripts/jquery-ui-{version}.js"));
 
            bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                        "~/Scripts/jquery.unobtrusive*",
                        "~/Scripts/jquery.validate*"));
 
            bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                        "~/Scripts/modernizr-*"));
 
            bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.css"));
 
            bundles.Add(new StyleBundle("~/Content/themes/base/css").Include(
                        "~/Content/themes/base/jquery.ui.core.css",
                        "~/Content/themes/base/jquery.ui.resizable.css",
                        "~/Content/themes/base/jquery.ui.selectable.css",
                        "~/Content/themes/base/jquery.ui.accordion.css",
                        "~/Content/themes/base/jquery.ui.autocomplete.css",
                        "~/Content/themes/base/jquery.ui.button.css",
                        "~/Content/themes/base/jquery.ui.dialog.css",
                        "~/Content/themes/base/jquery.ui.slider.css",
                        "~/Content/themes/base/jquery.ui.tabs.css",
                        "~/Content/themes/base/jquery.ui.datepicker.css",
                        "~/Content/themes/base/jquery.ui.progressbar.css",
                        "~/Content/themes/base/jquery.ui.theme.css"));
        }
 
Now in your Layout.cshtml file
Beginning of file
    <head>
........
        @Styles.Render("~/Content/css")
        @Scripts.Render("~/bundles/modernizr")
    </head>
End of the layout.cshtml file 
        @Scripts.Render("~/bundles/jquery")
        ...
    </body>
</html>

Web Application Custom Authentication

In order to implement custom authentication, application’s forms cookie need to override with custom user object with implementation of IPrincipal and IIdentity interfaces.
When application request for authenticate user then system fire an event of Application object.  
Implement authentication in Global.asax.cs
Add Application_AuthenticateRequest event into the Global.asax with AuthenticationTicket extension method.
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
      Context.AuthenticationTicket();//invoke extension method
}
When user request for login with valid credential, application should authenticate user and set application’s forms cookie with encrypted user information so next time user try to access any resources which required authenticate user, user will be authenticate by Application_AuthenticateRequest using application’s forms cookie.
To set authentication cookie 
Call AuthenticationProcessor.SetAuthenticationTicket(httpContext, user);
 
Create a static class to implement extension methods as below  
using System;
using System.Security.Principal;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.Security;
using DemoLib.Shared.Models;
 
namespace Mvc3Demo.Core
{
    public static class AuthenticationProcessor
    {
        public static void SetAuthenticationTicket(this HttpContextBase httpContext, User user)
        {
            var ticket = new UserTicket
                             {
                                 Name = user.UserName,
                                 Role = user.Role.RoleName,
                                 Id = user.Id
                             };
 
            var jsonSerializer = new JavaScriptSerializer();
 
            var userData = jsonSerializer.Serialize(ticket);
 
            var authTicket = new FormsAuthenticationTicket(1, user.UserName, DateTime.Now, DateTime.Now.AddHours(1), false, userData);
 
            string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
 
            var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
 
            httpContext.Response.Cookies.Add(authCookie);
        }
 
        public static void AuthenticationTicket(this HttpContext httpContext)
        {
            HttpCookie authCookie = httpContext.Request.Cookies[FormsAuthentication.FormsCookieName];
 
            if (authCookie == null || string.IsNullOrEmpty(authCookie.Value))
                return;
 
            try
            {
                FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
                
                var jsonSerializer = new JavaScriptSerializer();
 
                var ticket = jsonSerializer.Deserialize<UserTicket>(authTicket.UserData);
 
                var demoIdentity = new DemoIdentity(ticket.Name)
                                       {
                                           User = ticket,
                                       };
 
                httpContext.User = new DemoPrincipal(demoIdentity);
            }
            catch (Exception ex)
            {
 
            }
        }
 
        public class DemoPrincipal : IPrincipal
        {
            private readonly DemoIdentity _loyaltIdentity;
 
            public DemoPrincipal(DemoIdentity loyaltIdentity)
            {
                _loyaltIdentity = loyaltIdentity;
            }
            public bool IsInRole(string role)
            {
                return role.Contains(_loyaltIdentity.User.Role);
            }
 
            public IIdentity Identity { get { return _loyaltIdentity; } }
 
            public DemoIdentity LoyaltIdentity { get { return _loyaltIdentity; } }
        }
 
        public class DemoIdentity : IIdentity
        {
            public DemoIdentity(string name)
            {
                Name = name;
            }
 
            public string Name { getprivate set; }
            public string AuthenticationType { get { return "Custom"; } }
            public bool IsAuthenticated { get { return true; } }
 
            public UserTicket User { getset; }
 
        }
 
        public class UserTicket
        {
            public int Id { getset; }
            public string Name { getset; }
            public string Token { getset; }
            public string Role { getset; }
        }
    }
}

Host WCF Services with generic utility

Generic WCF Service Host
Generic service host allows you to host any WCF service which writes logs on each start so you don’t need to write manual log for individual service.
Logging utility based on EnterpriseLibrary , code is as below
using System;
using System.ServiceModel;
using DemoLib.Utilities.LoggingUtilities;
using DemoLib.Utilities.Properties;
 
namespace DemoLib.Utilities.ServiceUtilities
{
    public class GenericServiceHost<T> : ServiceHost
        where T : class
    {
        public GenericServiceHost()
            : base(typeof (T))
        {
        }
 
        protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
        {
            Log.LogInformation(string.Format(Resources.StartingService, typeof (T).FullName));
            return base.OnBeginOpen(timeout, callback, state);
        }
 
        protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state)
        {
            Log.LogInformation(string.Format(Resources.StopingService, typeof (T).FullName));
            return base.OnBeginClose(timeout, callback, state);
        }
 
        protected override void OnAbort()
        {
            Log.LogWarning(string.Format(Resources.AbortingSerivce, typeof (T).FullName));
            base.OnAbort();
        }
 
        protected override void OnFaulted()
        {
            Log.LogError(string.Format(Resources.ServiceFault, typeof (T).FullName));
            base.OnFaulted();
        }
    }
}
To install Enterprise Library 5.0 - Logging Application Block, run the following command in the Package Manager Console
PM> Install-Package EnterpriseLibrary.Logging
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.Practices.EnterpriseLibrary.Logging;
 
namespace DemoLib.Utilities.LoggingUtilities
{
    public  static class Log
    {
        public static void LogError(string message)
        {
            LogMessage(message, "Error"TraceEventType.Error);
        }
 
        public static void LogWarning(string message)
        {
            LogMessage(message, "Warning"TraceEventType.Warning);
        }
 
        public static void LogInformation(string message)
        {
            LogMessage(message, "Information"TraceEventType.Information);
        }
 
        public static void LogDebug(string message)
        {
            LogMessage(message, "Debug"TraceEventType.Verbose);
        }
 
        private static void LogMessage(string message, string category, TraceEventType eventType)
        {
            var logEntry = new LogEntry
            {
                Message = message,
                Severity = eventType,
                MachineName = Environment.MachineName,
                Categories = new List<string>() { category }
            };
 
            Logger.Write(logEntry);
        }
    }
}
Examples of generic service host utility
        #region Private methods
 
        private ServiceHost _authServiceHost;
        private ServiceHost _userServiceHost;
        ServiceHost _emailServiceHost;
 
        #region note for port sharing service
            //type services.msc and set "NetTcpPortSharing" start type to manual
            // start service 
            //net start NetTcpPortSharing
            // add SID in to SMSvcHost.exe.config (C:\Windows\Microsoft.NET\Framework\v4.0.30319) or task mgr (services)-> NetTcpPortSharing -> go to process -> go to file location 
            // get SID wmic useraccount get name,sid
            #endregion
 
        private void StartServices()
        {
            _authServiceHost = new GenericServiceHost<AuthoService>();
            _authServiceHost.Open();
 
            _userServiceHost = new GenericServiceHost<UserService>();
            _userServiceHost.Open();
 
            _emailServiceHost = new GenericServiceHost<EmailService>();
            _emailServiceHost.Open();
        }
 
        private void StopServices()
        {
            if (_authServiceHost != null)
                _authServiceHost.Close();
 
            if (_userServiceHost != null) 
                _userServiceHost.Close();
 
            if (_emailServiceHost != null) 
                _emailServiceHost.Close();
        }
 
        #endregion

TypeScript basics


 TypeScript is a free and open source programming language developed by Microsoft to generate JavaScript from class-based object oriented programming language. TypeScript supports ECMAScript 6 classes that integrate the optional type annotations support.
Install TypeScript
You can install TypeScript via an nuget package manger package for node.js or as an MSI that integrates with Visual Studio 2012.
After installing, TypeScript for Visual Studio 2012 you can create TypeScript file .TS file and edit in TypeScript editor.
Example of TypeScript (TypeScript/TestScript.ts is a file name)
// Interface
interface IPoint {
    getDist(): number;
}

// Module
module Shapes {

    // Class
    export class Point implements IPoint {
        // Constructor
        constructor (public x: numberpublic y: number) { }

        // Instance member
        getDist() { return Math.sqrt(this.x * this.x + this.y * this.y); }

        // Static member
        static origin = new Point(00);
    }

}

// Local variables
var p: IPoint = new Shapes.Point(34);
var dist = p.getDist();
Manual Compile TypeScript
Go to command prompt, then type
>tsc ../TypeScripts/TestScript.ts --out ../Scripts/TestScrip.js
Compile with Web project
Go to web project property and type "tsc ../TypeScripts/TestScript.ts --out ../Scripts/TestScrip.js" in the Build Events' Pre-build event command line textbox.
If you have multiple files then create a text file and type all command in that file and change above command as "tsc @../TypeScripts/Scripts.txt"
There is a Compile-on-save feature available with  Visual Studio TypeScript editor.
References from another library
e.g. JQuery example
You need to add a reference to the jQuery definition at the top of your .ts file.
/// <reference path="jquery.d.ts"/>

/// <reference path="someclass.ts"/>


e.g.
//MainModule.ts
// Interface
interface IPerson {
    age: number;
    name: string;
    getDetails(): string;
}

// Module
module MainModule {

    // Class
    export class PersonBase implements IPerson {
        // Constructor
        constructor (public age: numberpublic name: string) { }

        getDetails() { return this.name + ' ' + this.age; }
    }
}

//PersonProcessor.ts
/// <reference path="./MainModule.ts" />
module PersonProcesser { 
    
    //derived class from  personBase
    export class  Person extends MainModule.PersonBase implements IPerson
    { 
        address: string;
        //Constructor
        constructor (age:number, name:string, addr: string){
            super(age, name);
            this.address = addr;
        }

        getDetails() { return this.name + ' ' + this.age + ' ' + this.address; }
    }
}
// Local variables
var person : IPerson = new PersonProcesser.Person(20,"abc""abc street, xyz city")
var details = person.getDetails();
Get more details about TypeScript modules.

TypeScript type definitions repository for popular JavaScript libraries

Entity framework Code first basics



Entity framework Code first basics

Entity framework Code first allows you write code without database. first you have create your POCO classis then map with relevant database tables.

To start writing code with EF code first, you need to download relevant "Entity framework Code first" package from Nuget Package manager. 

To install EntityFramework, run the following command in the Package Manager Console

PM> Install-Package EntityFramework -Version 4.2.0.0

  Create POCO class

using System.ComponentModel.DataAnnotations;
    public class BasicUser
    {
        [Required]
        [Display(Name = "User name")]
        public string UserName { getset; }
 
        [Required]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { getset; }
        
    }
 
    public class RegisterUser : BasicUser
    {
        [Required]
        [DataType(DataType.EmailAddress)]
        [Display(Name = "Email address")]
        public string EmailId { getset; }
    }
 
    public class User : RegisterUser
    {
        public int Id { getset; }
 
        public int RoleId { getset; }
        public virtual Role Role { getset; }
    }
 
    public class PublicUser : User
    {
        public string Addess { getset; }
    }
 
    public class InternalUser : User
    {
        public string Dept { getset; }
    }
 
    public class Role
    {
        public int Id { getset; }
 
        [Required]
        [Display(Name = "Role name")]
        public string RoleName { getset; }
 
        public string Permissions { getset; }
    }
Create DataContext
using System.Data.Entity;
using {your model namespace}.Models;
 
    public class DemoDataContext : DbContext
    {
        public DemoDataContext()
        { }
 
        public DemoDataContext(string connectionString)
            : base(connectionString)
        {
 
        }
 
        public DbSet<User> Users { getset; }
        public DbSet<Role> Roles { getset; }
        public DbSet<News> News { getset; }
        public DbSet<UserTask> Tasks { getset; }
 
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<User>().ToTable("User");
            modelBuilder.Entity<Role>().ToTable("Role");
            modelBuilder.Entity<News>().ToTable("News");
            modelBuilder.Entity<UserTask>().ToTable("Task");
            modelBuilder.Entity<PublicUser>()
                .Map(x=>x.Properties(p=> new
                    {
                        p.Addess
                        
                    })).ToTable("PublicUser");
 
            modelBuilder.Entity<InternalUser>()
                .Map(x => x.Properties(p => new
                {
                    p.Dept
 
                })).ToTable("InternalUser","dbo");
        }
 
        public override int SaveChanges()
        {
            return base.SaveChanges();
        }
    }
Instatiate DB context
  using (var db = new DemoDataContext())
            {
                return db.Users.FirstOrDefault(x => x.Id == id);
            }
in above example case you need connection sting in your Hosting Application Setting as below; 
  <connectionStrings>
    <add name="DemoDataContext" providerName="System.Data.SqlServerCe.4.0" connectionString="Data Source=.\Databases\DemoDatabase.sdf" />
  </connectionStrings>
Note: name should be same as DataContext Name alternatively you can pass your connection string as below
 using (var db = new DemoDataContext("your connection string"))
            {
                return db.Users.FirstOrDefault(x => x.Id == id);
            }