Tuesday, 27 December 2011

Best Practices of ASP.Net

 I always want a cheat sheet that has a best practices written in a classified manner so it will be easy to remember and also easy to refer. 

Below table for Best Practices of ASP.Net solves that problem. All the details given below are very SHORT and mostly solves PERFORMANCE issues. If you want to read about why the best practices should be followed, just type in the Google bar whatever it is written in the table with asp.net text concatenated. You can find why the particular best practices need to be followed. It is actually for people who have already worked in asp.net and they need a cheat sheet to remember when they are attending interview or reviewing code.


Level
DO's and Don’t's
.Aspx Level


Disable Session State if not needed

Disable View State if not needed, e.g.:- static page

Use Lesser Web Controls, try normal HTML Controls if possible

Scripts should be placed at the end of page, Scripts hinders loading

Try removing scripts from aspx page to separate JS file

Try removing styles from aspx page to separate Stylesheet file


.CS Level


Use Server.Transfer instead of Response.Redirect wherever possible

Use String builder instead of String concatenation using '+'

Handle exception in previous layer do not through till presentation layer

Use IsPostBack always in Page_Load and wherever possible

Always use Arraylist instead of Array

Use Page.IsValid for validating the whole page

Cache object if it is frequently used

Design using Value types.

Use ASCII Format instead of UTF

Use Format() instead of toString()

Remove unnecessary looping inside code

Check all loops. Identify any code that needs to be
outside loop and remove from the loop


Config Level


Disable Tracing in production environment

Set Debug = false in compilation tag


JS & Stylesheet


Remove scripts or Stylesheet that are never used from the respective files




Talk to you soon

IMPORTANT: Leave a comment to share what you learned, and hit the “like” button to let others know about it (make sure you’re logged into Facebook to like and comment).


Monday, 19 December 2011

Why DLL's Should be Signed




Ever been in a project where you are asked to create Strong Name for DLL and you created a Strong Name for one project and the compiling project solution started giving you weird compilation errors. I have been there many times. When facing those issues I had some questions that crossed my mind.  

·        What is Strong Name?
·        What is significance of a Strong Name?
·        Why we need strong name? Do all DLL's need strong names to be created?
·        What happens actually when Strong Name is created
·        How Strong Name is used in real time scenario?

Basics before Deep Dive

           Before deep dive let us brush through following basics. We will look into following
1.      Assembly
2.      Encryption
3.      Hashing
4.      Digital Signatures

Assembly 

        Assembly is a compiled code library used for Deployment, Security and Versioning. EXE and DLL are different type of assembly. It consists of Name, Culture, Version and Public key token.

Encryption

            Encryption is a process of converting information into unreadable using an algorithm and unreadable information can only be converted to readable format using special information called as key.

   They are of two types
a)     Symmetric Cryptography
b)     Asymmetric Cryptography
Let us concentrate only on Asymmetric cryptography since the symmetric cryptography is flat straight forward cryptography.

Asymmetric cryptography provides a very secure mechanism for encrypting and decrypting data, due to its use of a pair of keys called the private and public keys.

Private Key should never be passed to another entity.
 Public key is opposite it should be passed.

The private key is held by one entity and securely locked down. It should never be passed to another entity. The public key is the opposite; you can give the public key to anyone who requests it.


Let us consider an analogy, Gates and Steve wants to communicate with each other. They choose the Asymmetric way. Gates send an open box with automatic numeric padlock. This numeric padlock can be closed automatic but it needs key to open.

Open Box = Public Key
Numeric padlock key = Private Key


Open box is considered as public key where everyone can be aware of them. Steve places the message and closes the automatic open numeric padlock box. Here the key that is used to open the box is the private key.

Hashing

       What if the data is changed after the data is placed in the box (Even box along with content). To avoid the change of data after or before encryption, we use the process called hashing. A Cryptographic hashing function will take a block of data of arbitrary size and returns a fixed size of binary data known as Hash value. If you change the original block of data in any way, the calculated hash value changes. If a single bit is changed in the original data, at least fifty percent of the calculated hash value’s bits change. If the data has not changed and you calculate the hash value over and over, the hash value will be the same. If you copy the data and calculate its hash value, it’ll be the same.

Digital Signatures

A digital signature proves that a message hasn’t been modified and proves the identity of its author.

Combination of Asymmetric encryption and Hashing

This is an essential combination of two topics that have been already covered in this topic: asymmetric encryption using the private key, and hashing. A digital signature is created by calculating a hash of data, followed by encrypting the hash, with a private asymmetric encryption key.

Deep Dive is over guys let’s go back to surface to discuss about what we are really for.

What is Strong Name?

        Strong Name is Technology used to uniquely identify Assemblies. It consists of Name, Version Number, Culture, Public key token and Digital signature.

What is Significance of a Strong Name?

           Strong Name solves two purposes. 

1.      Versioning  
2.      Authentication.

Versioning solves the problem called “DLL Hell”. Since it is technology to uniquely identify assembly, the same DLL name can exist in same folder (GAC) with different version number.
Authentication, the process we want to ensure ourselves the origin of the code. This is solved since we sign the assembly, which solves the authentication issues.


Why we need Strong Name? Do all DLL's need Strong Names to be created?


As we have discussed the Strong Name solves the purpose of versioning and authentication, the Shared or public assembly when signed with Strong Name it can be published in GAC (Global Assembly Cache). Any one who uses our assembly can be sure that they are using correct version and assembly which is not modified by external sources.

Strong Name signing is only for Shared or Public Assembly

Strong Name signing is only for shared or public Assembly. We don’t need to sign the assembly with Strong Name if we are only using assembly in our own executables.

What happens actually when Strong Name is created? How it is used in real time scenario
                   Let’s separate the process of creation and utilization of strong Name. When you add a strong name to a library the compiler creates a hash over most of the assembly. The hash is encrypted with the publisher's private key to form the strong name signature. The strong name signature and the public key are then placed in the assembly.
  Compiler stores the full name of the signed assembly into the assembly it is creating

When you tell the compiler that you will use a strong named assembly, the compiler stores the full name of the signed assembly into the assembly it is creating. This is reason why two DLL with same name can exist in GAC Folder The full name includes the public key, and because this is large, the runtime uses part of the hash of the public key, called the public key token.









When .NET loads the referenced assembly it verifies that the assembly has specified the public key, and of course, it can do this by extracting the public key and hashing it to be able to extract the public key token. It also needs to verify the public key, and it can do this by generating the hash of the referenced assembly. The strong name signature is this hash encrypted with the private key, so only the correct public key can decrypt it.

 Thus the runtime extracts the strong name signature decrypts it with the public key and if the result does not agree with the hash it generated the runtime will not load the assembly.

Now we had close look at the DLL signing process with basic included. Hope this will be helpful even for people who are new to Encryption.



IMPORTANT: Leave a comment to share what you learned, and hit the “like” button to let others know about it (make sure you’re logged into Facebook to like and comment).

       




Thursday, 27 October 2011

Creational Pattern - A Close Look

 Ever Wondered in  a new project while creating a new module or a page that would have given a compilation error or a screen pops up without any default data being loaded in the master controls.

 We know consciously or unconsciously that we did not implement an interface or did not implement a  default method or set a value in default property.


   We have been there many times. I would say most of this issue happens either the COMPILATION ERROR or a BLANK SCREEN WITHOUT DATA are due to following reasons.


  • We did not understand what they have implemented in different layers.
  • Current project is not designed using any design pattern, that force the user to implement certain methods by default, eg. say Interface
  • Multiple patterns are used which solves different problem and we cannot figure out what is the actual purpose of the pattern which is used to solve the respective problems.
 Here we will see real time example where different pattern are used to get solution for different type of problems.


 Let us consider my previous project about travel agent for booking airline tickets. This is the biggest project i have worked till  now. We will only talk about scope which will be useful for us in explaining our Creational Pattern.

Problem Statement:


      Travel agent named OBTS(Osaka Business Travel System) manages travel needs of customers. Their main business is to take care of business travels. They reserve/book tickets for airlines/Hotel/Car that is needed for business travel. They also take care of Round trip of WORLD(RTW).


 For example: Business user and his wife flies from Japan to California takes a Rental car drives to Santa Clara, catches a flight and travels to Singapore drops his wife there and travels back to Japan. In Singapore he stays for two days.


OBTS Travel Agent will gather details about the person who travel and reserves Air/Hotel/Car. The details about the traveller and travel should be saved in our local database before booking the travel itinerary. The agent who booked the itinerary should also be saved in the itinerary.


Note: For reserving tickets in various geographical regions we need to access different servers.


Amadeus - North/South America
Abacus - Asia Pacific 
AXES - Japan/Korea
Galileo - Europe


These are commonly used servers. Each servers have different MODES OF COMMUNICATION


Amadeus - XML
Abacus - Webservice
AXES - MQ Series
Galileo - HTTP


We will discuss two CREATIONAL PATTERN which was used to solve the problem.


  1. Abstract Factory Pattern
  2. Singleton Pattern 
Abstract Factory Pattern: 


     Abstract Factory Pattern means providing an interface for creating families of related or dependent objects without specifying their concrete classes.


 In our real time example we will solve the following problem of booking tickets in different servers. Above itinerary has to be booked in different servers with different mode of inputs. Data will be same, but data format and way of communication is different for each server of same itinerary.


Japan to California - AXES
California  to Santa Clara - Amadeus
Santa Clara to Singapore - Abacus


Our first step is build a interface which has the following method that need to Book/Update/Cancel tickets. This will be the object type that will be returned when we try to Create/Modify tickets. We will name it as  IAirlineServerFactory


    public interface IAirlineServerFactory
    {
        bool BookTicket(ItineraryInfo itinerary);
        bool UpdateTicket(ItineraryInfo itinerary);
        bool CancelTicket(ItineraryInfo itinerary);

    }


IAirlineServerFactory will be the interface which gives us the objects by hiding underlying Concrete Class. Next step is to create Concrete class which will have implementation for all different servers. All the implemented class should inherit our IAirlineServerFactory.
 
    public class AbacusServer : IAirlineServerFactory
    {
        public bool BookTicket(ItineraryInfo itinerary)
        {
            //Implementation Here
            return true;
        }
        public bool UpdateTicket(ItineraryInfo itinerary)
        {
            //Implementation Here
            return true;
        }
        public bool CancelTicket(ItineraryInfo itinerary)
        {
            //Implementation Here
            return true;
        }
    }
For simplicity, we will consider only AbacusServer where the data communication is through webservice. Now we need to handle the  creation of Classes for booking tickets for different Server.
    public class AirlineServer
    {

        public static IAirlineServerFactory CreateAirlineServerFactory(String serverType)
        {
            IAirlineServerFactory airlineServer= null;

            if (serverType == "Axes")
            {
                airlineServer = (IAirlineServerFactory)new AxesServer();
            }
            else if (serverType == "Abacus")
            {
                airlineServer = (IAirlineServerFactory)new AbacusServer();
            }
            else if (serverType == "Amadeus")
            {
                airlineServer = (IAirlineServerFactory)new AmadeusServer();
            }
            else if (serverType == "Galileo")
            {
                airlineServer = (IAirlineServerFactory)new GalileoServer();
            }
            return airlineServer;

        }
        
    }


AirlineServer Class acts as factory that actually creates the dependent object based on the servertype. Let us look into FlightItinerary which consumes the class for booking tickets. .

    public class FlightItinerary
    {
        public bool BookTickets(ItineraryInfo itinerary, String serverType)
        {
            IAirlineServerFactory airlineServer = AirlineServer.CreateAirlineServerFactory(serverType);
            return airlineServer.BookTicket(itinerary);
        }
    }
 Thus the concrete class implementation is masked by the IAirlineServerFactory, so we get to book ticket without knowing the implementation of server. To FlightItinerary, it is AirlineServer that has been exposed.


Let us look into second part of the problem


The details about the traveller and travel should be saved in our local database before booking the travel itinerary. The agent who booked the itinerary should also be saved in the itinerary.


We can solve this problem using another Creational pattern named as Singleton Pattern


  Singleton pattern will ensure a class has only one instance and it has only one global entry Point.


We need to save the itinerary in our local database with the details of the agent who booked the ticket.  The details about the agent will always be the same until he logs off. So we dont need to access the database everytime a ticket is booked for agent details.


    public class AgentInfo
    {
        private static AgentInfo _instance;


        public static AgentInfo  GetAgentInfo()
        {
            if (_instance == null)
            {
                _instance = new AgentInfo();
                //Implementation for setting AgentDetails
            }
            return _instance;
        }

    }

  Whenever the agent info needs to saved in the database the application will be get the instance from GetAgentInfo(), which in turn will return new instance if it is for the first time or already created instance if the instance is already created.

Thus booking ticket in different server is handled using Abstract Factory pattern and the user details that needs to be retrieved everytime,  for saving in the local database have been handled by Singleton pattern.

Monday, 24 October 2011

Simple understanding of Design Pattern

Reason for writing this blog about Design Pattern is that it has been Greek, Latin and Hebrew for me  long time. I figured out, from some of my friends that you need to know about Design Patterns if u want to excel in Technical career. I told my self OK, am gonna figure out this myself. So i downloaded a 400 pages PDF book about Design patterns and read the whole book.

     I felt only one thing. this is really Greek and Latin.

   Actually i heard the word for the first time about design pattern from my client's architect Doi San, when i was working for a project in Japan. He said we use combined Data factory and Singleton pattern in this project. I could relate to Singleton pattern from the project, because the logged in details about the user, will be fetched from database for the first time, when the user logs in and the user object is created and saved.

 Later if we need the user details, the object will not be instantiated, it will send the object that was already created and saved, that way, the database call is only once.

   I could not understand what is Data Factory pattern for a long time even though i implemented almost 5 modules in the project throughout my 6 months tenure in Osaka. I will explain about this later, about this pattern.

  Then I tried using wikipedia to learn it in a layman's term, but no use. Every resource i referred gave me the same definition. So I went back to 400 Page PDF book.

I read the first chapter at least five time to figure out what exactly it means, once i figured out the definition by myself. It became a cake walk for me.

 So I thought, i have figured it out, why not represent in a way that will be simple & easy for others to learn, so they don't have to go through the pain i went through.

 So i have put up this blog which will be useful for others. Stick with me in reading this. You can take these below as guidelines and remember these and you can master it from there. Because first step is always the tough step.

My read of design pattern is
" Design Pattern is set of solutions available for set of problems ".

 The Gang of Four (GOF) patterns are generally considered the foundation for all other patterns. . We will discuss only  about two principles which i feel very important.
  • High Cohesion (Cohesion  meaning Relationship between methods in a class)
  • Low Coupling  (Coupling meaning Dependency between two or more classes)
Remember the above two(also the definition) which is very important, if u are interested you can read more of GOF principles.

GOF is categorized into three

  • Creational
  • Behavioral
  • Structural
Way to Remember this is Chocolates are Bitter and Sweeter.

Chocolates - CREATIONAL
Bitter          - BEHAVIORAL
Sweeter      - STRUCTURAL

What is Creational Pattern ?
                      Solution that denotes how objects should be created to solve a problem
What is Behavioral Pattern ?
                    Solution that denotes how objects should be Communicated to solve a problem
What is Structural Pattern ?
                    Solution that denotes how entities should be related to solve a problem

    If you can remember these definitions and relate what it means, then you are half way through. Let us discuss about each and every category in following blogs.






Wednesday, 12 January 2011

About Me



        His name is Karthik. He works as Software Architect in a  leading Payroll Company. He has been in this .Net world for past 9 years. He started his career in .Net 1.1. He has worked in all enterprise technologies including Web services to WCF.  He has hands on experience in IBM MQ series. MCTS certified. 

 He reads a lot. Favorite authors are Stephen covey, Richard Dawkins, Robin Baker,Stephen Hawkins and Dale Carnegie. He watches lots of Hollywood movies. His favorite movies are Matrix, Shaw shank redemption, Fight Club and all Bond movies. He is interested in taking active part in activities which includes water.

Understand and Implement Roles Vs Claims Based authentication in MVC Web API

In this blog, you will learn on how to Implement Roles and claims based authentication. You will also understand what is the difference b...