Saturday, 13 April 2013

What's New in C# 4.0


Below are new features introduced in c#4.0 with example:
1.       Dynamic Lookup: It resolves types in a program at runtime. It’s very useful in below scenarios:
a.       Office Automation or COM Interop scenarios.
b.      Consuming types written in dynamic languages (like IronPython, IronRuby…)
c.       Call Reflection : currently we use Reflection to instantiate a class when a types is not known at compile type.
Example:


2.       Named and Optional Parameters: Named arguments enable you to specify an argument for a particular parameter by associating the argument with the parameter's name rather than with the parameter's position in the parameter list. Optional Parameters enable you to omit arguments for some parameters. Both techniques can be used with methods, indexers, constructors, and delegates.
Example:

3.       Covariance and Contravariance: covariance and contravariance refers to the ordering of types from narrower to wider and their interchange ability or equivalence in certain situations (such as parameters, generics, and return types). (Source- Wikipedia).
Types that are
·         covariant: converting from a specialized type (Cats) to a more general type (Animals): Every cat is an animal.
·         contravariant: converting from a general type (Shapes) to a more specialized type (Rectangles): Is this shape a rectangle?
Example:
Covariance:

If you see above example here, you will find two interesting point here inside Main method. If you try to compile this program in .Net Framework 3.5 or less you will get error in second line of Main method saying “An explicit conversation exist (are you  missing a cast?)”.
IEnumerable<Person> persons = new List<Employee>();
It’s really surprising, If a base class called Person can hold the object of his child class called Employee, then why this is not applicable in with group of objects. SO this is where C#4.0 introduced a feature called Covariance. SO if you compile it under C# 4.0 compiler you will not get any error.
So the result here is: Covariance preserves assignment compatibility.
ContraVariance:

In above example, I have an overloaded method called PrintPerson. If you compile above code in C# 3.5 or less version you will get error on last line of code.
IEnumerable<Employee> empList = new List<Employee>();
PrintPerson(empList);
But in C# 4.0 or later version it works fine. SO this is where C#4.0 introduced a feature called Contravariance.

4.       COM Interop Enhancement.
In C# 4.0, calling COM object become more easier. For an example let’s talk about Microsoft.Office.Interop.Word. We will write a code to open a word file in C# 3.5 and C#4.0 and then we will see what’s enhancements is done in C#4.0.


If you see the above code here, it says itself about the enhancement of COM Interop library. Writing code become more easier than earlier version of C#.

Thank You for reading. Feel free to give your feedback.

Sunday, 3 March 2013

All about JsonObject.


What is JSONOBJECT?
A JSONObject is an unordered collection of name/value pairs. The JSON format is often used for serializing and transmitting structured data over a network connection. It is used primarily to transmit data between a server and web application, serving as an alternative to XML.

for example: 
Below example shows the JSON representation for list of cities in india:
{"Cities":[
                                {"name":"Select City", "value":"-1"},
                                {"name":"Bangalore", "value":"Bangalore"},
                                {"name":"Chennai","value":"Chennai"},
                                {"name":"Goa","value":"Goa"},
                                {"name":"Delhi","value":"Delhi"}
                ]
}

And the xml format for this will be
<Cities>
                <city>
<name>Select City</name>
<value> -1</value>
</city>
<city>
<name> Bangalore </name>
<value> Bangalore </value>
</city>
<city>
<name> Chennai </name>
<value> Chennai </value>
</city>
<city>
<name>Goa</name>
<value> Goa </value>
</city>
<city>
<name>Delhi </name>
<value> Delhi</value>
</city>
</Cities >

Another Example of JSON format data is:
{
"Person":[
                {
                                "firstName": "Binod", "lastName": "Mahto",
                                 "address":
                                  {"city": "Bangalore", "state": "Karnataka", "country": "India"},
                                  "email":
                                  {"provider": "Gmail","id": "xyz@gmail.com"}
}
                ]
};
And the xml format for above data is:
<person>
  <firstName> Binod </firstName>
  <lastName> Mahto </lastName>
  <address>
      <city>Bangalore</city>
     <state>Karnataka</state>
     <Country>India</ Country >
  </address>
  <Email>
                    <provider>Gmail</provider>
                    <id>xyz@gmail.com</id>
  </ Email >
</person>

Advantages of using JSON:
  • ·         It is much simpler than XML.
  • ·         No extra tags or attributes to represent data.
  • ·         Language independent.
  • ·         Very lightweight text-data
  • ·         Because of simplicity of converting xml to JSON, it is more adoptable.

Disadvantages of using JSON:
  • ·         Lack of display capability as it’s not a mark-up language.
  • ·         JSON does not have a <[CDATA[]]> feature, so it is not well suited to act as a carrier of sounds or images or other large binary payloads.
  • ·         JSON is optimized for data. Besides, delivering executable programs in a data-interchange system could introduce dangerous security problems.

Now let’s see how to consume/use JSON object in HTML.
HTML code:
<!DOCTYPE html>
<html>
<body>
<h2>JSON Object Example</h2>
<p>
Name: <span id="jname"></span><br />
Address: <span id="jadd"></span><br />
Contact:<span id="jemail"></span><br />
</p>
<script>
var JSONObject= {
"Person":[
                {
                                "firstName": "Binod", "lastName": "Mahto",
                                 "address":
                                  {
                                                "city": "Bangalore", "state": "Karnataka", "country": "India"
                                },
                                  "email":
                                {
                                                "Provider": "Gmail","id": "xyz@gmail.com"
                                }
                }
                ]
};
document.getElementById("jname").innerHTML= JSONObject.Person[0].firstName +" "+ JSONObject.Person[0].lastName
document.getElementById("jadd").innerHTML=JSONObject.Person[0].address.city +", "+JSONObject.Person[0].address.state+", "+JSONObject.Person[0].address.country
document.getElementById("jemail").innerHTML=JSONObject.Person[0].email.id
</script>
</body>

Here I have created a JSON Object in JavaScript which contains a person information. Next I am reading the values from the JSON Object and displaying it to the HTML Page. In html I have three span html tag with id where values are getting assigned through JavaScript.
Below is the screen shot of above html code:
Now let me show you an example of using JSONObject in asp.net mvc application. In below example I have a dropdown which shows list of countries. 
Below is the code for my controller class.


Here in above code I have method called GetCountries in controller which return list of countries. Now in view we will consume this JSONObject using Jquery.
Below is the code for View:

consumption of JSONObject using Jquery call.
and below is the output :

That's all. Now you are ready to play with JSONObject. 

Thank you for the reading. Feel free to give your feedback/suggestion.


Reference:

Saturday, 23 February 2013

ASP.NET MVC 3 Dependency Injection using Unity.MVC3


ASP.NET MVC 3 Dependency Injection
Dependency injection (DI) is a design pattern and it is based on separating component behaviour from dependency resolution without object intervention. In other words we can say it removes the tightly coupled dependency between objects and components in collaboration model where there are contributors and consumers.
To know more about Dependency Injection Pattern, Please follow below links:
http://msdn.microsoft.com/en-us/magazine/cc163739.aspx
Dependency Injection is a particular implementation of Inversion of Control (IoC) principle, which says, An Object should not create other object in which they rely. It means the consumer object receives his dependencies inside constructor properties or arguments.
The advantages of using Dependency Injection pattern and Inversion of Control are:
·         Reduces class coupling
·         Increases code reusing
·         Improves code maintainability
·         Improves application testing

In ASP.Net MVC framework we need Dependency Injection to remove dependency between consumer (say controller) and contributors (service/business layer object).

Now let’s move on Implementation of Dependency Injection in ASP.Net MVC 3. Here we will talk about using Dependency Injection inside an MVC controller. We can also use Dependency Injection inside MVC View and MVC Action Filter.

I assume, you already have the knowledge regarding ASP.Net MVC3.
Before starting first thing we have to do is, IoC container which basically create dependency resolver per HTTP request. And I feel let’s not do that as there are lot many open sources available which provides library to do this like Ninject, Unity and so on.

Here I am going to use Unity.MVC3 and will show you, How you can use Dependency Injection inside controller using Unity.MVC3 IoC library. We will discuss to perform CRUD operation

Introduction of Unity.MVC3:
 A library that allows simple Integration of Microsoft's Unity IoC container with ASP.NET MVC 3. This project includes a bespoke Dependency Resolver that creates a child container per HTTP request and disposes of all registered IDisposable instances at the end of the request.

How to get this library: To include this on project, Right click on your MVC3 app solution in visual studio and click on “Manage NuGet Packages” and search of Unity (refer below pic).

Here you have select Unity.MVC3 (Highlighted on) click to install. Once you installed this you can see below highlighted (in pic) dlls reference in your project:

Next step we will create a service(with interface and implementation)  which is basically responsible to communicate with DB.

And then we create the actual service class which perform all my CRUD operation to create, delete, edit and modify user details to the DB.

Now we will create a controller factory class for Unity which implements IControllerFactory interface, extending CreateController and ReleaseController methods to work with Unity. This factory will create the instances of the controllers that work with Dependency Injection.
Note:
A controller factory is an implementation of the IControllerFactory interface, which is responsible both for locating a controller type and for instantiating an instance of that controller type.
The following implementation of CreateController finds the controller by name inside the Unity container and returns an instance if it was found. Otherwise, it delegates the creation of the controller to an inner factory. One of the advantages of this logic is that controllers can be registered by name.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Microsoft.Practices.Unity;

namespace MyMVC3WebApp.Factories
{
    public class UnityControllerFactory: IControllerFactory
    {
        private IUnityContainer unityContainer;
        private IControllerFactory defaultInnerFactory;

        public UnityControllerFactory(IUnityContainer container)
            : this(container, new DefaultControllerFactory())
        {
        }

        protected UnityControllerFactory(IUnityContainer container, IControllerFactory innerFactory)
        {
            unityContainer = container;
            defaultInnerFactory = innerFactory;
        }

        public IController CreateController(System.Web.Routing.RequestContext requestContext, string controllerName)
        {
            try
            {
                return unityContainer.Resolve<IController>(controllerName);
            }
            catch (Exception ex)
            {
                return defaultInnerFactory.CreateController(requestContext, controllerName);
            }
        }

        public System.Web.SessionState.SessionStateBehavior GetControllerSessionBehavior(System.Web.Routing.RequestContext requestContext, string controllerName)
        {
            return System.Web.SessionState.SessionStateBehavior.Default;
        }

        public void ReleaseController(IController controller)
        {
            unityContainer.Teardown(controller);
        }
    }
}


Now next steps we have to register this Unity Library. While installing Unity.MVC3 you have observed, there is class called Bootstrapper.cs is been added to the solution including above mentioned dlls (shown in below pic, highlighted one).

Now next step we have to register our service Type inside BuilUnityController method present under Bootstrapper class.

Highlighted code in above pic is to register our service.

And the last step we have to do is, call the Initialize method of the Bootstrapper class from the global.asax.cs file. Shown in below pic

Now we have done with the create part and will see how I am using this inside my controller.
      
Now if you see, controller receives the business object through constructor and use this to perform CRUD operation. So here our controller is no more depended on creation object of service class on which it relays.

Please feel free to give your suggestion/feedback.

Thank You for reading this.  

References:

Saturday, 15 December 2012

Avoid SQL Injection in dynamic SQL query inside stored procedure.

Frnds,

I had a requirement where I had to write a stored procedure which will give the data back to the user. Looks very simple but the interesting part was that, Inside SP the table name was coming as a parameter with other parameters.
I went ahead created stored procedure something like shown below here:


Create PROC [sp_demo_injection02]
(
@tablename varchar(50),
@username varchar(50),
@lastname varchar (50)
)
AS
  declare @cmd nvarchar(max)
  declare @parameters nvarchar(max)
  set @cmd = N'SELECT * FROM '+ @tablename +' WHERE username = '+''''+ @username+''''
  set @cmd = @cmd+' and lastname= '+''''+@lastname+''''
  --print @cmd
  Exec @cmd
go

In runtime sql query for this
exec [sp_demo_injection02] 'tblUser','bkm','mahto'
generated like
SELECT * FROM tblUser WHERE username = 'bkm' and lastname= 'mahto'

but when I run the same SP with below parameter I was shocked:
[sp_demo_injection02] 'tblUser;Drop table tblUser;--','bkm','mahto'
Output generated query:
SELECT * FROM tblUser;Drop table tblUser;-- WHERE username = 'bkm' and lastname= 'mahto'

Let's see here what I did, Basically I have given a way to a hacker to delete/or do anything serious using my query. Above query will drop my table and this is a big security risk.

Above query is just an example, In real time it could be a big disaster. So this is called SQL Injection.

Now I must need to re-write my stored procedure to avoid this sql injection, so this is what I did:
I changed my above SP like this:

Create PROC [sp_demo_injection02](
@tablename varchar(50),
@username varchar(50),
@lastname varchar (50)
)
AS
  declare @cmd nvarchar(max)
  declare @parameters nvarchar(max)

  set @cmd = N'SELECT * FROM '+ quotename(@tablename)+' WHERE username = @username and @lastname=lastname' --Make use of quotename for sql object

 set @parameters = '@username varchar(50), @lastname varchar (50)' --Here goes all parameters except the sql object(table name, sp name)
  
EXEC sp_executesql @cmd, @parameters, @username = @username, @lastname = @lastname
go


Let me explain what i did here:
1. I removed concatenation for table name and parameters which was the biggest culprits here.

2. Also I used quotename(@tablename) : quotename is a sql function which will convert my @tablename string value to this [tblUser]. So any string withing bracket is considered as a sql object (table, stored proc, view...). this method can be apply to a string for 128 char long.
for more info: http://msdn.microsoft.com/en-us/library/ms176114.aspx

3. I converted all my string parameter to sql parameter.
set @parameters = '@username varchar(50), @lastname varchar (50)'

4. Executing my dynamic query using sp_executesql which executes my dynamic sql query by accepting parameters.
For more Info: http://msdn.microsoft.com/en-us/library/ms188001.aspx

In this way you can be sure of any sql attacks for your dynamic sql query. But for best practices you also must do following things:
Implement strong server side validation for all user inputs including cookie values.

  1. Must do server side validation and escape or filter the special characters from user inputs.
  2. Always use store procedures whenever possible.
  3. Always use parameters with stored procedures or dynamic queries inside stored procedures.
  4. Always use least privileged account (like read-only) to execute queries.
  5. Avoid disclosing error (exception) details to the user, instead use customize error information for client. Because exception details may have critical information (like code logic, server info., etc)
Thanks.







Wednesday, 22 August 2012

Custom Handle Error Attribute to handle exception in MVC 3 app


Frnds.
In this post I am going to explain, How can we handle error in MVC  application through common custom error attribute.
First create the custom Error Handler Attribute class. So here is our attribute class:
 public class HandleExceptionAttribute : FilterAttribute, IExceptionFilter
    {
        public void OnException(ExceptionContext filterContext)
        {
            filterContext.ExceptionHandled = true;

            string controllerName = filterContext.RouteData.Values["controller"].ToString();
            string actionName = filterContext.RouteData.Values["action"].ToString();
            string exceptionMessage = string.Empty;

            //You may not need this tracing code. Ignore it!
            Trace.TraceError("Controller = {0} : Action = {1} : Message = {2} : StackTrace = {3}",
                controllerName,
                actionName,
                filterContext.Exception.Message,
                filterContext.Exception.StackTrace);

            //Below is the switch case to handle error for all the controller class in our
            //MVC application at one place.
            switch (controllerName)
            {
                case "State":
                    switch (actionName)
                    {
                        case "Create":
                            actionName = "Index";
                            exceptionMessage = "Sorry, an error occured on creating new State, Please try again.";
                            break;
                        case "Edit":
                            actionName = "Index";
                            exceptionMessage = "Sorry, an error occured on editing new State, Please try again.";
                            break;
                        case "Delete":
                            actionName = "Index";
                            exceptionMessage = "Sorry, an error occured on deleting new State, Please try again.";
                            break;
                        default:
                            break;
                    }
                    break;
                case "Account":
                    switch (actionName)
                    {
                        case "Register":
                            controllerName = "Register";
                            actionName = "Index";
                            exceptionMessage = "Sorry, an error occured on registering new User, Please try again.";
                            break;
                        case "Login":
                            controllerName = "Login";
                            actionName = "Index";
                            exceptionMessage = "Sorry, an error occured on Login, Please try again.";
                            break;

                    }

                    break;
            }

            //Creating ViewData Dictionary which will hold the error info to show to the end user.
            ViewDataDictionary viewData = new ViewDataDictionary();
            viewData.Add(new KeyValuePair<string, object>("controller", controllerName));
            viewData.Add(new KeyValuePair<string, object>("action", actionName));
            viewData.Add(new KeyValuePair<string, object>("message", exceptionMessage));

            //Calling error page inside shared folder to show the proper error message.
            filterContext.Result = new ViewResult { ViewName = "Error", ViewData = viewData };
        }
    }
Above attribute will help to handle error. You can add your controller and action method in switch case
statement as per your need.

Now Next step we will see how to use this attribute.
        [HandleException]
        public ActionResult Edit(StateModel stateModel)
        {
            try
            {
                // TODO: Add update logic here
                throw new InvalidOperationException();
            }
            catch(Exception ex)
            {
                throw ex;
            }
        }
Since my Custom Error Handler Attribute  is written to handle error for each action of controller so I need to use it before my action method. In above code [HandleException] attribute  will execute our Custom Handle Attribute class code written here in case of any error.
Next step we need to modify/create the error  page (Error.cshtml) inside shared folder to show the error message to the end user.
@{
    ViewBag.Title = "Error";
}

<h2>
    Sorry, @ViewData["message"].<br />
    <a href="@Url.Action(ViewData["action"].ToString(),ViewData["controller"].ToString())">Back</a>
</h2>
Note: Modify the above code as per your need and enjoy.
Thank You for reading.