Friday, November 29, 2013

Try out- GC.Collect executed in Separate Thread

Garbage collection works in a separate thread. Want to check this out.

 

Execute the following code in a Console Project.

 

using System;
using System.Threading;


 

namespace Demo {
    class Program {
        public static void Main(string[] args) {
            Log("Calling Test");
            Test();
            //GC.Collect(0, GCCollectionMode.Forced);
            Thread.Sleep(2000);
            Log("Called Test");
        }

        public static void Test() {
            Person p = new Person();
            p = null;

        }

        public static void Log(string s) {
            Console.WriteLine("In Thread {0}({1})- {2}", Thread.CurrentThread.Name, Thread.CurrentThread.ManagedThreadId, s);
            Thread.Sleep(2000);
        }
    }

    public class Person {
        public Person() {
            Program.Log("Person");
        }
        ~Person() {
            Program.Log("~Person");
        }
    }
}

 

You can expect an output showing some logs in a main thread and the destructor log in a separate thread. Garbage collection is done automatically while the program exists as it a small program and does not usually do a collection in between the program.

To check the forced collection, uncomment the following line in main.

//GC.Collect(0, GCCollectionMode.Forced);

Monday, July 15, 2013

LINQ 11- Filtering with Where Clause

One of the important operation in list of values is filtering. in LINQ filtering can be done with where clause or Where extension method.

 

Where clause receives value of each element and needs an expression that returns a boolean value based on the input element. Result will be the list of elements which results true while evaluating the where clause.

 

Sample 1

Extension Method

int[] numbers = new int[] { 1, 2, 3, 4, 5 };
IEnumerable<int> selected = numbers.Where(number => number > 2);

LINQ

int[] numbers = new int[] { 1, 2, 3, 4, 5 };
IEnumerable<int> selected =

    from number in numbers where number > 2 select number;

Sample 2

Extension Method

IEnumerable<Employee> managers = employees.Where(employee => employee.Role==”Manager”);

LINQ

IEnumerable<Employee> managers =

    from employee in employees

    where employee.Role==”Manager”

    select employee;

Thursday, July 11, 2013

LINQ 10- Projection/Select- 4

LINQ statements are simple like SQL, with minor changes. One of the important change is the Select clause comes later in LINQ. Examples shown in previous posts can be rewritten as follows.

 

Query 1

Extension Method

IEnumerable<int> selected = numbers.Select(number => number);

                            ------- ------ ------    ------

                            Part1   Part2  Part3     Part4

LINQ

IEnumerable<int> selected = from number in numbers select number;

                                 ------    ------- ------ ------

                                 Part3     Part1   Part2  Part4

Query 2

Extension Method

IEnumerable<int> selected = numbers.Select(number => number * 2);

                            ------- ------ ------    ----------

                            Part1   Part2  Part3     Part4

LINQ

IEnumerable<int> selected = from number in numbers select number * 2;

                                 ------    ------- ------ ----------

                                 Part3     Part1   Part2  Part4

Query 3

Extension Method

IEnumerable<string> selected =

    numbers.Select(number => (number * 2).ToString());

    ------- ------ ------    -----------------------

    Part1   Part2  Part3     Part4

LINQ

IEnumerable<string> selected =

    from number in numbers select (number * 2).ToString();

         ------    ------- ------ -----------------------

         Part3     Part1   Part2  Part4

Query 4

Extension Method

IEnumerable<string> selected =

    employees.Select(employee => employee.Name);

    --------- ------ --------    -------------

    Part1     Part2  Part3       Part4

LINQ

IEnumerable<string> selected =

    from employee in employees select employee.Name;

         --------    --------- ------ -------------

         Part3       Part1     Part2  Part4

 

Here the

Part1 is the source on which the LINQ is to be executed

Part2 is the operation to be executed, here the transformation

Part3 is the alias name to be used for each item in the source

Part4 is the transformation to be applied, it can be any complex expression returning a single value

Sunday, July 07, 2013

LINQ 10- Projection/Select- 3

Lazy loading

Linq does few things in background for better performance. One of the important thing is lazy loading. Linq statements or methods are not executed immediately in the very statement. To verify this we can use the following sample class.

public class Employee {
    private string name;
    public string Name {
        get {
            Console.WriteLine("Name Get ");
            return name;
        }
        set {
            name = value;
        }
    }
}

 

In the above code, whenever the Employee name is retrieved it will print the message “Name Get” in the console.

Following code uses the above Employee class for LINQ.

Employee[] employees = new Employee[] {
    new Employee { Name = "John" },
    new Employee { Name = "Bill" },
    new Employee { Name = "Steve" } };
IEnumerable<String> selected = employees.Select(employee => employee.Name);

foreach (String item in selected)
    Console.WriteLine(item);

 

  • In the first statement, we have declared 3 Employees.
  • In the second statement, employee.Name is retrieved from the collection. If the Select method has completed its work in that statement itself, it will get all 3 names and it should print 3 “Name Get” messages. But, it will not, as it is just stores, what needs to be done and not actually doing it.
  • Next, the for each statement prints each names. Meanwhile, to print the names, names should be retrieved from the previous statement. But due to lazy loading,  names are retrieved during MoveNext method’s execution (implicitly done in foreach statement)

Output will be

Name Get
John
Name Get
Bill
Name Get
Steve

Above output clearly shows the Select is not immediately executed.

 

If we print the Type name of “selected” variable, we can see how this is done.

We can use the following statement to check this.

Console.WriteLine(selected.GetType().FullName);

Output

System.Linq.Enumerable+WhereSelectArrayIterator`2[Employee, String]

So during the execution .Net stores the transformation information in the WhereSelectArrayIterator.

WhereSelectArrayIterator class is an internal class, so cannot see the details using Object Browser, but, we can see the details using reflection. We can see this in further posts.

 

We can force the execution of LINQ statements to complete using some other LINQ extensions. Some of them are,

  • ToArray
  • ToList
  • Count

Example

Employee[] employees = new Employee[] {
    new Employee { Name = "John" },
    new Employee { Name = "Bill" },
    new Employee { Name = "Steve" } };
List<String> selected = employees.Select(employee => employee.Name).ToList();

foreach (String item in selected)
    Console.WriteLine(item);

Output

Name Get
Name Get
Name Get
John
Bill
Steve

Tuesday, July 02, 2013

LINQ 10- Projection/Select- 2

IEnumerable’s extension method Select, automatically identifies the input and output type. Input and output types are not restricted.

So Select method is powerful enough to transform one object to another. We already have seen one example in  “LINQ 10- Projection/Select- 1” which transforms an integer array to string Enumerable.

 

Following statement extracts the Name from Employee object.

IEnumerable<String> selected = employees.Select(employee => empoyee.Name);

 

Here Employees is the source IEnumerable witch generic type argument Employee. So TSource is Employee.

Transformation function gets the Name from Employee and returns it. So TResult is String.

 

Even we can transform a class object to another class object

IEnumerable<Manager> selected = employees.Select(employee => new Manager() {
    ID = employee.ID,
    Name =  employee.Name
});

 

Above statement transforms a list of Employee objects to List of Manager Objects

Sunday, June 30, 2013

LINQ 10- Projection/Select- 1

Select method provides a way to transform each element to a desirable format.

Following code does nothing but gives a enumerable list of the source.

int[] numbers = new int[] { 1, 2, 3, 4, 5 };
IEnumerable<int> selected = numbers.Select(number => number);

 

Let try a simple transformation like getting the numbers doubled

int[] numbers = new int[] { 1, 2, 3, 4, 5 };
IEnumerable<int> selected = numbers.Select(number => number * 2);
foreach (var item in selected) {
    Console.WriteLine(item);
}
Console.ReadKey();

 

Above code returns a Enumerable set of integers with values doubled from the source.

So you will get result 2,4,6,8,10

 

Select method is declared in System.Linq.Enumerable class as

public static IEnumerable<TResult> Select<TSource, TResult>

(this IEnumerable<TSource> source,

Func<TSource, TResult> selector);

 

Here TSource is automatically identified from the input enumerable. As we are using Integer Array, TSource is identified as Integer.

 

TResult is identified from the delegate or lambda expression passed to the method. As we are returning just the doubled number TResult is also identified as Integer.

 

Consider the following example which returns a String.

int[] numbers = new int[] { 1, 2, 3, 4, 5 };
IEnumerable<String> selected = numbers.Select(number => (number * 2).ToString());
foreach (String item in selected) {
    Console.WriteLine(item);
}
Console.ReadKey();

 

As we are returning the string TResult is identified as String, hence the select returns IEnumerable<String>

Tuesday, June 25, 2013

LINQ 09- LINQ Extensions

As we discussed earlier in "LINQ 08- IEnumerable", LINQ works with IEnumerable interface along with many extension methods. These extension methods are available in System.Core assembly in .Net Framework 4.0. You can find several extension methods available in the class System.Linq.Enumerable

 

So If you are going to use LINQ queries, you have to add System.Core as a reference and add “using Sytsem.Linq” to your imports.

 

Reference: Enumerable Class

Wednesday, June 19, 2013

LINQ 08- IEnumerable

LINQ is designed to work with collections. Common use of collection is iterating through them to read, filter and manipulate them.

Following diagram shows the flow which is commonly used for reading all items with IEnumerable

IEnumerable flow

 

Foreach loop uses the same logic to iterate through items in collections. Behind the scenes .Net  uses IEnumerable for iterating through collections. All the collection classes (from arrays to generic lists) are implemented using IEnumerable. So IEnumerable interface is unavoidable for every .Net programmer.

 

LINQ extends the concept of IEnumerable with extension methods to provide LINQ queries. Even without LINQ, the extension method provides many collection operations like searching, transforming, grouping and ordering using IEnumerable interface.

 

Sample Code

var a = new int[] { 1, 2, 3, 4, 5 };
var e = a.GetEnumerator();
while (e.MoveNext()) {
    Console.WriteLine(e.Current.ToString());
}

Wednesday, June 12, 2013

LINQ 07- Anonymous Types

Anonymous types allows users to create objects without creating classes. In many cases, we may need to store compound related data, but that will be referred in within a particular method. In .net framework 2.0, anonymous types, we have to write a simple classes and properties to achieve this.

Anonymous types works with Automatic Type Inferencing, Auto Implemented properties and Object Initializers

Example

var e = new {
    ID = 10,
    Name = "John",
    Designation = "Software Engineer",
    Age = 25
};

 

C# Compiler implicitly creates a type and uses it.

Notes:

  • As the type name is unknown, automatic type inferencing should be used.
  • As Automatic type inferencing is the only option to declare anonymous types, it can be used within code blocks only, can not be used as type member
  • Anonymous types with same properties with same property types are considered as equal.

Hence

var e = new {
    ID = 10,
    Name = "John",
    Designation = "Software Engineer",
    Age = 25
};

and

var f = new {
    ID = 11,
    Name = "Mike",
    Designation = "Software Engineer",
    Age = 26
};

are considered as same type.

  • Arrays with anonymous type elements can be created as

var e = new[]{ new {
    ID = 10,
    Name = "John",
    Designation = "Software Engineer",
    Age = 25
},
new {
    ID = 11,
    Name = "Mike",
    Designation = "Software Engineer",
    Age = 26
}};

  • It is not possible to refer property values within declaration. Following statement is WRONG.

var e = new {
    ID = 10,
    FirstName = "John",
    LastName ="Carter",
    FullName = FirstName + " " + LastName,
    Designation = "Software Engineer",
    Age = 25
};

Saturday, June 08, 2013

LINQ 06- Automatic type inferencing

Automatic type inferencing allows you to declare variables without specifying the type before the variable name.

You don’t have to specify the exact type when initializing variable with a type specific value

Example:

Instead of

int i = 10;

you can use

var i = 10;

 

Same can be used for objects to

var e = new Employee();

In case you want a base class type to be used for the variable, you can use casting.

var p = (new Employee()) as Person;

 

Note:

    • This can only be used inside a code block (methods, property get set blocks, etc)

Wednesday, June 05, 2013

LINQ 05- Object Initializers

Object initializer provides a shortcut to initialize an object with property values.

Considering the following class.

public class Employee {
    public Employee() {
       
    }
    public Employee(int id) {
        this.ID = id;
    }
    public int ID { get; set; }
    public string Name { get; set; }
    public string Designation { get; set; }
}

 

With object initializer, we can initialize an Software Engineer John with ID 10, in one statement.

var e = new Employee() {
    ID=10,
    Name="John",
    Designation="Software Engineer"
};

or

var e = new Employee(10) {
    Name="John",
    Designation="Software Engineer"
};

Second example shows the initialization of a class with parameterized constructor.

Tuesday, June 04, 2013

LINQ 04- Auto implemented properties

While writing properties to classes, mostly we declare a variable and expose it through properties.

public class Employee {
    private int id;
    public int ID {
        get { return id; }
        set { id = value; }
    }
}

Auto implemented properties help to reduce the code by implicitly doing the field declaration, return and assignment through get and set of the properties.

 

With auto implemented properties, above code can be optimized as

public class Employee {
public int ID { get; set; }
}

Notes:


Properties type is used for the implicit variable.


Implicit variable will be declared as private.


Automatically implemented properties must define both get and set accessors


We can use separate access modifier for get or set. (public int ID { get; private set; })

Sunday, June 02, 2013

LINQ 03: Lambda expression

Lambda expressions provides a simpler mechanism, to create or pass delegates without creating a separate methods to be referred.

In other words, we can say lambda expressions are inline functions

 

For example consider the following

we have a delegate CalcDelegate with two integer parameters

delegate void CalcDelegate(int a, int b)

we have a method Calc requires the CalcDelegate to be passed.

int Calc(CalcDelegate, int m, int n)

To create an Add operation with this, we will create a add method

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

So that we can call the Add using Calc

Calc(Add, 1, 5);

But for using in a single location, we have to create a function for this (without lambda expressions)

With lambda expressions we can simplify this with the inline method

Calc( (a,b) => a+b, 2, 5);

 

Lambda expressions are simple to create

left side of => is the parameter section

right side of => is the body section

 

Parameter section

  • when no parameters are required for the delegate, we can use ()
    • Example: ()=> Console.WriteLine(‘no parameter method invoked’)
  • when only one parameter is required for the delegate, we can use paramName or (paramName)
    • Example: a=> a*2
  • when more that one parameters are required for the delegate, we can use (paramName1, patamName2, …)
    • Example: (a, b) => a +b
  • Parameter types are inferred with automatic type inferencing
  • When the automatic does not help, we can use explicit declaration (paramType1 paramName1, paramType2 paramName2, …)
    • Example: (int a, int b) => a + b

Body section

  • When the function has single statement, no need for open and close braces, but we can use them optionally.
    • Example: a=> a*a
  • When the function has multiple statements we should enclose them within open and close braces
    • Example: a=> { var b=a*a;  return b;}

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);
}

Saturday, April 06, 2013

Calling a function after .Net Ajax UpdatePanel Partial Postback

In case you need to call a javascript code blocks after a Partial Postback using Update Panel, you can use the following code block after window load.

 

var v= Sys.WebForms.PageRequestManager.getInstance()

 

v.add_endRequest( function ()

          {

               // callback code goes here

          }

     );

 

The callback code will be called after a Partial PostBack. In case the callback method should also be called during first time page load, you can move the callback code to a method and call it in two places as mentioned below

 

var v= Sys.WebForms.PageRequestManager.getInstance()

MyCallBackCode();

v.add_endRequest( function ()

          {

               MyCallBackCode();

          }

     );

 

function MyCallBackCode()

{

// callback code goes here

}

 

To execute this on window load you can use jQuery

 

$(document).ready(function(){

     var v= Sys.WebForms.PageRequestManager.getInstance()

     MyCallBackCode();

     v.add_endRequest( function ()

               {

                   MyCallBackCode();

               }

          );

 

     function MyCallBackCode()

     {

          // callback code goes here

     }

});

Thursday, March 28, 2013

Factory Method Pattern

Factory method pattern provides a way for extensibility. It is a creational pattern. Factory Method pattern, is a method that can be used to create one of the Implemented contracts (Instance of a Concrete class) among choices. Usually creational patterns hides the instantiation from the user.

 

Scenario:

You want to provide choice to your class users in a specific situation. Those choices fulfils the contract in different ways.

 

Basic Solution For this Scenario:

For example you have a part of code that has to add or multiply two values based on a configuration. You will implement this like

  • You will write two methods for Add and Multiply.
  • You will ask you user to call you methods based on the configuration.

 

void Calc(int n1, int n2)

{

    char op= GetOpConfig();

    int r;

    switch(op)

    {

    case ‘+’:

        r=Add(n1, n2);

    case ‘*’:

        r=Multiply(n1, n2);

    }

    Display(r);

}

 

Problem:

User has to change the code when you are implementing new methods like Subtract. User has to add another case to implement this.

 

void Calc(int n1, int n2)

{

    char op= GetOpConfig();

    int r;

    switch(op)

    {

    case ‘+’:

        r=Add(n1, n2);

    case ‘*’:

        r=Multiply(n1, n2);

    case ‘-’:

        r=Subtract(n1, n2);

    }

    Display(r);

}

 

So you both has to alter the code when the requirement changes.

 

Solution:

You can use Factory Method pattern to solve this issue.

  • Understand the scenario and bring up a common contract from it (basically with a class, interface or delegate). The common contract should be abstract superset.
  • Here what I mean by superset is, it should cover all the requirements.
  • Consider you are implementing a negation operation that requires only one operand. As you are making it common, you have to use the second operator in the abstract but leave it ignored during negation implementation.
  • Consider you are implementing ternary operation that requires three operators, then the super class should cover all.
  • If you have completed the factory method with two operators and you have a new requirement to support ternary operator that is almost a BREAKING CHANGE.
  • Implement your different implementations of contract with that superset’s abstract.
  • Implement a factory method, that receives a code for a specific instance (which is given to the user in a document) and returns instance of implemented contract based on the received code.
  • Document the usage with following details and give it to the user.
  • Contract Details such as properties and methods defined in the contract

Factory method parameters and possible values Factory method is implemented.

 

Implementation:

Ok. Lets implement a sample for the above requirements.

 

Understanding the scenario

  • We are going to provide the users with a way to calculate.
  • We want to make it extensible so that new operators can be added later.

 

Creating Common Contract

 

  • Calculation basically requires two operands
  • Calculation will return one result.
  • For unary operator, user won’t give second operand. Implemented contract will ignore the second operator.

 

public abstract class Operation {
    public int Num1 { get; set; }
    public int Num2 { get; set; }
    public int Result { get; set; }
    public abstract void Calc();
}

 

Implementing Contract

  • Above contract can be implemented for Add and Multiply as follows

public class Add : Operation {
    public override void Calc() {
        Result= Num1 + Num2;
    }
}

public class Multiply : Operation {
    public override void Calc() {
        Result = Num1 * Num2;
    }
}

 

Implementing Factory Method

 

  • Factory method can be implemented with a single static method as coded below

public class Calculation {
    public static Operation GetOperation(char op) {
        switch (op) {
            case '+': return new Add();
            case '*': return new Multiply();
        }
        return null;
    }
}

 

 

Using Factory Method

 

  • Calling factory method is easy. It is just like calling regular methods.

var cal = Calculation.GetOperation(op);
cal.Num1 = n1;
cal.Num2 = n2;
cal.Calc();
var ret = cal.Result;

 

  • value for op can be hard coded or from a configuration.

 

Extending with Factory Method Pattern

  • New implementation can be added anytime without affecting the users code.
  • Adding a subtract will be easy as mentioned below

public class Subtract : Operation {
    public override void Calc() {
        Result = Num1 - Num2;
    }
}

  • Adding a simple case block will be enough in Factory method.

case '-': return new Subtract();

 

We can implement the same using interfaces or delegates as contracts

Friday, March 22, 2013

Html5- Geolocation API- With Google Maps

Following is a stand alone HTML5 code that shows a simple sample for Html5 Geolocation API

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>     <title>Location Sample</title>     <script src="http://maps.google.com/maps/api/js?sensor=true"></script>     <script>         window.onload = Window_OnLoad;                  function Window_OnLoad() {             var lbl = document.getElementById('lblLocation');             if (navigator.geolocation) {                 lbl.innerHTML = "Geolocation supported";                 navigator.geolocation.getCurrentPosition(                     function (location) {                         lbl.innerHTML = location.coords.latitude + "," + location.coords.longitude;                         ShowGoogleMap(location.coords);                         AddMarker(location.coords);                     }                     );             }             else {                 lbl.innerHTML = "Geolocation not supported";             }         }         var map;                 function ShowGoogleMap(Coords) {             var mapOptions = {                 zoom: 15,                 center: new google.maps.LatLng(Coords.latitude, Coords.longitude),                 mapTypeId: google.maps.MapTypeId.ROADMAP             };             var mapDiv = document.getElementById("divMaps");             map = new google.maps.Map(mapDiv, mapOptions);         }         function AddMarker(Coords, Title) {             var markerOptions = {                 position: new google.maps.LatLng(Coords.latitude, Coords.longitude),                 map: map,                 title: Title,                 clickable: true             };             var myLocationMarker = new google.maps.Marker(markerOptions);         }             </script>
</head>
<body>     <span id="lblLocation"></span>     <div id="divMaps" style="width:400px; height:400px"></div>
</body>

</html>

Monday, March 18, 2013

Singleton Pattern

Singleton is a Creational Design Pattern. Often we may need to group a related members into a single class but only one instance of a class is enough for example Helper classes. We can solve this problem with many methods. A simple method would be using a static class with static methods.

 

// Singleton class
public static class Singleton {

    private static Data data;
    public static void commonMethod1() {
    }
    public static void commonMethod2() {
    }
}

 

As we marked the Singleton class as static, an instance to the Singleton class cannot be created. To access the singleton methods, we can directly invoke them using the class name as the methods are also static.

Singleton.commonMethod1();

 

Disadvantage of this implementation is we don’t have the control over the instantiation and destruction of this class as everything is defined as static.

 

To overcome this, we can implement the singleton pattern as below.

Saturday, March 09, 2013

Extension Methods

Extensions methods allows you to add methods to an existing classes without modifying or inheriting it.

 

Previously we were adding static methods outside the class and calling it by passing the object as a parameter.

 

using System;

class Program {
    static void Main(string[] args) {
        var emp = new Employee() { Id = 1, Name = "John" };
        SampleExtensions.Print(emp);
    }
}

public class Employee {
    public int Id { get; set; }
    public string Name { get; set; }
}

public static class SampleExtensions {
    public static void Print(Employee emp) {
        Console.WriteLine("Employee: " + emp.Id.ToString() + "-" + emp.Name.ToString());
    }
}

 

We can upgrade this code using Extension methods. All we need is to

  • Create a static class
  • Add static method
  • Add this prefix before the first parameter declaration

 

Note: Extension methods only works with reference types

 

using System;

class Program {
    static void Main(string[] args) {
        var emp = new Employee() { Id = 1, Name = "John" };
        emp.Print();
    }
}

public class Employee {
    public int Id { get; set; }
    public string Name { get; set; }
}

public static class SampleExtensions {
    public static void Print(this Employee emp) {
        Console.WriteLine("Employee: " + emp.Id.ToString() + "-" + emp.Name.ToString());
    }
}

This in fact, improves the readability of the code, so it is easy to understand.

Saturday, March 02, 2013

Including JQuery in ASP.Net Project

JQuery can be included in your asp.net web application or web site using any one of the following methods.

  • Using Nuget Package Manager
    • In Visual Studio, Open Nuget package manager console, (Tools\Libarary Package Manager\Package Manager Console)
    • It will open a tool window
    • In that, type following command to install jquery
      • install-package jquery
  • Downloading from jquery from Official JQuery site
    • Go to official jquery site, (www.jquery.com)
    • Click on the download jquery button to download the latest verion.
    • Page will be directed to download page
    • In the jquery can be downloaded from any one of following mode
      • uncompressed- development
      • compressed- production
    • Include the downloaded file to the application using add existing item in that project.

JQuery

JQuery is a javascript library which basically designed to work on all the browsers.

JQuery contains many modules to simplify our day to day coding work.

 

More information can be found in Official JQuery Site.

 

JQuery can be used in any html based applications. As it is a javascript library, we can use it with .Net, Java, Php etc.. based web applications.

 

Current version of JQuery is 1.9.1

Microsoft Releases Microsoft ASP.NET and Frameworks 2012.2

Microsoft today released Microsoft ASP.NET and Frameworks 2012.2.

 

Link:

 http://www.microsoft.com/en-us/download/details.aspx?id=36829&WT.mc_id=rss_alldownloads_devresources

 

This release updates ASP.NET and includes updates to Visual Studio 2012 or Visual Studio 2012 Web Express.

For more information see instructions in the release notes at http://go.microsoft.com/fwlink/?LinkID=275132.

Features and updates:

ASP.NET Web API

  • ASP.NET Web API now includes support for OData endpoints that support both ATOM and JSON-light formats. With OData you get support for rich query semantics, paging, $metadata, CRUD operations, and custom actions over any data source. Read more about ASP.NET Web API OData support at http://go.microsoft.com/fwlink/?LinkID=271141.
  • New built-in tracing functionality lets you easily diagnose problems with Web API whether you’re running in Visual Studio or on Windows Azure. Tracing output from Web API is automatically written to the Visual Studio output window, IntelliTrace, and any other trace listener that you would like, including Windows Azure Diagnostics.
  • The output shows the full Web API pipeline for all requests, including any exceptions or errors that occur, what controller and action were selected, model binding, the format that was negotiated, and the response.
  • Updated Web API projects now contain a link to an automatically generated help page that shows how to call your web API.
  • The help page shows all of your API endpoints, the HTTP verbs they support, parameters, and sample request and response messages.
  • You can customize the help page as you like. For more information see http://go.microsoft.com/fwlink/?LinkID=285385.

ASP.NET SignalR

  • ASP.NET SignalR is a new library for ASP.NET developers that simplifies the process of adding real-time web functionality to your applications.
  • Real-time web functionality is the ability to have server-side code push content to connected clients instantly as it becomes available.
  • You may have heard of the HTML5 WebSocket API that enables efficient bidirectional communication between the browser and server. SignalR uses Websockets when it is supported by the browser and the server, and gracefully falls back to other techniques and technologies when it is not. Either way, your application code stays the same.
  • SignalR provides a simple API for creating server-to-client remote procedure calls (RPC) that call JavaScript functions in client browsers from server-side .NET code. SignalR also includes API for connection management (for instance, connect and disconnect events), grouping connections, and authorization. Read more about SignalR at http://go.microsoft.com/fwlink/?LinkID=285432.

ASP.NET MVC

  • The new Facebook Application template makes writing Facebook Canvas applications easy.
  • In a few simple steps, you can create a Facebook application that gets data from a logged in user and integrates with their friends.
  • The template includes a new library to take care of all the plumbing involved in building a Facebook app, including authentication, permissions, accessing Facebook data and more.
  • This lets you focus on building the business logic in your app.
  • The Facebook apps you can build with this new template are hosted on the web and displayed inside the Facebook chrome via an iframe.
  • A new Single Page Application MVC template allows developers to build interactive client-side web apps using HTML 5, CSS 3, and the popular Knockout and jQuery JavaScript libraries, on top of ASP.NET Web API.
  • The template creates a “todo” list application that demonstrates common practices for building a JavaScript HTML5 application that uses a RESTful server API. You can read more at http://go.microsoft.com/fwlink/?LinkID=285433.

Wednesday, February 27, 2013

Threading: 13- Multi-threading

When one programs uses multiple threads to accomplish its tasks, it is called multithreading.

Multithreading doesn’t guaranties the sequence of execution between threads.

Sample Code

Threading: 12- ThreadPool

Managed thread pool, provides efficient use of threads with a pool of background threads managed by system.

 

Example Code

Microsoft Releases Internet Explorer 10 for Windows 7

Microsoft today released Internet Explorer 10 for Windows 7

Find below the download links

 

Internet Explorer 10 for Windows 7 32-bit Edition and Windows Server 2008 R2 32-bit Edition

http://www.microsoft.com/en-us/download/details.aspx?id=36808&WT.mc_id=rss_alldownloads_devresources

 

Internet Explorer 10 for Windows 7 64-bit Edition and Windows Server 2008 R2 64-bit Edition

http://www.microsoft.com/en-us/download/details.aspx?id=36806&WT.mc_id=rss_alldownloads_devresources

Tuesday, February 26, 2013

Threading: 11- Background & Foreground threads

Managed thread can be either background or foreground. Differences are listed below.

If all the foregrounds are completed, background threads will be automatically closed and application will be closed. By default all applications will have a main foreground thread.

 

Background threads can be created by setting Thread’s IsBackground property to true. By default, a thread will be created as foreground thread.

 

var th = new Thread(Greet);
th.Name = "Greeting";
th.IsBackground = true;

Asp.net and web tools 2012.2 released

Asp.net and web tools 2012.2 is released and available on the web.
Download link: http://go.Microsoft.com/fwlink/?linkid=282650

Monday, February 25, 2013

Threading: 10- Assigning a name to a thread

We can assign a meaningful name to the thread after creating the thread and before starting the thread.

var th = new Thread(Greet); // Create new thread
th.Name = "Greeting";

Threading: 09- Getting current thread information

Information about current thread can be obtained using Thread.CurrentThread static property.

Thread.CurrentThread returns the Thread Object related to current thread.

Thread object gives the following information about the thread.

  • Name
  • ManagedThreadId
  • IsBackground
  • IsThreadPoolThread
  • IsAlive
  • Priority
  • ThreadState

Sample Code:

using System;
using System.Threading;

// Current thread info

class Program {
    static void Main(string[] args) {
        Console.WriteLine("Main Started");
        var th = new Thread(Greet); // Create new thread
        th.Start(new object[] { "Bob", "Good Morning" });  // Execute Greet method in the created thread
        Console.ReadKey();
    }

    private static void Greet(object info) {
        Console.WriteLine("Hi {0}, {1}!", (info as object[])[0], (info as object[])[1]);
        Console.WriteLine("\tThread Name: " + Thread.CurrentThread.Name);
        Console.WriteLine("\tThread Id: " + Thread.CurrentThread.ManagedThreadId);
        Console.WriteLine("\tIs Background: " + Thread.CurrentThread.IsBackground);
        Console.WriteLine("\tIs ThreadPool Thread: " + Thread.CurrentThread.IsThreadPoolThread);
        Console.WriteLine("\tIs Alive: " + Thread.CurrentThread.IsAlive);
        Console.WriteLine("\tPriority: " + Thread.CurrentThread.Priority);
        Console.WriteLine("\tThread State: " + Thread.CurrentThread.ThreadState);
    }
}

Output

Main Started
Hi Bob, Good Morning!
        Thread Name:
        Thread Id: 11
        Is Background: False
        Is ThreadPool Thread: False
        Is Alive: True
        Priority: Normal
        Thread State: Running

Sunday, February 24, 2013

Threading: 08- Aborting a running thread

A running thread can be aborted using Thread.Abort method. When we abort a thread, a thread abort exception will be thrown in that thread.

 

using System;
using System.Threading;

// Thread.Abort

class Program {
    static void Main(string[] args) {
        Console.WriteLine("Main Started");
        var th = new Thread(Greet); // Create new thread
        th.Start(new object[] { "Bob", "Good Morning" });  // Execute Greet method in the created thread
        Thread.Sleep(500);
        th.Abort();
        Console.WriteLine("Main Completed");
        Console.ReadKey();
    }

    private static void Greet(object info) {
        try {
            Thread.Sleep(1000);
            Console.WriteLine("Hi {0}, {1}!", (info as object[])[0], (info as object[])[1]);
            Thread.Sleep(1000);
        }
        catch (ThreadAbortException) {
            Console.WriteLine("Greet Aborted");
        }
    }
}

 

Output:

Main Started
Main Completed
Greet Aborted

Saturday, February 23, 2013

Threading: 07- Waiting for a thread to complete, but just for a while, Thread.Join

We can wait for a thread to complete, but we cannot wait indefinitely sometimes. .Net allows us to wait for a thread to complete just for a while, using Thread.Join method.

Thread.Join method, receives a timeout in milliseconds and waits up to that period. If it is still running, it stops waiting and returns false, else returns true.

 

using System;
using System.Threading;

class Program {
    static void Main(string[] args) {
        Console.WriteLine("Main Started");
        var th = new Thread(Greet); // Create new thread
        th.Start(new object[] { "Bob", "Good Morning" });  // Execute Greet method in the created thread
        if (th.Join(800))
            Console.WriteLine("Greeting finished");
        else
            Console.WriteLine("Greeting is still running");
        Console.WriteLine("Main Completed");
        Console.ReadKey();
    }

    private static void Greet(object info) {
        Thread.Sleep(1000);
        Console.WriteLine("Hi {0}, {1}!", (info as object[])[0], (info as object[])[1]);
        Thread.Sleep(1000);
    }
}

 

Output:

Main Started
Greeting is still running
Main Completed
Hi Bob, Good Morning!

Threading: 06- Freezing a thread for a while- Thread.Sleep

We can make a thread sleep for a specific milliseconds. We can use this for testing the thread and asynchronous programming concepts and also we can use this to wait for a resource.

 

Example:

using System;
using System.Threading;

class Program {
    static void Main(string[] args) {
        Console.WriteLine("Main Started");
        var th = new Thread(Greet); // Create new thread
        th.Start(new object[] { "Bob", "Good Morning" });  // Execute Greet method in the created thread
        th.Join();
        Console.WriteLine("Main Completed");
        Console.ReadKey();
    }

    private static void Greet(object info) {
       Thread.Sleep(1000);
        Console.WriteLine("Hi {0}, {1}!", (info as object[])[0], (info as object[])[1]);
       Thread.Sleep(1000);
    }
}

 

Above thread will waiting for 1 second (1000 milliseconds) before printing the greetings and after printing the greetings

Threading: 05- Waiting for thread to complete- Thread.Join

We can wait for a thread to complete using the thread’s Join method.

 

using System;
using System.Threading;

class Program {
    static void Main(string[] args) {
        Console.WriteLine("Main Started");
        var th = new Thread(Greet); // Create new thread
        th.Start(new object[] { "Bob", "Good Morning" });  // Execute Greet method in the created thread
        th.Join();
        Console.WriteLine("Main Completed");
        Console.ReadKey();
    }

    private static void Greet(object info) {
        Console.WriteLine("Hi {0}, {1}!", (info as object[])[0], (info as object[])[1]);
    }
}

 

Join method will block the calling thread until the thread completes.

Threading: 04- Thread with multiple parameters without class or struct

Instead of creating a class to pass multiple parameters to a thread, we can use Object arrays to be passed to the method.

 

Example:

using System;
using System.Threading;

class Program {
    static void Main(string[] args) {
        Console.WriteLine("Main Started");
        var th = new Thread(Greet); // Create new thread
        th.Start(new object[] { "Bob", "Good Morning" });  // Execute Greet method in the created thread
        Console.WriteLine("Main Completed");
        Console.ReadKey();
    }

    private static void Greet(object info) {
        Console.WriteLine("Hi {0}, {1}!", (info as object[])[0], (info as object[])[1]);
    }
}

Threading: 03- Thread with multiple parameters

Thread class supports two types of methods

  • Method without parameter and return values- using ThreadStart delegate
  • Method with one object type parameter and without return values- using ParameterizedThreadStart delegate

To pass multiple values to Thread, we can create a small class to store multiple parameters and send it as the parameter

 

Example:

using System;
using System.Threading;

class Program {
    static void Main(string[] args) {
        Console.WriteLine("Main Started");
        var th = new Thread(Greet); // Create new thread
        th.Start(new GreetInfo() { Name = "Bob", Message = "Good Morning" });  // Execute Greet method in the created thread
        Console.WriteLine("Main Completed");
        Console.ReadKey();
    }

    private class GreetInfo {
        public string Name { get; set; }
        public string Message { get; set; }
    }

    private static void Greet(object info) {
        Console.WriteLine("Hi {0}, {1}!", (info as GreetInfo).Name, (info as GreetInfo).Message);
    }
}

Threading: 02- Thread with parameter

We can pass one argument to thread during thread start

 

using System;
using System.Threading;

class Program {
    static void Main(string[] args) {
        Console.WriteLine("Main Started");
        var th = new Thread(Greet); // Create new thread
        th.Start("Good Morning");  // Execute Greet method in the created thread
        Console.WriteLine("Main Completed");
        Console.ReadKey();
    }

    private static void Greet(object message) {
        Console.WriteLine("Hi, {0}!", message);
    }
}

 

  • Constructor of Thread class here, receives the method to be invoked using a delegate called ParameterizedThreadStart which is defined in BCL.
  • Signature of the parameterized thread start is defined in BCL as

public delegate void ParameterizedThreadStart(object obj);

  • During thread start we can pass value to the Thread

Output

Main Started
Main Completed

Hi, Good Morning!

 

Threading: 01- A Simple Thread

Program in the Sample 00 can be converted to utilize the thread as follows.

 

using System;
using System.Threading;

class Program {
    static void Main(string[] args) {
        Console.WriteLine("Main Started");
        var th = new Thread(Greet); // Create new thread
        th.Start();  // Execute Greet method in the created thread
        Console.WriteLine("Main Completed");
        Console.ReadKey();
    }

    private static void Greet() {
        Console.WriteLine("Hi, Good Morning!");
    }
}

 

  • Constructor of Thread class here, received the method to be invoked using a delegate called ThreadStart which is defined in BCL.
  • Console application by default run in Main thread.
  • During th.Start, runtime creates a new thread and starts the execution of Greet method in that thread.
  • So the line after th.Start will continue to execute while Greet method is being executed in a new thread.
  • Result will vary based on system performance.

Output

Main Started
Main Completed

Hi, Good Morning!

 

Threading: 00- Life without Thread

A Simple program without threading.

Project Type: Console Application
class Program {
    static void Main(string[] args) {
        Console.WriteLine("Main Started");
        Greet();
        Console.WriteLine("Main Completed");
        Console.ReadKey();
    }
    private static void Greet() {
        Console.WriteLine("Hi, Good Morning!");
    }
}
Above programs calls a static method “Greet” from Main method.
Output

Main Started
Hi, Good Morning!
Main Completed

0x80070020- Cannot Start Web Site, The process cannot access the file because it is being used by another process

Error:
Cannot Start Web Site
There was an error while performing this operation.
Details:
The process cannot access the file because it is being used by another process. (Exception from HRESULT: 0x80070020)

More details:
As we don’t get more information from the above error message, we have to use windows event log to obtain more details
If you open event log and navigate to system log, you can obtain the following two log entries

Event Log 1
Unable to bind to the underlying transport for [::]:80. The IP Listen-Only list may contain a reference to an interface which may not exist on this machine.  The data field contains the error number.
Event Log 2
The World Wide Web Publishing Service (WWW Service) did not register the URL prefix http://*:80/ for site 1. The site has been disabled. The data field contains the error number.

Fix:
Port 80 is already is in use.
We can change the IIS web site configuration to use another port.
We can identify the program which uses port 8 using the following command
> netstat –a –b
After that we can
  • configure that program to use another port
  • configure IIS to use another port
  • stop the program temporarily and start the IIS web site
  • Uninstall the program permanently if not required, and start the IIS web site.


















Friday, February 22, 2013

Unable to create the virtual directory. ASP.NET 2.0 has not been registered on the Web server.

Error:

Unable to create the virtual directory. ASP.NET 2.0 has not been registered on the Web server. You need to manually configure you Web server for ASP.NET 2.0 in order for your site to run correctly.

Fix:

Open Command Prompt in Admin mode

Navigate to C:\Windows\Microsoft.Net\Framework\

To identify the framework versions installed, type dir /ad

 

image

Navigate to the required framework folder

> cd v2.0.50727

Run asp.net registration tool

> aspnet_regiis /i

 

This will install the asp.net of the selected framework into IIS

 

Notes:

.Net framework 2.0, 3.0 and 3.5, uses CLR 2.0

.Net framework 4.0 and 4.5 uses CLR 4.0

Thursday, February 21, 2013

Installing Windows Authentication on IIS

Windows Authentication may not be installed in IIS in some machines, which might be useful debugging and other purposes.
To Install Windows Authentication on IIS, follow the following steps.

Search for “Turn on or off windows features” in Control Panel and Open it
  • Navigate to Internet Information Services/World Wide Web Services/Security
  • Mark Windows Authentication and other authentication modes, if required
  • Click on OK and wait for the installation to complete.
  • If you have already opened the IIS Manager (inetmgr), close and reopen it to see the changes



Verifying the installation
  • 6 IIS (Internet Information Services) Manager
  • Click the root (your machine name) in left side pane
  • In the content window Select IIS/Authentication and Open it
  • There you can see the installed Authentication modes




Following Authentication modifies are available in IIS on Windows 7

  • Basic Authentication
  • Digest Authentication
  • Windows Authentication

Following Authentication modes are installed by default on IIS

  • Anonymous Authentication
  • Forms Authentication
  • ASP.Net Impersonation


Wednesday, February 20, 2013

Unable to create the virtual directory. IIS is not installed on this computer

If you try to create a virtual directory from Visual Studio, you might get the following exception when you don’t have IIS installed.

Unable to create the virtual directory. IIS is not installed on this computer. To access local IIS Web sites, you must install the following IIS components:

      Internet Information Services
      IIS 6 Metabase and IIS 6 Configuration Compatibility
      ASP.NET
      Windows Authentication

In addition, you must run Visual Studio in the context of an administrator account.

To install IIS, Search for “Turn on or off windows features” in Control Panel.
Enable the following items and Click Ok to install the following items

  • Internet Information Services
  • IIS 6 metabase and IIS 6 configuration compatibility


Keywords: IIS, ASP.NET, Virtual Directory

Thursday, February 14, 2013

Console Application: Read File

Console Application: Read File
Following source code, contains a simple console application that gets a file name as a command line argument and prints its content in the console.

Source Code
using System;
using System.IO;

namespace ReadFile {
      class Program {
            static int Main(string[] args) {
                  if (args.Length == 0) {
                        Console.WriteLine("Please specify filename.");
                        return 0;
                  }
                  if (args.Length > 1) {
                        Console.WriteLine("Too many filenames specified.");
                        return 0;
                  }
                  if(! File.Exists((args[0])))
                        Console.WriteLine("Specify file not found.");
                  Console.WriteLine(File.ReadAllText(args[0]));
                  return 1;
            }
      }
}

Sample Output

Keywords:
Console Application, Command Line Arguments, File I/O

Monday, February 11, 2013

Want to learn F#?

Want to learn F#?
Microsoft has recently unvelied an updated vesion of www.tryfsharp.org. You can try learn fsharp interactively.

Attributes

Attributes
Attributes are details/data that can be attached to assemblies, types and members.
These attributes are specific to some programs/libraries and those libraries will use those attributes to do some processing.
For example, if we use XmlAttribute attribute apon a property, that will be writen as attribute in xml while we serialize the containing object using xml serialization.

Saturday, February 02, 2013

Asynchronous Programming

Now a days computers, have multiple cores in its processors, capable of executing multiple programming in parallel. Our code should be written to utilize the available resources to provide high performance processing to our clients. To support this .Net provided many classes written on top of windows low level API.

We can write parallel programming using following concepts

  • Threads
  • Thread Pools
  • Background Worker
  • Timers
  • Delegates with Begin Invoke

we can write asynchronous programming in following modes

  • Start a code execution in a new thread and let it complete its work.
  • Start a code execution in a new thread with a method (using delegate) to thread so that the method will call back our method after completion of the program.
  • Start a code execution in a new thread and do some other work and wait for the signal from the thread about the completion of the thread.

Delegates: Passing methods as Arguments

Methods can be passed to another methods through delegates.
Find below the sample for Passing methods as Arguments

Friday, February 01, 2013

Delegates: Using Delegates

Delegate definition

is almost similar to method declarations.

Syntax
<accessmodifier> delegate <methoddeclaration>
Example
public delegate int Calc(int a, int b);

Delegate variable declaration

is just like variable declaration

Syntax
<delegatetype> <delegatevariable>
Example
Calc c;

Method assignment to delegates

To use a delegate, we have to associate a method to the delegate instance.
Method to be associated to a delegate should match the signature of the delegate, which includes parameter types and return types

Example
public int Add(int x, int y)
{
return x+y;
}

Instantiating delegates

Syntax
new <delegatetype>(<methodname>)
Example
Calc c= new Calc(Add);

Using a delegates

Delegates are basically used to invoke a method which is associated to it.
.Net automatically adds few methods to it which enables us to invoke the method.

Here Invoke(int a, int b) will be added to Calc delegate.
Methods associated with the delegates can be invoked using the following syntax

Syntax
<delegatevariable>.Invoke(<parameters>)
Example
int x = c.invoke(10, 20);

There is another simple shortcut for this.
Syntax
<delegatevariable>(<parameters>)
Example
int x = c(10, 20);

Delegates: Introduction

A delegate is a class that can hold a reference to a method.

A delegate class has a signature, and it can hold references only to methods that match its signature.

Base class for all the delegates is Delegate.

When we declare a delegate, it implicitly defines a class derived from System.Delegate. It automatically adds few methods that supports method invocations.

Thursday, January 31, 2013

JSON Parsers in .Net 3.5

In .Net 3.5, there are 2 built in classes to support JSON serialization and deserialization.

  • System.Runtime.Serialization.Json.DataContractJsonSerializer, in System.ServiceModel.Web.dll
  • System.Web.Script.Serialization.JavaScriptSerializerm in System.Web.Extensions.dll

Sunday, January 20, 2013

Exception: Unable to cast object of type 'System.DBNull' to type 'System.String'.

Exception: When you try to convert a DBNull value to string this error will occur.

 

Description: DBNull is not equivalent to null. As DBNull is a different type. So it can not be converted to string.

 

Fix: ADO.NET mostly returns DBNull for database null value.

 

ToString() on DBNull value will return empty string

Convert.IsDBNull will return true if the given value is null

 

Example

 

String s = dr[“column”] ; // will throw error

String s= dr[“column”].ToString()l //will save empty string instead of null

String s= Convert.IsDBNull(dr[“column”])?null:dr[“column”]; // will save null for DBNull value

Wednesday, January 09, 2013

AndAlso & OrElse Operator

In VB.Net, there are two useful operators AndAlso & OrElse to Replace And & Or operators.

AndAlso & OrElse, operators are works as follows.

Both takes two operators.

When First one evaluated as false, AndAlso will not evaluate the second, as the result will surely result in false.

When First one evaluated as true, OrAlso will not evaluate the second, as the result will surely result in true.

 

This operation helps in one important situation, to check null and evaluate.

obj IsNot null AndAlso obj.Value=”value”

When obj is null, second condition will not be evaluated, and so, it will result in NullReferenceException.

Also, AndAlso and OrElse operators perform well than And and Or operators as the second operant will not be executed based on the result of first operand

??- Is Null Operator in C#

?? works as a Is Null operator in C#.

It can be used as

c = a??b

 

If a is non null value, a will be assigned to c, other wise b will be assigned to c.

 

?? operator is introduces in C# 2.0

Tuesday, January 08, 2013

Where is .Net 4.5 in C:\Windows\Microsoft.Net\Framework

Microsoft .Net Framework 4.5 is a replacement for Microsoft .Net Framework 4.0. It will overwrite the dlls in Microsoft .Net Framework 4.0. So it will use the following folder for its installation.

C:\Windows\Microsoft.NET\Framework\v4.0.30319