Sunday, January 8, 2012

Asynchoronous Invocations

Functions can be invoked asynchronously via many ways. here is simplest way to call WCF function in ASP MVC asynchronously..

1. Create a new ASP.net MVC project
2. Add a new WCF project to the solution


 public class Service1 : IService1
    {
        public string GetData(int value)
        {
            return string.Format("You entered: {0}", value);
        }
}

This is the default WCF project with implementation.


Add the following to the controller to invoke the function asynchronously.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MyWcfService;

namespace Sample1.Controllers
{
    [HandleError]
    public class HomeController : AsyncController
    {

        IService1 service = new Service1();

        //delegate string asyncDelegate(int id);

        public void IndexAsync()
        {
            ViewData["Message"] = "Welcome to ASP.NET MVC!";

            int num = 5;

            for (int i = 0; i < num; i++)
            {
                Func<int, string> myAction = input =>
                {
                    return service.GetData(input);
                };

                AsyncCallback mycallBack = result =>
                {
                    AsyncManager.Parameters["myString"] = myAction.EndInvoke(result);
                    AsyncManager.OutstandingOperations.Decrement();
                };

                myAction.BeginInvoke(i, mycallBack, null);
             }
         }

        public ActionResult IndexCompleted(string myString)
        {
            return this.View((object)myString);
        }

        public ActionResult About()
        {
            return View();
        }
    }
}

IndexAsync & IndexCompleted is used to call the controller asynchronously.

Action or Func has BeginInvoke & EndInvoke methods which is used to call the method asynchoronously.

Properties added to AsyncManager.Parameters can be accessed in Completed async controller as a paramters.

Sunday, January 1, 2012

Simple Dot Net Extension

Simple Class Extension can be written using "this" keyword in the parameter. These extensions can be used for Dot net and static classes.

public static class MyExtension
{
     public static string myString(this string s)
     {
         return "my string is:" + s;
     }
}

public class SimpleExtensionTrial
{
   public static void Main ( )
  {
          string  name = "Dot Net Extension"
          System.Console.WriteLine( name.myString());
   }
}


Output:
my string is: Dot Net Extension