Singleton Pattern : Load Balancer Demonstration

Singleton Pattern : This is a pattern which is widely used when there is a situation to create only one instance of a class.

Lets demonstrate the pattern using a simple example.
Earlier i used to wonder how load balancer servers work. So, i decided to write an application to demonstrate both the things in one go.


Structural Pattern - Adapter Pattern - Object Adapter Pattern

I am a big time fan of Animation movies and cartoons.
I love cartoons like Calvin & Hobbes, Tom & Jerry; Animations like Shrek, Kung Fu Panda (Poo).
So, lets see how these characters will teach us Adapter pattern. :)


Behavioral Pattern - Chain of Responsibilities Using Extensibility Framework

"Change is good and Inevitable", this is what i said in my earlier post.
But not all changes are good. That is why we have Change management system in place in IT.
Because some changes will be like this :


Productivity Improvements for the Entity Framework


The improvements provide a cleaner and simpler API surface that focuses your attention on the most common scenarios but still allows you to drill down to more advanced functionality when it’s needed. We hope you will enjoy this simpler experience, but we should be quick to assure you that this is NOT a new data access technology. These improvements are built on the same technology for mapping, LINQ, providers and every other part of the Entity Framework. Think of this as a fast path to writing data access code using conventions over configuration, better tuned APIs and other techniques intended to reduce development time when using the EF.


Persistence Ignorance in Entity Framework 4.0

The intent of this post is to address below questions
a. clarify what exactly is "Persistence Ignorance"
b. what is problem with default Entity Framework infrastructure
c. How we addressed it

Entity Framework 4.0 - POCO

In earlier Post we have seen how to create a entity data model file and how to use Entity Framework infrastructure in our class library.
Lets have a close look at both File structure and Properties Window.

If you observe the highlighted items, the "Code Generated Strategy" property is set to Default. This means the entity generation from .edmx file will be taken care by framework itself. Thus resulting in .Designer.cs file which was highlighted in right.

Entity Framework 4.0 - Introduction

Entity Framework in next level of database programing which is much more flexible and adoptable than earlier methods like Regular ADO.Net and LINQ to SQL.
Comparisons between different models will be seen in another post, but lets not dig much into theory.
Rather we can concentrate on programing part, and thus you can discover what we have in EF 4.0.
We will go step by step how we can use EF 4.0 for rapid development and yet deliver a flexible and a reliable product.


Sharepoint Admin's Best Practices [MSDN]

Best Practices for SP Administration:
1.       Don’t create too many Web applications. Its specified that 4 web applications are enough on a server.
a.       Intranet / Portal
b.      My sites
c.       Team sites
d.      Partner Access
2.       Don’t mess up with IIS settings of Central admin. SP likes to save the changes to Config DB, and Central admin works well as far as IIS Settings and Config settings match.
The only change which has to be done at IIS for Central Admin is SSL Settings.

@Html.Partial() Vs @Html.Action() - MVC Razor

In earlier post we have seen how to render different partial views (each using different model).
By which we displayed both Personal and Professional details of an employee as below:
Now lets look at other aspect.
Objective: I wanna display Professional details of an employee for both 2010 and 2011.
This means Using the same View and Same model but i need different data.
Lets see how this gonna be achieved.

Partial Views with Different Models - MVC Razor

In this post we will see:
1. How to use Different Partial views on a Master View.
2. How to attach models to different Partial Views.

Objective: I wanna create an MVC Razor application which will display both Personnel and Professional Details.


Cookie Capturing using HttpWebRequest

In this post we will see about how cookies can be captured using HttpWebRequest class.
When ever i say some thing about Cookie, first question people ask me is...
What if Cookies are disabled by Client or User ?
Ok! Let me ask you the same. Be genuine and don't search in Google now.
Tell me steps for how to disable the cookies in IE or Firefox?
I bet half of us don't remember how to disable them.
Being Technical persons, if we can't do that, how a client / user will do that.

If you still  stick to the same, let me tell you not only mine, even your web application won't work in his machine. That is for sure.


Custom Controller Factory & Structure Map - MVC Razor

Oww.... wait, why i have to go for Custom Controller Factory ? 
Error shown in earlier post "Default Controller Factory Vs Custom Controller Factory"  is lack of default constroctor. So, i will add one parameter-less constructor. That is it. Problem solved. :)

Sorry, now you have created a bigger problem. Let me show you how.
If you understood the article "Dependency Injection", you will observe the flexibility (Loosely coupled) we achieved because of that.


Default Controller Factory Vs Custom Controller Factory - MVC Razor

In order to have a better understanding of this, lets start this discussion with MVC Page life cycle.
Let's see step by step how it works.


Presence Control in Web app

We have seen many ways of implementing presence control in our web application.
The simplest of all of them is a combination of Images with Java script.
Lets see how to implement it.
Before going to actual implementation, we have to answer a few questions.
Why i need to use this one, i have my predefined reusable user controls for presence control ?
Ans: Yes, you can use them unless you answer below questions.
    i. Is it light weight?
    ii. Is it talking to your Messenger service or you want to take the overhead of communicating with exchange server?
    iii. Do you want to have complete control over the functionality and display?
    iv. Do you want to avoid the issues due to lack of complete information regarding references and bugs?
    v. Are you working on MVC Razor which cannot accommodate the heavy weight user controls designed in regular asp.net?


Digital Certificates & Logic Behind

Digital certificates are electronic credentials that are used to assert the online identities of individuals, computers, and other entities on a network. Digital certificates function similarly to identification cards such as passports and drivers licenses. They are issued by certification authorities (CAs) that must validate the identity of the certificate-holder both before the certificate is issued and when the certificate is used. Common uses include business scenarios requiring authentication, encryption, and digital signing.

Certificate Architecture:
A digital certificate binds a user, computer, or service’s identity to a public key by providing information about the subject of the certificate, the validity of the certificate, and applications and services that can use the certificate. Certificates issued in Windows Server 2003 and earlier PKIs are structured to meet these objectives based on standards established by the Public-Key Infrastructure (X.509) Working Group (PKIX) of the Internet Engineering Tasks Force (IETF). The following figure shows the contents of X.509 version 3

  • Subject. Provides the name of the computer, user, network device, or service that the CA issues the certificate to. The subject name is commonly represented by using an X.500 or Lightweight Directory Access Protocol (LDAP) format.
  • Serial Number. Provides a unique identifier for each certificate that a CA issues.
  • Issuer. Provides a distinguished name for the CA that issued the certificate. The issuer name is commonly represented by using an X.500 or LDAP format.
  • Valid From. Provides the date and time when the certificate becomes valid.
  • Valid To. Provides the date and time when the certificate is no longer considered valid.
    • The date when an application or service evaluates the certificate must fall between the Valid From and Valid To fields of the certificate for the certificate to be considered valid.
  • Public Key. Contains the public key of the key pair that is associated with the certificate.

WCF - Implementing Message Level Security

Lets start this topic with a comparison between Transport and Message level security.

Transport Level Security
Message Level Security
Scenarios when we should be using one of them
When there are no intermediate systems in between this is the best methodology.  
If it’s an intranet type of solution this is most recommended methodology.
When there are intermediate systems like one more WCF service through which message is routed then message security is the way to go.
Does not need any extra coding as protocol inherent security is used.
Performance is better as we can use hardware accelerators to enhance performance.
There is lot of interoperability support and communicating clients do not need to understand WS security as it’s built in the protocol itself.
Does not need any extra coding as protocol inherent security is used.
Performance is better as we can use hardware accelerators to enhance performance.
There is lot of interoperability support and communicating clients do not need to understand WS security as it’s built in the protocol itself.
As it’s a protocol implemented security so it works only point to point.
As security is dependent on protocol it has limited security support and is bounded to the protocol security limitations.

Needs application refactoring to implement security.
As every message is encrypted and signed there are performance issues.
Does not support interoperability with old ASMX webservices/

So, both Transport and Message level security have their pros and cons.
But, in real time internet scenarios, message level security will be the best pick.

Message Level Security:
Message security uses the WS-Security specification to secure messages. The specification describes enhancements to SOAP messaging to ensure confidentiality, integrity, and authentication at the SOAP message level (instead of the transport level).


Builder Pattern

Developers have observed that, composing a system using inheritance makes it too rigid.
Creational Pattern is a way to break that tight coupling by abstract out the object creation.
The Creational patterns aim to separate a system from how its objects are created, composed, and represented. They increase the system's flexibility in terms of the what, who, how, and when of object creation. Creational patterns encapsulate the knowledge about which classes a system uses, but they hide the details of how the instances of these classes are created and put together.

Lets start this pattern with a hot snac. "Pizzaaaa . . . "
 Even though i am a non vegetarian, i love "Veggi Delight" than any other flavor. I know its very hard to discuss a design pattern keeping this picture in front of you. But lets stick to topic.
There are lot of variations in Pizza, different sizes, there are different types of bread doughs(base), different types of sauces , different types of toppings that can be used to prepare a pizza.
Now let's cook a pizza in c# mode.


WCF - Implementing Transport Security using SSL

Security :  Security ensures that the information does not go in wrong hands when it travels from the sender to the receiver. This feature ensures that the receiver of the message gets the same information that the sender sends without any data tampering.

There are two types of security provisions in WCF.
1. Transport Level
2. Message Level

Transport level security happens at the channel level. Transport level security is the easiest to implement as it happens at the communication level. WCF uses transport protocols like TCP, HTTP, MSMQ etc and every of these protocols have their own security mechanisms. One of the common implementation of transport level security is HTTPS. HTTPS is implemented over HTTP protocols with SSL providing the security mechanism. No coding change is required it’s more of using the existing security mechanism provided by the protocol.

Message level security is implemented with message data itself. Due to this it is independent of the protocol. Some of the common ways of implementing message level security is by encrypting data using some standard encryption algorithm.
 In this post we will see how to implement transport security on http protocol using SSL certificates.


MVC Razor - Custom Html Helper Calsses.

We have seen several examples on MVC Razor in earlier posts. In every code module we demonstrated until now, @Html.SomeFunction() made our lifes easy with MVC. These are nothing but Html Helper classes.

HTML Helper classes:
An HTML Helper is just a method that returns a string. The string can represent any type of content that you want. For example, you can use HTML Helpers to render standard HTML tags like HTML <input> and <img> tags. You also can use HTML Helpers to render more complex content such as a tab strip or an HTML table of database data.
The ASP.NET MVC framework includes the following set of standard HTML Helpers (this is not a complete list):
  • Html.ActionLink()
  • Html.BeginForm()
  • Html.CheckBox()
  • Html.DropDownList()
  • Html.EndForm()
  • Html.Hidden()
  • Html.ListBox()
  • Html.Password()
  • Html.RadioButton()
  • Html.TextArea()
  • Html.TextBox()
We can even write our own helper classes to perform common & complex tasks with ease.
Immediately a question pops up into your mind.
Why Helper classes, why not a DLL where i can use through out the project?
Yes, you can do that, but with helper class you can do better. Let me explain you. If you use the function as DLL, you might use it in model or Controller. Thus you are making that functionality specific to that controller or Model or may be view. But if you use it as a helper class, it can be used just like any html helper class through out the project. In future if you changed the helper method name, it requires no code change in Controller or Model. Search the old method name and replace it with new method name just like any html tag.
Enough with theory, lets jump in to practice.

Dependency Injection (DI / IOC)

"Loosely Coupled" is the one of the basic qualities of a good design.
Let me justify that first.
If you have 2 choices:
1. A task which has lot of dependencies on others.
2. A task which have Minimum number of dependencies.
Which one will be easier. Obviously its #2.
So, less dependencies means more loosely coupled and better the design it will be.

I believe 80% of world population know below Guy.
He is Harry potter with a Magic Wand (stick in his hand), which he will be using to cast the spell.
Now lets watch the potter's magic in a console application using c#.


MVC Razor - Using Sections & Partial Views

Being a web developer, dealing with page layouts and striving for optimized code will be our D2D activity.
In typical Asp.Net scenario we use Master Pages and User controls for these two tasks respectively.
So, today we will see how we handle these things in MVC Razor 3.0.
There are no Master Pages and User controls in MVC.
You know why? Comparatively they are complex to develop. :)

In order to implement both Sections and Partial Views, i will take a task of displaying a small Menu which will redirect me to 2 different pages in my application.

There are 3 ways of doing it.
1. Hard coding the menu on Master Page.
2. Rendering the menu based on Page.
3. Using Partial Views.


Abstract Factory Pattern

Let me begin with a proverb, "Change is Inevitable & Good." If you are not ready to adapt to the change, you will not survive. Same case applies to our software as well.

Like many of us, I am a big time Fan of PC Games. So, i thought of interpreting the usage and implementation of a pattern on the same lines.

I love "Company of Heroes" game. It has awesome UI and whole lot of Gadgets and i had great time playing it.
Look at UI once.
If you closely observe, there are Cars, Tankers, and Flights. In fact there are different types of each kind.
Now, lets say i have Scenario, where i designed this kind of a game (Lets Assume ;))
I have to handle all these kinds of vehicles say, Tankers. Tomorrow, i got a complain that, the tankers are not efficiently attacking the Aircrafts. Now, i have to categorize Tankers into 2 different types.
1. Ground Tankers.
2. Air Tankers
Tomorrow, there may come another type. And my code should be open to implement any new kind of vehicle that may creep into scope in future.

So, in order to handle families of related and dependent objects, we use "Abstract Factory Pattern".

Coming to Game, when the user starts the game, i have to give him the following vehicles to start off.
1. Soldiers Car
2. Officers Car
3. Passenger Aircraft
4. Soldiers Aircraft
5. Land Tanker
6. Air Tanker.


Session Sharing

Scenario: In one of the projects, i got a situation where Half of the application is Migrated to MVC and other half is in Old 3 tier architecture.
Now, i have to host both the applications, and need to switch the context from one app to other with out intervening the user actions. We use to save all the user context and other information in sessions to maintain the state.
Bottom line is "I have to share the sessions between two different virtual directories in order to maintain the continuity of the application."

Resolution : After verifying couple of approaches, we found that Session can be shared by using a combination of  Custom Http Module  and SQL State management. We will see how to do that step by step.
Before going to Actual implementation, we need to see what are the tables used for SQL state management and their significance, thus we can understand how to make them work as we require.

Sql Server State Management: We know what are the different steps to do in order to configure SQL State management. Lets Open and see ASPState database. You will have 2 data tables.
             #1. ASPStateTempApplications - This used to create a unique Appid for each in-comming application request based on the unique application name/ application ID.
            #2. ASPStateTempSessions - This is used to create unique sessions for each user, correlated with each applicationid created in #1 table.

Logic: Now, from #1, you might have observed if you have 2 different applications, there will be 2 different application ids that will be created in table #1. So our duty is to restrict both the applications to create a single Appid, and this is acheived by using custom HTTP Module.


How to create a Google's Doodle.

In this post we will see the basic development secret of most of the Google's Doodles.
Try rotating your cursor around the monster image.
That is nothing but a combination of Images , style sheets, and JQuery.

We will see step by step how to develop one.

Step 1: Get a Sprite Image. (Not a soft drink).
It is a technology of displaying multiple images using a single image. See the below image for example.
This is a single image file containing 18 different images. I am going to use only first nine on the left.



We know Service and Client interact through EndPoints in WCF.

So clients send their request to the service and the service will receive them Via Endpoints. Thus the request will be processed.
Now, what if Service is down by the time client sends a request.
This is where Message Queuing (MSMQ) comes to picture to provide Message reliability. 

This article will describe how to Create / Test one, by providing step by step description. Before we start anything, go to Programs in control panel, open "Turn on/off windows componenets". There enable all the services pertaining to MSMQ. Also ensure that all the services pertaing to Message Queuing are started in services section.

Step 1: Objective
            I want to write a simple service (File Writer) which accepts user info from client and will write a log to a text file. And implement the message reliability using MSMQ.
Step 2: Create Service Contract.
           I defined a Interface for the file writer service. This interface is called "Contract", which will define the basic skeleton of the service.


WCF Key Points

#1. In WCF Protocol Choice, Message Format, Encoding Format, Hosting Environment, Process Allocation etc, almost everything is configurable and hence called as loosely coupled.

#2. A WSDL (Web Service Description Language) file will define the following details of a WCF service.
  • Provides the information about the service contract and operations available.
  • Provides the information about all the end points exposed by the WCF service.
  •  Provides the information about the messages and types that can be exchanged between the client and the WCF service.
  •  WSDL also provides any information about the policies used.
 #3. Below are the advantages of defining the service contract at Interface level:
  • Defining service contracts using interfaces, removes coupling to service implementation. Later the implementation can be changed at will without affecting the clients.
  • Defining service contracts using interfaces, also allows a service to implement more than 1 contract. 


View Controling in MVC.

We all know how View, Model, Controller communicates with each other.

Everything a View expects is a Model object sent by controller. So, nothing else can effect the View.
So, what if you have a Grid View which has multiple columns and will display them based on certain roles.Keep in mind that View didn't support any CS files.

There are 2 ways of doing it.
1. Create separate Views and invoke them from controller based on the role.
2. Controlling the View by making Visibility matrix as a part of Model.(View Controling)

I believe APPROACH1 is not so appealing, as both the development cost and maintenance cost will be more with it.

So, i have chosen Approach2.


Showing the views in Modal Popup in MVC

Showing a Modal popup using Jquery is nothing new.
The concept i like to stress on is how to display a View in that Popup.

Step 1: I have created a  View (Popup View). Make sure that you haven't selected any Layout page (Master), as we will b displaying it in the Popup.
Just for time being i embed some text in Popup View.
Step 2: Here in order to have ease of development, i have added a Telerik reference and using a telerik window. Place the below code for embedding the telerik window for accommodating your view.

@(Html.Telerik().Window() // Add Telerik.web.mvc.dll in references
    .Title("PopUp View")

Step 3: Add the required script and CSS files to support the JQuery modal popup functionality.


LINQ to SQL changes in .NET 4.0

Change list


  • Query plans are reused more often by specifically defining text parameter lengths (when connecting to SQL 2005 or later)
  • Identity cache lookups for primary key with single result now includes query.Where(predicate).Single/SingleOrDefault/First/FirstOrDefault
  • Reduced query execution overhead when DataLoadOptions specified (cache lookup considers DataLoadOptions value equivalency)


  • ITable<T> interface for additional mocking possibilities
  • Contains with enums automatically casts to int or string depending on column type
  • Associations can now specify non-primary-key columns on the other end of the association for updates
  • Support list initialization syntax for queries
  • LinqDataSource now supports inherited entities
  • LinqDataSource support for ASP.NET query extenders added

Page Controller Vs Front Controller Pattern

How do you best structure the controller for moderate / complex Web applications so that you can achieve reuse and flexibility while avoiding code duplication?

MVC has been a tried and tested method of structuring your applications for a long time. Generally MVC mainly focuses on separating model and view and less attention on the controller. Specially in rich client applications the view and the controller tends to lie close together. But in web applications this separation is more critical since the view is essentially happening at client side (browser) while the most of the controller sits in the server side.
There are 2 basic ways of structuring the 'C' of the MVC, i.e Controller. The 2 basic methods are the Page Controller method and the Front Controller method.

MVC Application Execution

The following table lists the stages of execution for an MVC Web project.
The respective class names will redirect to MSDN, for further reference.

Stage Details
Receive first request for the application In the Global.asax file, Route objects are added to the RouteTable object.
Perform routing The UrlRoutingModule module uses the first matching Route object in the RouteTable collection to create the RouteData object, which it then uses to create a RequestContext object.
Create MVC request handler The MvcRouteHandler object creates an instance of the MvcHandler class and passes the RequestContext instance to the handler.
Create controller The MvcHandler object uses the RequestContext instance to identify the IControllerFactory object (typically an instance of the DefaultControllerFactory class) to create the controller instance with.
Execute controller The MvcHandler instance calls the controller's Execute method.
Invoke action For controllers that inherit from the ControllerBase class, the ControllerActionInvoker object that is associated with the controller determines which action method of the controller class to call, and then calls that method.
Execute result The action method receives user input, prepares the appropriate response data, and then executes the result by returning a result type. The built-in result types that can be executed include the following: ViewResult (which renders a view and is the most-often used result type), RedirectToRouteResult, RedirectResult, ContentResult, JsonResult, FileResult, and EmptyResult.

Is it helpful for you? Kindly let me know your comments / Questions.


Features of MVC 3.0

# Extensible Scaffolding with MvcScaffold integration
     The new Scaffolding system makes it easier to pick up and start using productively if you’re entirely new to the framework, and to automate common development tasks if you’re experienced and already know what you’re doing.
     This gave a provision of using and even modifying the scaffold template as per your requirements. This topic is being discussed in detail in my other posts.

# HTML 5 Project Templates
     The new project template supports HTML5 template, which have far better performance and compatibility advantages compared with earlier versions of rendering formats. The advantages of HTML5 were discussed separately in my next post.


Using Scaffold Package to generate your MVC project.

This is a basic topic discussing about how existing scaffold template works while creating a new MVC Views in Razor.

When you try to create a View, you will get a window giving you all the options supported by Scaffolding. Like one showed in left.

All the options below View Engine drop-down will be enabled after you check "Create a strongly-typed View", where you have to select a Model. Thus showing Scaffolding is Model Dependant.

Once you select a model, Scaffold template drop down will be enabled, giving you options
1. Empty - Creates a Empty Controller.
2. CURD - Creates a model supporting all the CURD operations.


MVC Remote Validation

ASP.NET MVC 3 supports the new RemoteAttribute class that enables you to take advantage of the jQuery Validation plug-in's remote validator support. This enables the client-side validation library to automatically call a custom method that you define on the server in order to perform validation logic that can only be done server-side.

Step1: The appSettings element contains the following keys to enable client validation and enable unobtrusive JavaScript validation.

Step2: Define the remote attribute to the prop in model


MVC 3.0 Scaffolding Basics

MvcScaffolding : The term “Scaffolding” is used by many software technologies to mean “quickly generating a basic outline of your software that you can then edit and customize”. It saves you from the trauma of looking at a blank page and having no idea where to start!
    The new Scaffolding system makes it easier to pick up and start using productively if you’re entirely new to the framework, and to automate common development tasks if you’re experienced and already know what you’re doing.
    This is supported by new NuGet scaffolding package called MvcScaffolding. If you installed MVC 3 , you can find "NuGet" as one of your programs in Control panel. 

If your work involves repeatedly creating similar classes or files of some sort, because you can create custom scaffolders that output test fixtures, deployment scripts, or whatever else you need. Everyone on your team can use your custom scaffolders, too.
    We will see how to automate the desired code snippets using Scaffold in next posts. 

Is it helpful for you? Kindly let me know your comments / Questions.


About Author.

Being in IT from last 11 years, i learned one thing.
"More you share, More you learn".

Hope this help me and all the readers as well.

"This Blog is not about what i know, its about what i learned."

"It takes less time to make it right, than explaining why i did it Wrong."
                                                                                 Pratap Reddy P