How JSONP work on cross domains

Be a fan

Cross domain Ajax are disable all modern browsers because of security concerns but now web components are very highly distributed, means various kind of JavaScript widgets require get data from different server. Facebook like button, twitter tweet button, or LinkedIn share button these are few examples of third party widgets which allow you to embed them to your website. But accessing data from other site is key all widgets. JSONP solved the problem of cross site ajax request.

JSONP work like just simple JavaScript file. To understand JSONP understand following points

- Cross site JavaScript file injection on your site is possible, means you can inject JavaScript file which hosted by another domain on runtime by JavaScript to your website

- Whatever JavaScript file is added, browsers execute it immediately, means if any method calling statement in this file, browsers call these methods also.

So idea is behind JSONP Ajax request is to add JavaScript tag runtime and set src attribute of this tag is JSONP api endpoint. But how callback method will be called? to understand let understand this trick

- We register a method with unique name to windows object

windows["postsLoaded"] = fucntion(data){ //use data  }

- We pass callback parameter with endpoint and set this complete endpoint to ‘script’ tag as src attribute.

example : http://my-awesome-api.com/api/v1/posts/10?page=1&callback=postsLoaded

- Now from server we read callback parameter and server JSON in this format

<Callback parameter Value>(<Response JSON Data>);

example :  postsLoaded([{ "name" : "jon" },{ "name" : "smith" },{ "name" : "david" }]);

- Now browser will automatic call postsLoaded method when response will come to browser

 

Check complete code to call JSONP ajax


Be a fan

Marvel plugin installation for ElasticSearch on windows

Be a fan

In My last Blog of installation ElasticSearch on windows, Now you can start exploring ElasticSearch on windows, You can Marvel plugin for it

  • Open command prompt and navigate to your elastic installation directory and then navigate to bin directory in my case path command was

cd C:\Program Files\Elasticsearch\bin

  • Run this command

Plugin.bat -i elasticsearch/marvel/latest

If you get this error “Failed to install elasticsearch/marvel/latest, reason: plugin directory C:\Program Files\Elasticsearch\plugins is read only” then create a ‘plugins’ directory to root of your ElasticSearch installation path and make it write and Read write permissions for all user.

    • Again run same command
  • Restart ElasticSearch service
  • Open http://localhost:9200/_plugin/marvel from any browser

You can see various option, you can learn about it further from various sources detailing out these option off topic for this blog, You can querying on ElasticSearch by sense plugin, on right top you can see one dropdown menu click on ‘Dashboard’ you can see various options in this menu, select ‘sense’ option it will open query window. Now you start querying on ElasticSearch.


Be a fan

ElasticSearch setup on windows

Be a fan

If you are going to try ElasticSearch on Windows PC, I can help you, these are easy and simple steps to install ElasticSearch on windows PC

  • Java 7 or later require on your PC, if it is not installed on your PC than install, and set JAVA_HOME environment variable properly, download java 7 from oracle’s java download page an check instructions to setup JAVA_HOME environment variable
  • Download ElasticSearch installer from https://github.com/rgl/elasticsearch-setup/releases and install it your PC.
  • Navigate to you elastic installation directory and open config directory. In my case C:\elastic\config
  • Open elasticserach.yml file in any text editor
  • Search ‘cluster.name’, remove comment from this line by removing hash and set name which you want
  • Just below line check node.name and remove comment and set node name which you want
  • Open services (by typing services in run) panel and run ‘elasticsearch’ service.
  • Enter url http://localhost:9200 to any web browser and press enter

Now your ElasticSearch is ready on your PC, start exploring it. You can read next blog post for installing Marvel plugin for ElasticSearch on windows to exploring ElasticSearch more…


Be a fan

Custom container key for AWS beanstalk in Visual Studio

Be a fan

You can’t redeploy for just changing string SMTP credential or connection etc. In normal deployments we use appSetting in web.config, but when we use AWS beanstalk the we can’t change web.config, because these two reasons.

  1. Multiple Instances.
  2. Removed changes when machine upgrade.

For this problem AWS provide Container (environment configuration settings), In legacy hardware it provide only 5 predefined keys PARAM1 to PARAM5.

But in non-legacy hardware it support custom key, for creating deployment with non-legacy hardware you have to create deployment from AWS console. All keys can access through ConfigurationManager.AppSettings, so no need to any extra code to access AWS container keys.


string connstring = ConfigurationManager.AppSettings["ConnString"];

For adding these key in Visual studio project

  1. add a directory in root .ebextensions, and make sure it is part of project
  2. add a file with .config extension, eg. appSetting.config, and make sure it is content as build action (to set build action, right click on file and property)

this file can only contains YAML, so we have to write keys using YAML syntax,

option_settings:
  - option_name: ConnString
    value: Data Source = db.hostname ; Initial Catalog = MyDB ; User ID = myuser; Password = pass2123
  - option_name: IsLoggerOn
    value: 1

Note

option_settings: root (equivalent to >appSetting> in web.config)
option_name: Key (equivalent to key attribute of >add /> element)
value: Value of key (equivalent to value attribute of >add /> element)

Make sure you are writing valid YAML syntax, because Visual Studio auto format .config files. You can use YAMLLint to check valid YAML or not. You can add more keys in this.

Now when you will deploy your application these key will automatically added to Environment configuration settings. You can change these key any time from Visual Studio AWS plugin or AWS console.

for changing Container from Visual Studio : To access the Container/.NET Options panel for your AWS Elastic Beanstalk application

  1. In AWS Toolkit for Visual Studio, expand the AWS Elastic Beanstalk node and your application node.
  2. In AWS Explorer, double-click your AWS Elastic Beanstalk environment.
  3. Under ‘Advanced’ scroll to aws:elasticbeanstalkapplication:environment , you can configure container options.

Change value and click on ‘Apply changes’.


Be a fan

jQuery Ajax using Http Handler

Be a fan

Handlers makes life easier for using pure JavaScript or jQuery Ajax, I think it’s much cleaner way to use Handlers to call Ajax. jQuery is most popular JavaScript library in the world and it’s very easy to use.

We can create handlers in to ways one is Generic handler and second is custom handler. Generic handlers have pre mapping as *.ashx with custom handler we need to add handler mapping in web.config.

Handler are faster then ASP.NET WebPage, because of small life cycle (only one method for executing). Handlers never generate ViewState also.

Every handler must be implemented System.Web.IHttpHandler, and need to implement following method and property

    public class SampleHandler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            context.Response.Write(_jsserializer.Serialize(_productentity.GetProduct()));
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

I already mentioned that we can use handlers two types. let understand it.

Generic handler (.ashx) :

It is pre mapped handler and .ashx is a mark up file like .aspx. for adding Generic handler follow these steps.

Right click on Project > Add > New Item… > Web > Generic Handler (enter name of handler)

generic handler contains two file (one is mark and second is code behind), in markup file VS generate following directive

<%@ WebHandler Language="C#" CodeBehind="getproducts.ashx.cs" Class="IAnswerable.HttpHandlersTutorial.GenericHandler.getproducts" %>

we can remove code behind file and add code below directive (it is same as add runat server script on .aspx page)., but this will not be pre compiled, let understand with getproduct handler

<%@ WebHandler Language="C#" CodeBehind="getproducts.ashx.cs" Class="IAnswerable.HttpHandlersTutorial.GenericHandler.getproducts" %>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using IAnswerable.HttpHandlersTutorial.Entity;
using System.Web.Script.Serialization;

namespace IAnswerable.HttpHandlersTutorial.GenericHandler
{
    public class getproducts : IHttpHandler
    {
        ProductEntity _productentity = new ProductEntity();
        JavaScriptSerializer _jsserializer = new JavaScriptSerializer();

        public void ProcessRequest(HttpContext context)
        {
            context.Response.Write(_jsserializer.Serialize(_productentity.GetProduct()));
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

We can check result of this direct from browser just type url of this (on my end it is http://localhost:2312/GenericHandler/getproducts.ashx), we will use this handler in jQuery after Custom handler.

Custom handler :

for adding this kind of handler follow following steps

Right click on Project > Add > New Item… > Web > ASP.NET Handler

enter name according to your requirements, it will be looked like just simple class

My product handler is (I have coded same functionality as generic handler)

using System;
using System.Web;
using System.Web.Script.Serialization;
using IAnswerable.HttpHandlersTutorial.Entity;

namespace IAnswerable.HttpHandlersTutorial.CustomHandler
{
    public class Products : IHttpHandler
    {
        #region IHttpHandler Members
        ProductEntity _productentity = new ProductEntity();
        JavaScriptSerializer _jsserializer = new JavaScriptSerializer();

        public void ProcessRequest(HttpContext context)
        {
            context.Response.Write(_jsserializer.Serialize(_productentity.GetProduct()));
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
        #endregion
    }
}

We can’t access this handler without adding Handler mapping in web.config, open Web.config and add following mapping.

If you are using IIS6 then add following under system.web > httpHandlers

<add path="getproducts.pr" verb="*" type="IAnswerable.HttpHandlersTutorial.CustomHandler.Products"/>

and if using II7 or 7.5 then

<add name="getproducts" path="getproducts.pr" verb="*" type="IAnswerable.HttpHandlersTutorial.CustomHandler.Products"/>

in mapping

  • path : url of handler (don’t have added getproducts.pr)
  • verb : accepted http methods (GET, POST, HEAD etc.) * means all
  • type : Type of handler
  • name (in IIS 7 or above) : just unique name.

We can access this handler from browser directly (my end url is http://localhost:2312/getproducts.pr)

Handlers useful in REST api (not recommended) and in Ajax, Let we understand how to use Handlers through jQuery. jQuery is very easy to use and lightweight.

first add jQuery I recommend use google cdn for this

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

then use this jQuery ajax code, click event of a button

<script>
$(document).ready(function(){
     $("#loadpage").click(function(){
         $.getJSON("/getproducts.pr",function(products){
                $.each(products, function(key, val) {
                   items.push('<li id="' + key + '">' + val + '</li>');
                });
                // created list and append to products div.
                $('<ul/>', { 'class': 'my-new-list',html: items.join('')}).appendTo('#productsdiv');
         });
     });
});

</script>

You can use various ajax methods as your requirements.

Stackoverflow reference


Be a fan

Asp.net Web API and google chrome’s Postman plugin

Be a fan

MS introduced Asp.net web api with Visual studio 11 (Consumer preview, you can download from here), Its a good framework to create REST api, very clean and maintainable. I have created a sample project for learning purpose and I used Google chrome’s Postman plugin it is good plugin to consume REST services. You can add from here.

1. Open Visual Studio 11 create new project using “ASP.NET MVC 4 Web Application” and Click on OK button


MVC4 Project



2. Select “Web API” from Project template dialog box


ASP.NET Web Api



3. Solution will be ready in few seconds and its look like


Asp.net web api project



4. Open global.asax file and check “RegisterRoutes” method, in this by default “MapHttpRoute” (MapHttpRoute is responsible for routing of web api controller) map to “api/{controller}/{id}” means Web api controllers accessing through “api/{controller}/{id}” path you can change it according to your requirement.

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }




5. Now create a Employee class with following definition in Model

namespace SampleWebApi.Models
{
    public class Employee
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Department { get; set; }
    }
}




6. And Create following EmployeeModel. In this model I have created Add, UpdateEmploayee, DeleteEmployee, GetEmployees and and GetEmployee methods and for data storage I have used a static List, it store data unless App recycle. You can use database for storage. I have used static List for just showing example.

using System.Collections.Generic;
using System.Linq;

namespace SampleWebApi.Models
{
    public class EmployeeModel
    {

        public static List<Employee> _employees =new List<Employee>();

        public void Add(Employee employee)
        {
            //for getting next ID
            if (_employees.Count > 0)
            {
                employee.ID = _employees.Max(emp => emp.ID) + 1;
            }
            else
            {
                employee.ID = 1;
            }

            //add to _employee
            _employees.Add(employee);
        }

        public List<Employee> GetEmployees()
        {
            return _employees;
        }

        public Employee GetEmployee(int id)
        {
            return _employees.Where(employee => employee.ID == id).FirstOrDefault();
        }

        public int UpdateEmployee(int id, Employee employee)
        {
            var updatableemployee = _employees.Where(emp => emp.ID == id).FirstOrDefault();

            if (updatableemployee != null)
            {
                updatableemployee.Department = employee.Department;
                updatableemployee.Name = employee.Name;
                return updatableemployee.ID;
            }
            else
            {
                return 0;
            }
        }

        public bool DeleteEmployee(int id)
        {
            return _employees.Remove(_employees.Where(emp => emp.ID == id).FirstOrDefault());
        }
    }
}




7. And Following EmployeesController. In following code you are seeing that EmployeesController inherit ApiController and ApiController class is base class of web api controller. Mapping of HTTP methods and api controller’s methods is


GET ==> Get (used for getting resources)

POST ==> Post (used for Adding resource)

DELETE => Delete (used for deleting resource)

PUT ==> Put (used for Updating resource)

using System.Collections.Generic;
using System.Web.Http;
using SampleWebApi.Models;

namespace SampleWebApi.Controllers
{
    public class EmployeesController : ApiController
    {
        EmployeeModel employeemodel = new EmployeeModel();

        // GET /api/employees
        public IEnumerable<Employee> Get()
        {
            return employeemodel.GetEmployees();
        }

        // GET /api/employees/5
        public Employee Get(int id)
        {
            return employeemodel.GetEmployee(id);
        }

        // POST /api/employees
        public void Post(string name, string department)
        {
            Employee employee = new Employee();
            employee.Name = name;
            employee.Department = department;
            employeemodel.Add(employee);
        }

        // PUT /api/employees/5
        public void Put(int id, Employee employee)
        {
            employeemodel.UpdateEmployee(id, employee);
        }

        // DELETE /api/employees/5
        public void Delete(int id)
        {
            employeemodel.DeleteEmployee(id);
        }
    }
}




8. Run this project and open Google chrome’s postman plugin, in this we option to Enter Url, HTTP request type, Request Headers, Form collection, Url parameter etc, so it is very easy to test Web api with Postman plugin.


Google Chrome PostMman Plugin



9. Now I am consuming these requests through Google chrome’s postman plugin. It can used just for testing and debugging the web api’s before implementing.


1. HTTP POST : First I am adding some record to the data store, for I need to call HTTP POST request of web api endpoint.

for calling HTTP POST follow these steps

1. Input endpoint, my endpoint is http://localhost:2411/api/employees/.

2. Select ‘POST’ from drop down.

3. Select form type is “x-www-form-urlencoded”.

4. Add two key “name” and “department” and their values.

5. Click on “Send” button.

6. After few milliseconds api will respond, this request add a record.

I added two records for example following above steps again.


example http post request in postman plugin



2. HTTP GET : For getting Employees list I need to call HTTP post of web api endpoint

for calling HTTP GET follow these steps

1. Input endpoint, my endpoint is http://localhost:2411/api/employees/.

2. Select “GET” from drop down.

3. 5. Click on “Send” button.

6. After few milliseconds api will respond. It returns json array in response, you can see in following image.


example http get request in postman plugin

If you want to get specific Employee then use specific ID like

http://localhost:2411/api/employees/2

Response of this request is

{
     "Department" : "MBA",
     "ID" : 2,
     "Name" : "Ashok Bishnoi"
}



3. HTTP PUT : For updatting I need to call HTTP PUT request of web api endpoint.

for calling HTTP PUT follow these steps

1. Input endpoint, my endpoint is http://localhost:2411/api/employees/.

2. Add a employee at end of endpoint(http://localhost:2411/api/employees/) , I am updating employee of ID 2, so endpoint looks like http://localhost:2411/api/employees/2

3. Select ‘PUT’ from drop down.

4. Select form type is “x-www-form-urlencoded”.

5. Add two key “name” and “department” and their values.

6. Click on “Send” button.

7. After few milliseconds api will respond, this request update the record with ID 2. In my example just “1″ you can manipulate it.


http post using postman plugin

You can check updated records using HTTP GET request.



4. HTTP DELETE : For deleting record I need to call HTTP DELETE request of web api endpoint

for calling HTTP DELETE follow these steps

1. Input endpoint, my endpoint is http://localhost:2411/api/employees/.

2. Select ‘DELETE’ from drop down.

3. Select form type is “x-www-form-urlencoded”.

4. Add one key “id” and its value, I am deleting record with ID 2.

5. Click on “Send” button.

6. After few milliseconds api will respond, this request delete the record with ID 2.


http delete request using postman plugin

You can check deleted record using HTTP GET request.


Be a fan

Func, Action and Predicate

Be a fan

Func, Action and Predicate are predefined generic delegates which are included with .NET framework. Func refer method which always return a value, Action always refer a method which don’t return value and predicate which always take one argument and return always bool type value.

let understand their signature, I have decompiled the mscorlib and navigate to System namespace and found these signature for

1. Func : Func have nine kinds of signature in param are input type and out param is return type, maximum 8 input parameters

func

2. Action : Action have eight kind of signature, maximum 8 input parameters

action

3. Predicate : Predicate have only one input parameter and returns always boo type.

predicate

let understand with code example, I used Math delegate in my previous blob on delegate, Anonymous methods and Lambda notation that Math delegate is equivalent of

Func<int,int,int>
// delegate int Math(int value1, int value2);

now I can use this Func delegate to refer Add method , in this example I just refer Add method to math delegate. I am using Func with 2 int input param with int return type.

    class Program
    {
        static void Main(string[] args)
        {
            Func<int, int, int> math = Add;
            Console.Write(math(1, 1));
        }
        public static int Add(int a, int b)
        {
            return a + b;
        }
    }
    //output
    //2

we can also assign anonymous method, in this I have created a anonymous method through delegate

    class Program
    {
        static void Main(string[] args)
        {
            Func<int, int, int> math = delegate(int a, int b)
                                        {
                                            return a + b;
                                        };
            Console.Write(math(1, 1));
        }
    }
    //output
    //2

we can also assign anonymous method through lambda notation

    class Program
    {
        static void Main(string[] args)
        {
            Func<int, int, int> math = (a, b) => { return a + b; };
            Console.Write(math(1, 1));
        }
    }
    //output
    //2

or if anonymous method have single statement then

    class Program
    {
        static void Main(string[] args)
        {
            Func<int, int, int> math = (a, b) =>  a + b;
            Console.Write(math(1, 1));
        }
    }
    //output
    //2

Action never return value, following example I have created a delegate which takes one int input parameter and Print on console.

    class Program
    {
        static void Main(string[] args)
        {
            Action<int> Print = (a) => { Console.Write(a); };
            Print(10);
        }
    }
    //output
    //10

You can pass multiple input parameters up to 8 , in following example i am passing 3 input parameter 2 string type and 1 int type.

    class Program
    {
        static void Main(string[] args)
        {
            Action<string,string,int> PrintResult = (name,regNo,marks) => { Console.Write(string.Format("Name : {0} \nRegisteration No. : {1} \nMarks : {2} ",name,regNo,marks)); };
            PrintResult("Mark", "RJ24", 390);
        }
    }
    //output
    //Name : Mark
    //Registeration No. : RJ24
    //Marks : 390

And now finally predicate takes only one input parameter and return always bool type

    class Program
    {
        static void Main(string[] args)
        {
            Predicate<int> IsLessThenTen = (a) => { return a < 10; };
            Console.WriteLine(IsLessThenTen(10));
            Console.WriteLine(IsLessThenTen(2));
        }
    }
    //output
    //False
    //True

its equivalent to Func<int,bool> , check following example

    class Program
    {
        static void Main(string[] args)
        {
            Func<int,bool> IsLessThenTen = (a) => { return a < 10; };
            Console.WriteLine(IsLessThenTen(10));
            Console.WriteLine(IsLessThenTen(2));
        }
    }
    //output
    //False
    //True

You can pass Func, Action and Predicate as parameter also, check following example

class Program
    {
        static void Main(string[] args)
        {
            var namesstartwithm = GetNames(name => name.StartsWith("M"));
 
            Console.WriteLine("--- Name which are starts with M char ------");
            foreach (var name in namesstartwithm)
            {
                Console.WriteLine(name);
            }
 
            var names = GetNames(name => name.Count()<=3);
 
            Console.WriteLine("\n\n--- Name which are contains less then or equals to 3 chars ------");
            foreach (var name in names)
            {
                Console.WriteLine(name);
            }
 
            Console.ReadLine();
        }
 
        public static IEnumerable<string> GetNames(Func<String,bool> namecriteria)
        {
            List<string> names = new List<string>();
            names.Add("John");
            names.Add("Martin");
            names.Add("Tom");
            names.Add("Nick");
            names.Add("Geoge");
            names.Add("Matt");
 
            foreach (var name in names.AsEnumerable())
            {
                if (namecriteria(name))
                {
                    yield return name;
                }
            }
        }
    }
 
//output
//
//--- Name which are starts with M char ------
//Martin
//Matt
 
//--- Name which are contains less then or equals to 3 chars ------
//Tom

Be a fan

Linq to Asp.net controls

Be a fan

Some we use many controls on a page and we need to get their value we access them through ID and its very time consuming process, we can access through Linq , It is easy and much cleaner way. For querying on controls of page we need to create a function which can access all controls of page recursively. For this I am creating a extension method which get reference all controls recursively.


using System.Collections.Generic;
using System.Web.UI;

namespace IAnswearble.Utility
{
    public static class PageExtension
    {
        public static IEnumerable<Control> GetAllControls(this Control parent)
        {
            foreach (Control parentcontrol in parent.Controls)
            {
                yield return parentcontrol;
                foreach (Control childcontrol in parentcontrol.GetAllControls())
                {
                    yield return childcontrol;
                }
            }
        }
    }
}

Now I we can use it for any type query on controls of page, for querying we need use namespace IAnswearble.Utility

Example 1 : Get all check boxes which are selected

var selectedcheckboxes = this.GetAllControls().OfType<CheckBox>().Where(item => item.Checked);

Example 2 : Get value of all TextBoxes

using System;
using System.Linq;
using System.Web.UI.WebControls;
using IAnswearble.Utility;

namespace WebApplication1
{
    public partial class Default : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            var textoftextboxes = from textbox in this.GetAllControls().OfType<TextBox>()
                                     select new { ID = textbox.ID, Text = textbox.Text };

            foreach (var textoftextbox in textoftextboxes)
            {
                Response.Write(string.Format("Value of {0} is {1}", textoftextbox.ID , textoftextbox.Text));
            }
        }
    }
}

Example 3 : Get child controls of a specific control

 var textboxofdivform = this.GetAllControls().Where(item => item.Parent.ID == DivForm.ID).OfType<TextBox>();

Be a fan

Extension Methods

Be a fan

Extension methods enable you to “add” methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type. (Source MSDN)

For creating Extension method
1. Method should be in static class
2. Method should be static
3. Pass parameter (with this keyword) of type for which you are writing extension method.
4. Namespace (where extension method defined) should be added where you want to use it

let understand with example

public static class NumericExtension
{
    public static ToInt(this string value)
    {
        int number;
        if(int.TryParse(value,out number))
        {
            return number;
        }
        else
        {
          throw  new InvalidCastException();
        }
    }
}

We can use this on string object directly like

    class Program
    {
        static void Main(string[] args)
        {
            string strnumber ="1980";
            int number = strnumber.ToInt(); // call ToInt() directly like member methods
        }
    }

Extension method behave like public member so it is inherited to derived classes le understand one example.

public static class ObjectExtension
{
    public static bool IsNotNull(this object value)
    {
        return value!=null;
    }
}

In above example I attached a extension methods to Object and Object is parent class of all classes, so we can call IsNotNull method on any type.

    class Program
    {
        static void Main(string[] args)
        {
            string name = null;

            //on string type
            if (name.IsNotNull())
            {
                // do your stuff
            }

            //on string array type
            if (args.IsNotNull())
            {
                //do your stuff
            }

            List<int> series = new List<int>();

            //on generic list type
            if (series.IsNotNull())
            {
                //do your stuff
            }
        }
    }

Be a fan

Delegate, Anonymous method and Lambda notation

Be a fan

Definition : A delegate is a type that references a method. Once a delegate is assigned a method, it behaves exactly like that method. The delegate method can be used like any other method, with parameters and a return value. (source : MSDN )

delegate is defined by delegate keyword lets understand with example I am creating delegate with name Math

delegate int Math(int value1, int value2);

in this delegate 2 int argument and int return type so we can assign any function’s reference which takes 2 int arguments and returns int value, I created a method for sum two values.

       public static int Add(int a, int b)
        {
            return a + b;
        }

I can assign reference of this method to Math delegate, like

Math math = Add;

and call this delegate

math(1, 1);

it return 2 because this delegate call Add method. We can also assign anonymous methods to delegate

Math math = delegate(int a, int b) { return a + b; };

above I created a anonymous method and assign to  math delegate. we can also use lambda (=>) notation for creating anonymous functions.

Math math = (a, b) => { return a + b; };

We can also write if our anonymous method contains only one statement

Math math = (a, b) => a + b;

in above statement no need to write datatype, lambda notation widely used in C# these days for creating anonymous methods.

    class Program
    {
        delegate int Math(int value1, int value2);

        static void Main(string[] args)
        {
            Math math = (a, b) => a + b;

            Console.Write(math(1, 1));
        }

        public static int Add(int a, int b)
        {
            return a + b;
        }
    }

delegate allows to pass functions as arguments and its very powerful feature of .net with this we can create more generic method, lambda notation used for passing small methods to function.

Let understand a example in this I am passing method’s reference to method for creating more generic method.

class Program
    {
        public delegate bool NameCriteria(string name);

        static void Main(string[] args)
        {
            var namesstartwithm = GetNames(name => name.StartsWith("M"));

            Console.WriteLine("--- Name which are starts with M char ------");
            foreach (var name in namesstartwithm)
            {
                Console.WriteLine(name);
            }

            var names = GetNames(name => name.Count()<=3);

            Console.WriteLine("\n\n--- Name which are contains less then or equals to 3 chars ------");
            foreach (var name in names)
            {
                Console.WriteLine(name);
            }

            Console.ReadLine();
        }

        public static IEnumerable<string> GetNames(NameCriteria namecriteria)
        {
            List<string> names = new List<string>();
            names.Add("John");
            names.Add("Martin");
            names.Add("Tom");
            names.Add("Nick");
            names.Add("Geoge");
            names.Add("Matt");

            foreach (var name in names.AsEnumerable())
            {
                if (namecriteria(name))
                {
                    yield return name;
                }
            }
        }
    }

//output
//
//--- Name which are starts with M char ------
//Martin
//Matt

//--- Name which are contains less then or equals to 3 chars ------
//Tom

in above program I created a method GetNames (in this I create List of names for example) it returns list of names as IEnumerable and it takes one parameter NameCriteria (defined at first line of class Program) type, NameCriteria is a delegate this delegate takes one string parameter and return boolean value.In GetNames method I iterate the name list and pass name to the namecriteria delegate and check if it is true then return. (note yield used to return iterate values)

Then I used this method for two type

1. in first I passed following anonymous method, it check is name starts with ‘M’

name => name.StartsWith("M")

2. in second I passed following anonymous method, it check is name contains less then or equals 3 chars.

name => name.Count()<=3

Be a fan