Friday, May 31, 2013

LINQ 02- Extension Methods

Extension method is a way to add methods to existing types without inheritance. It is actually a virtual implementation of static methods.

For example, we may frequently want to get the Right n characters from string. We cannot inherit string data type as it is a sealed type. Even if we have a non sealed type, it would be difficult to include the right method to existing objects.

Simplest way would be adding a static method which receives a String and a length parameter, and returns string of right n characters.

public class StringMethods{

    public static string Right(string s, int n) {
        return s.Substring(s.Length - n);
    }

}

Calling this method would be easier like,

String s = “Muthukrishnan”;

String t = StringMethods.Right(s, 5); // Will return “shnan”

 

Extension method makes this easier for better readability.

To convert the right static method to extension method, we have to prefix this keyword to the first parameter which marks it as the calling object.

public class StringMethods{

    public static string Right(this string s, int n) {
        return s.Substring(s.Length - n);
    }

}

With this, we can call the Right method with a simple and familiar syntax.

String s = “Muthukrishnan”;

String t = s.Right(5); // Will return “shnan”

 

Note: To make the Extension methods to a code, the namespace or extension class should be imported.

Wednesday, May 29, 2013

LINQ 01- Introduction

Language INtegrated Query, is a simplified syntax for processing collection of objects.

We can say most of the new language features in .NET 3.5 and above are innovated to realize, simplify and improve LINQ syntax.

Basically LINQ is built around IEnumerable interface. Almost all of the .Net collection objects from Arrays to Generic List and Dictionary, are implemented with IEnumerable interface.

LINQ syntaxes are realized with Extension methods and Delegates. For eg, LINQ to Objects are built with Extension methods for IEnumerable with delegate parameters.

To simplify the usage of delegate parameters, anonymous methods, lambda methods and lambda expressions are introduced.

A simple LINQ Query

var s = new string[] { "Apple", "Orange", "Mango" };
var l = from i in s
select i.Length;

Above is a simple LINQ query, just selects the length of string items from an array. Above can be achieved without LINQ as


var s = new string[] { "Apple", "Orange", "Mango" };
var l = s.Select(i => i.Length);

Following concepts can be used to simply the LINQ statements



  • Extension Methods
  • Lambda Expressions
  • Anonymous Types
  • Automatic Type Inference
  • Auto Implemented Properties
  • Object and Collection Initializers

Tuesday, May 21, 2013

Types of Applications with .Net Framework

We can classify the applications into the following categories

 

  • CUI Applications- Primary interface will be a Console, which can basically support characters alone.
    • Console Applications
  • GUI Applications- Primary will be a window capable of showing rich graphics
    • Windows Forms
    • WPF Forms
  • No-UI/Background Applications- Will be running in background and do the intended work or will support other application types
    • Windows Services
  • Web Applications- Will be deployed in a web server and provide interface
    • ASP.NET Web Forms Applications
    • ASP.NET MVC Applications
  • Services- Provides business logic to other application types
    • ASP.NET Web Services
    • WCF Services

 

Notes:

  • .Net supports showing GUI from Console Applications
  • WCF services can be hosted in any type of services

Sunday, May 12, 2013

Returning Json Results from Mvc Controllers without JsonResult

Some of the developers may not like returning JsonResult, because it may hide the actual data type we intend to return. They may like to return an object which should be automatically converted to JSON by the controller. The default ASP.NET controller will not do this. We have a work around to fix this.

 

Action invocation in ASP.NET MVC controller is accomplished by ActionInvoker. IActionInvoker is the base interface used by ASP.NET MVC controller for Action invocation. System.Web.Mvc.Async.AsyncControllerActionInvoker  is one of the default action invoker for ASP.NET MVC. We can change the default Action Invoker of a Controller by changing the ActionInvoker property of a controller. Before that we may have to created our own Action invoker for converted object to JsonResult.

 

public class JsonControllerActionInvoker : AsyncControllerActionInvoker {
    protected override ActionResult CreateActionResult(
        ControllerContext controllerContext,
        ActionDescriptor actionDescriptor,
        object actionReturnValue) {

 

       return actionReturnValue == null
            ? new EmptyResult()
            : (actionReturnValue as ActionResult)
            ?? new JsonResult() { Data = actionReturnValue, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
    }
}

 

Then we can change the controller’s Action invoker in the controller’s constructor, with the following code.

this.ActionInvoker = new JsonControllerActionInvoker();

 

Instead of adding this code to all our controller class we can have a base controller for this.

 

public class JsonController : Controller {
    public JsonController() {
        this.ActionInvoker = new JsonControllerActionInvoker();
    }
}

Returning Json Results from Mvc Controllers

When we use Mvc controllers as REST API Services, usually we may need to return data as JSON.

 

If we return data as its in ASP.NET Controllers, the data will be converted to String using ToString()

public string[] MyJsonData()
{    return new String[] { "A", "B", "C" };
}

will return



System.String[]


 


To avoid this we can use JsonResult method in Controller class


public JsonResult MyJsonData()
{     return Json(new String[] { "A", "B", "C" });
}

If we use the above code when we need to GET the data, it may throw the below error.



This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet


 


To avoid this we can pass a second parameter to the Json method as


public JsonResult MyJsonData()
{     return Json(new String[] { "A", "B", "C" }, JsonRequestBehavior.AllowGet);
}