Hashtable in C#

Hashtable objects are quite similar to an ArrayList object except that it is not required to use a numerical index. Instead, we can use a texture key that can be

Benefits of Hashtable

  1. Insert Elements: you can add as many pairs of key/value elements as required. You do not have to specify the size ahead of time.
  2. Non-numeric index: you can use text, number and dates as your key (index).
  3. Faster Lookup: the hashtable collection caters very fast lookup of elements.
  4. Flexibility when Removing elements: you can remove any element from an Arraylist very easily

Limitations of Hashtable

  • Key must be unique: The Hashtable stipulates the key uniqueness requirement that is very cumbersome to manipulate.
  • No useful sorting: Sorting is not done by using keys or values. The items in the Hashtable are sorted internally to make it easy to find objects very quickly.
  • Performance: Although the lookup is very quick in a Hashtable, the CLR must do quite a lot of work to maintain them that is very resource-intensive.

Hashtable obj = new Hashtable();
Obj[“in”] = “india”;
Obj[“en”] = “England”;
Obj[“us”] = “USA”;

Obj[Convert.ToDateTime(“21/12/2012”)] = “The Judgment day”;

string Country = Convert.ToString(obj[“in”]);

ArrayList in C#

Benefits of Array List

  1. Insert Elements: An Array List starts with a collection containing no elements. You can add them in any position as you choose them.
  2. Automatic Resizing: you do not need to specify the array size; as you add elements, the array automatically ensures there is enough memory for the array.
  3. Flexibility When Removing Elements: you can remove any element from an Array list very easily.

Limitations of Array List

The flexibility of Array List comes at a cost of performance. Since memory allocation is a very expensive business, the fixed number of elements of the simple array
makes it much faster to work with.


ArrayList obj = new ArrayList();



Abstract Class features

  • class members that are incomplete and must be implemented in a derived class.
  • An abstract class cannot be instantiated.
  • The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share.
  • Abstract classes may also define abstract methods.

public abstract class A
public abstract void DoWork(int i);

  • Derived classes of the abstract class must implement all abstract methods.
  • When an abstract class inherits a virtual method from a base class, the abstract class can override the virtual method with an abstract method.
  • We can also inherit normal method in the abstract class and declare it as abstract, though it compiles it shows warning that abstract method must be virtual.

public class D
public virtual void DoWork(int i)
// Original implementation.

public abstract class E : D
public abstract override void DoWork(int i);

public class F : E
public override void DoWork(int i)
// New implementation.

  • If a virtual method is declared abstract, it is still virtual to any class inheriting from the abstract class.
  • A class inheriting an abstract method cannot access the original implementation of the method.
  • override keyword  should be used while defining abstract method in derived class.

Ref:- http://msdn.microsoft.com/en-us/library/yd3z1377.aspx

Routing in MVC

ASP.MVC routing module is responsible for handling incoming browser request (http request) and map to MVC controller action method.

Routing Module

  • When first time request come to the MVC application, it check for ‘Route Table’ since it is first time request to the application it fills the ‘Route Table‘.
  • Once the ‘Route Table’ is updated then request goes to ‘URL Routing Module’. If the incoming request not first one then it directly goes to ‘URL Routing Module’.
  • And this ‘Routing table’ is created at Application_Start event.

“Default”,                                              // Route name
“{controller}/{action}/{id}”,                           // URL with parameters
new { controller = “Home”, action = “Index”, id = “” }  // Parameter defaults

Name: Default
URL Pattern: {controller}/{action}/{id}
Values: new { controller = “Home”, action = “Index”, id = “” }

  • Depending on the URL sent “UrlRoutingModule” searches the route table to create “RouteData” object which has the details of which controller and action to invoke.
  • From ‘URLRoutingModule’ it goes to ‘MVCHandler’ as RequestContext object, the ‘RouteData’ object is used as RequestContext object.
  • In ‘MVCHandler‘ Controller instance will be created and it calls the ‘Execute‘ method of the controller class.
  • Once ‘ActionMethod‘ executed result will be sent back to view as response object.

Routing module is responsible till it calls the matching ActionMethod.


Enable client side validation

By default client side scripting disabled by default. To enable Client side scripting in MVC you need to follow the below 2 steps.

Step 1:

To Enable Client Side validation in web.config

<add key=”ClientValidationEnabled” value=”true”/>
<add key=”UnobtrusiveJavaScriptEnabled” value=”true”/>

Step 2:

– Include reference of javascript files in the masterpage
– Avoid adding reference in each and every View page

Add the following references in Masterpage

<script src=”~/Scripts/jquery-1.8.2.min.js” type=”text/javascript”></script>
<script src=”~/Scripts/jquery.validate.min.js” type=”text/javascript”></script>
<script src=”~/Scripts/jquery.validate.unobtrusive.min.js” type=”text/javascript”></script>

The order of adding reference are also important.

Now we can able to validate in client side by avoiding round trip to server side.

Filters in MVC

Using filters you can inject you business logic or business rules into the Action Methods or to entire controller. Business rules can be applied before and after the action method gets executed.

Some of your action filters 
   1) OutputCache

– It will catch the out put of action method up to certain time period.
CacheProfiler > Define the cacheProfiler in web.config  and call it in controller action method. So that when you change it in later you no need to redeploye the code.

   2) HandleError

– Handles the error if any error occurs while executing the action method.
– No need to add separately to each action method or Controller since HandleErrorAttribute is added globally in Global.asax page.
<customErrors mode=”On”/> in root web.config of root application.
– we can also create common Exception Controller and specify the error code and the controller to redirect under customErrors of web.config file.
   3) Authorize

  • Allow/Restrict  particular user(or)roles.
  • By default all action methods are accessible all the anonymous and authenticated users in Mvc.
  • To allow only authenticated to access the Action Method use [Authorize] attribute.

   4) ChildActionOnly

ChildActionMethod Invoked by making child request from view using ‘Action()’, ‘RenderAction()’ html helper.
– When the Action Method is decorated with [ChildActionOnly] we can’t access it through URL. If you try to access it will throw you ‘ChildActionMethod can be accessible only through the child request’
ChildActionOnly typically associated with partial view but this is not compulsory.
– [NonAction] different from [ChildActionOnly], [NonAction] attribute can not be called through URL or through ‘Action()’, ‘RenderAction()’ html helper.
– Can cache portion of view through ChildActionMethod.
5) RequireHttps

– Force the actionmethod to execute and display it  through ssl layer
– So that data that is transmitted are secure.

you can create your own custom filters. In MVC 4.0 you have 4 types of custom filters

  1. Authorization Filter – Implements IAuthorizationFilter interface.
  2. Action Filter – Implements the IActionFilter interface.
  3. Result Filter – Implements the IResultFilter interface.
  4. Exception Filter – Implements the IExceptionFilter interface.

Filters will be executed in above order. If you want to control the order in which filters of same type are executed using filter’s Order property. System.Web.Mvc.FilterAttribute  is the base class for all the Filter actions, when ever you implement custom filter attribute you should inherit this base class and any one or more above mention filters.
ActionFilterAttribute this base class inherits IAction and IResult interfaces

The base ActionFilterAttribute class has the following methods that you can override:
OnActionExecuting – This method is called before a controller action is executed.
• OnActionExecuted – This method is called after a controller action is executed.
OnResultExecuting – This method is called before a controller action result is executed.
OnResultExecuted – This method is called after a controller action result is executed.

For More Refer here (Click Here)

Different ways of Parameter can pass in Controller

When you submit the data to action method of controller it can be done through the parameter. There are 4 different ways of parameter you can pass

1) Request object
2) FormCollection
3) using predefined datatypes
4) Custom datatype

When ever request object submit the data([HttpPost]) it will check with the action method’s parameter type based on that it will pass the parameter

1) Form Collection

It holds the value as key/value pair
While send the data back to the controller(Request object) we can send as FormCollection object.
If you specify as FormCollection type in action method signature you will get the user submitted value as key/value pair
Key contains control name and value will hold the value of the control.

public ActionResult SubmitFormWithFormCollection(FormCollection formCollection)
foreach (string _formData in formCollection)


return View();

2) Request Object

It holds the values as Name-Value pairs.
While send the data back to the controller(Request object) we can submit the form as Post method.
If you are not specify action method signature and using Request[“ControlName”] you can get the value.

public ActionResult SubmitFormWithRequestObject(FormCollection formCollection)
int i=convert.ToInt32(Request[“txtAge”].toString())

return View();

3) Predefined parameter

Name of the control in View must be the variable name of parameter with data type.
We can define the parameter with the corresponding data type (int, string,…) that control will get as input.
For each control we will pass the separate parameter in the action method.

public ActionResult SubmitFormWithSimpleParameter(string txtName, string txtAddress, int txtAge, date txtDOB)
// Do some codes;

return View();

4) Custom Parameter

Custom data type can be passed as parameter
In the action method we passed model as parameter

public ActionResult SubmitFormWithSimpleParameter(PersonalInfo info)
// Do some codes;

return View();

About Nuget

In Visual studio to add any reference in our project we will use ‘Add Reference Dialogue’, but in last few years apart from .net assemblies, we are started incorporate lots of 3rd party libraries(.NET open source libraries) into our projects.If you manually add any .NET open source assemblies some time it takes too much effort to make it work with the project. We can avoid this manual configuration through Nuget Packages available for VS2010 and from VS2012 this feature is comes by default during installation.

Nuget is type of Open source Package management system and it is a huge repository. Using Nuget we can include required assembly in to out application. we can make use of Package Manager Console window in VS to install any external assembly that is available in Nuget.

Security issue in MVC delete using hyperlink

In Stephen Walther post, he mentioned security issue in deleting the record through GET request. In MVC hyperlink will use GET request to delete a record, so any one can able to access the record just by passing the id of record.



In the above example we are using GET request to delete the employee record by clicking the corresponding delete hyperlink of the employee. So the value that you are passing is known and any one who knows the delete URL can have possibility of deleting the record which is not advisable.

Stephen Walther provide solution to bypass this issue is using client side scripting (AJAX(or) JQUERY, JavaScript…)

System.Data.Entity.Infrastructure missing Namespace

install the EntityFramework NuGet package which will setup everything for you .

Go to

menu “Tools”-> Library Package Manager –>  Package Manger Console
and typing there:
PM> install-package EntityFramework

That’s it. All errors disappeared.

%d bloggers like this: