Consuming a WebService using LINQ

[dropcap]T[/dropcap]his article demonstrates how to query a Web Service’s public API using LINQ. For this article, I am using the Web Service located at GeoNames. Our code will query the CountryInfo webservice which accepts a Country Code and returns information like the country’s capital, population, currency and so on.
Check out the XML document returned from this service over here http://ws.geonames.org/countryInfo?
Let us get started:

 

Step 1: Create a Console Application. To this application, add a class named ‘Country’ and ‘CountryInfo’. The CountryInfo class has the following definition:
class CountryInfo
{
    public string CountryName { get; set; }
    public long Population { get; set; }
    public string Capital { get; set; }
    public string CurrencyCode { get; set; }
    public float AreaSqKm { get; set; }
}
Step 2: The Country class contains a SearchCountry method that returns an IEnumerable<CountryInfo> as shown below:

 

class Country
{
    public IEnumerable<CountryInfo> SearchCountry(string countryCode)
    {
        string uri = Uri.EscapeUriString(countryCode);
        string url = FormatUrl(uri);
        XDocument xdoc = XDocument.Load(url);
        IEnumerable<CountryInfo> results =
        from cntry in xdoc.Descendants(“country”)
        select new CountryInfo
        {
            CountryName = cntry.Element(“countryName”).Value,
            Capital = cntry.Element(“capital”).Value,
            AreaSqKm = Convert.ToSingle(cntry.Element(“areaInSqKm”).Value),
            Population = Convert.ToInt64(cntry.Element(“population”).Value),
            CurrencyCode = cntry.Element(“currencyCode”).Value
        };
        return results;
    }
    string FormatUrl(string cCode)
    {
        return “http://ws.geonames.org/countryInfo?” +
            “country=” + cCode +
            “&username=christlin”;
    }
}
The code is pretty straightforward. We first create the url with the search string using our FormatUrlmethod. We then use the XDocument.Load to create an XML document from the url. The last step is to loop through the XML document, populate the CountryInfo object and return the results.

 

Step 3: The final step is to code the Main() method to retrieve and display the results from the WebService. Here’s how the Main() method looks
static void Main(string[] args)
{
    Country country = new Country();
    string cntryCode = “IN”;
    IEnumerable<CountryInfo> cntryInfo = country.SearchCountry(cntryCode);
    foreach (var c in cntryInfo)
    {
        Console.WriteLine(“You searched for {0}. “ +
                        “The population of {0} is {1} and its capital is {2}. “ +
                        “The CurrencyCode for {0} is {3} and it’s area in Sq. Km is {4}”,
            c.CountryName, c.Population, c.Capital,
            c.CurrencyCode, c.AreaSqKm);
    }
    Console.ReadLine();
}

 

In the example above, we are passing in the country code ‘IN’ for India. We then loop through an object of IEnumberable<CountryInfo> and print the result on the console. The output looks similar to the following:

 

00130032015 Console Output

 

Well that was a simple example of how to query a webservice using LINQ. I hope you liked this article and I thank you for viewing it. The entire source code of this article can be downloaded here

[wpfilebase tag=file id=1 tpl=download-button /]

CSharp Interview Question: What is Action in CSharp

One of my friends called me after his interview as for a developer role in an esteemed organization. One of the question, interviewer asked him,

What is Action

 

After talking to him, I thought why not to blog about it? I am trying here to use minimum words and optimum code samples can be discussed with interviewer as answer of this question.

Action is type of delegate

  1. It returns no value.
  2. It may take 0 parameter to 16 parameters.

For example below Action can encapsulates a method taking two integer input parameter and returning void.

imgp10

So if you have method like below,

imgp9

You can encapsulate method Display in Action MyDelegate as below,

imgp8

An Action with one input parameter is defined in System namespace as below,

imgp7

Where in T is type of input parameter and T obj is value passed for the parameter.

Action with Anonymous method

You can work with Action and anonymous method as well. You can assign anonymous method to Action as below,

imgp6

Above code will print 9 as output.

Action with Lambda Expression

Like any other delegates, Action can be worked with lambda expression also as below,

imgp5

Above code will also print 9 as output.

Passing Action as input parameter

You can pass Action as parameter of a function also. Let us say you have a class

imgp4

And two functions called Display and Show to display Name and RollNumber of Student.

imgp3

Now you got a function where you need to pass either Display or Show. Or in other words you need to pass any function with the same signature of Display or Show. In that case you will be passing a delegate as input parameter to the function.

imgp2

You can call CallingAction method in Main as below,

imgp1

Above we are creating instance of Student class and one by one passing Display function and Show function as input parameter to CallingAction function. In CallingAction function, we are printing name of the function being passed as input parameter. On running you will get below output.

output action

I hope now you would be able to answer what is Action in simple words. I hope this post is useful. Thanks for reading.

 

Types of Constructor in .Net

Constructor is nothing but a function (with the same name as Class) and is used for initializing the members of a class whenever an class object is created. You can initialize the members with any value (as per member datatype) or with the default values through constructor.

If a class is not defined with the constructor then the CLR (Common Language Runtime) will provide an implicit constructor which is called as Default Constructor.

A class can have any number of constructors provided they vary with the number of arguments that are passed, which is they should have different signatures.

Some of the basic properties of Constructor are :

  1. Constructors do not return a value.
  2. Constructors can be overloaded.
  3. If a class is defined with static and Non-static constructors then the privilege will be given to the Non-static constructors.

Using the code

A. Public Constructor:

These are the most common, widely used and simple to implement constructors in Object Oriented Programming. The constructor is defined as public and get be called whenever a class is instantiated from external location of your program. Public Constructors is also known as default constructor of any class.

Also the Classes without a specified public constructor will have an implicit public constructor and maintained internally by CLR. Public constructor cannot be used in abstract class because public constructors always create instances of a type, and you cannot create instances of an abstract type.

[ads1]

using System;

class MyClass
{
 // defalut public constructor
 public MyClass()
 {
   Console.WriteLine("This is default constructor");
 }
 //public constructor with parameter
 public MyClass(int a)
 {
  Console.WriteLine("Value is "+a);
 }
}

class MyProgram
{
// start execution here from main method.
static void Main()
 {
 // initialize the class object
 MyClass myclass1 = new MyClass(); // default constructor
 MyClass myclass2 = new MyClass(5);
 Console.ReadLine();
 }
}

B. Protected Constructor:

A constructor is defined as protected in such cases where the base class will initialize on its own whenever derived types of it are created.

Means protected constructor is used with an abstract class where object initialization could not happen (because of abtract nature). The base class initialization happen only when derived class is initialized and call base class constructor.

 

public class Base
{
 protected Base() { }
 protected static void staticFoo() { }
 protected void instanceFoo() { }
}

public class Derived : Base
{
 Derived()
 : base() // initialize protected constructor through derived constructor
 { }
// start execution here from main method.
 void Main()
 {
  Base b = new Base(); // Compiler Error: Can not access protected member
  b.instanceFoo(); // Compiler Error: Can't call a protected instance method on a Base.
  Base.staticFoo(); // You call protected static method
  Derived d = new Derived();
  d.instanceFoo(); // Can call an inherited protected instance method on a Derived
  Derived.staticFoo(); // Can access static method of base class.
 }
}

C. Private Constructor :

Private constructor is a soul of Singleton pattern and used whenever we have to restrict the initializatio of class using ‘new’ keyword from outside world. The private modifier is usually used explicitly to make it clear that the class cannot be instantiated.

A private constructor is a special instance constructor. It is commonly used in classes that contain static members only. If a class has one or more private constructors and no public constructors, then other classes (except nested classes) are not allowed to create instances of this class.

 

public class MyClass
{
 private MyClass() { } // Private constructor
 public static int iCount;
 public static int IncrementCount()
 {
  return ++iCount;
 }
}
class MyTestClass
{
 // start execution here from main method.
 static void Main()
 {
  MyClass myclass = new MyClass(); // Compiler Exception: Can't initialize class because of private constructor
  MyClass.iCount = 100; // static variable directly accessible and initialized
  MyClass.IncrementCount(); // Direct call to static method
  Console.WriteLine("New value: {0}", MyClass.iCount);
 }
}

Private constructor plays a very special role in singleton design pattern. Singleton class is same as static class and both are used relatively for similar purpose (to provide only one “instance”) but still they have major difference.

  1. Singletons class can implement interfaces or derive from useful base classes.

  2. Singleton class object can be use as a parameter which is not possible for Static class.

  3. Singletons can be handled polymorphically without forcing their users to assume that there is only one instance.

 

class Program
{
static void Main(string[] args)
{
// get the class object without initializing through 'new' keyword
MyClass instance = MyClass.Instance;
}
}
/// <summary>
/// Sealed class. Implemented through Singleton pattern.
/// </summary>
public sealed class MyClass
{
// The internal static valiable of class object
static readonly MyClass _instance = new MyClass();
/// <summary>
/// This is a private constructor, meaning no outsiders have access.
/// </summary>
private MyClass()
{
// initailize the internal variables
}
/// <summary>
/// The Instance object of an MyClass class.
/// Return the _instance object everytime whenever the MyClass class is initialized.
/// </summary>
public static MyClass Instance
{
 get { return _instance; }
}
}

D. Static Constructor :

A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed only once.

It is called automatically before the first instance is created or any static members are referenced. Static Constructor is special in nature as a static constructor does not take access modifiers or have parameters and can’t access any non-static data member of a class.

A static constructor cannot be called directly and the user has no control on when the static constructor is executed in the program.

A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced. The static constructors are basically useful when creating wrapper classes for unmanaged code.

 

class Program
{
 static void Main(string[] args)
 {
 MyClass.foo(); // call the static member directly
 MyClass myclass = new MyClass();
 myclass.foo(10);
 Console.ReadLine();
 }
}

public class MyClass
{
 static int a;
 int b;
 // Static constructor:
 static MyClass()
 {
  a = 10; // initialize the static variable
  //b = 20; // Compile Exception : non-static member can't be access through static constructor
  Console.WriteLine("I am in static constructor");
 }
 // non-static constructor
 public MyClass()
 {
  a = 10; // non-static constructor can initialize both static and non-static members
  b = 20;
  Console.WriteLine("I am in non-static constructor");
 }
 public static void foo()
 {
  Console.WriteLine("I am in static foo");
 }
 public void foo(int a)
 {
  Console.WriteLine("I am in non-static foo");
 }
}

Something More

Constructor Overloading : A constructor with zero arguments is known as the default constructor. A constructor can take zero or more arguments as parameters. The program have multiple constructors in a class with different sets of signatures. Such constructors are known as “overloaded constructors”. The overloaded constructors of a class must differ in their number of arguments, type of arguments, and/or order of arguments. This gives the user the ability to initialize the object in multiple ways.

The class in the program shown below contains three constructors. The first is the default constructor, followed by the two argument constructors. Note that the constructors differ in their signature.

using system;
public class MyClass
{
 public MyClass()
 {
 //Default constructor
 }
 public MyClass(int sampleValue)
 {
 // This is the constructor with one parameter.
 }
 public MyClass(int firstValue, int secondValue)
 {
 // This is the constructor with two parameters.
 }
}

Constructor Chaining : 

Constructor chaining refers to the ability of a class to call one constructor from another constructor. In order to call one constructor from another, we use base (parameters) or : this (parameters) just before the actual code for the constructor, depending on whether we want to call a constructor in the base class or in the current class.

using system;
public class MyClass
{
public MyClass(): this(10)
{
// This is the default constructor
// calling base class constructor and passing value 10 as parameter
}
public MyClass(int firstValue)
{
// This is the constructor with one parameter.
}
}

Conclusion

The best practice is to always explicitly specify the constructor, even if it is a public default constructor. Proper design of constructors goes a long way in solving the challenges faced in class designs.

 

Local Variable Type Inference

Local Variable Type Inference

Local variables can be given an inferred “type” of var instead of an explicit type. The var keyword instructs the compiler to infer the type of the variable from the expression on the right side of the initialization statement. The inferred type may be a built-in type, an anonymous type, a user-defined type, or a type defined in the .NET Framework class library

With this feature, the type of the local variable being declared is inferred from the expression used to initialize the variable. This is achieved using the var keyword (familiar to those who work with scripting languages, but actually it is quite different). It allows us to write the following code:

 

var num = 50; 
var str = "simple string";
var obj = new myType();
var numbers = new int[] {1,2,3};
var dic = new Dictionary<int,myType>();

The compiler would generate the same IL as if we compiled:

int num = 50; 
string str = "simple string";
myType obj = new myType();
int[] numbers = new int[] {1,2,3};
Dictionary<int,myType> dic = new Dictionary<int,myType>();

Note that there is no un-typed variable reference nor late-binding happening, instead the compiler is inferring and declaring the type of the variable from the right-hand side of the assignment. As a result, the var keyword is generating a strongly typed variable reference.

Automatic Properties C#

[dropcap]A[/dropcap]utomatic properties used as a shorter way of defining a simple property which just sets and gets the value of a private member variable. Consider the following Code;

public class Point
 {
    private int _x, _y;
    public int X
    {
        get
        {
          return _x;
        }
        set
        {
          _x = value;
        }
    }
    public int Y
    {
        get
        {
          return _y;
        }
        set
        {
          _y = value;
        }
    }
}

The above code simply defining a class with basic properties. Now with the new C# compiler in Visual Studio .NET, we can write a shorter cleaner version using Automatic Properties which automatically generates the private fields with get/set operations :

public class Point
{
    public int X { get; set; }
    public int Y { get; set; }
}

The code above is even more readable and less verbose.
Note that this feature has nothing to do with LINQ. I just thought it would be appropriate to list it with the other new language features.

 

For more information see MSDN C# Programming Guide

Delegates C Sharp – The Complete Tutorial

Introduction

        Delegate is like a buzz word in C#.NET programming. In this article, I explain delegates, multicast delegates and their usage with the help of simple C# programs.

What is a Delegate?

        Delegate is a type which holds the method(s) reference in an object. It is also referred to as a type safe function pointer. The below figure illustrates the overview of Delegate.

Delegate is a type which holds the method(s) reference in an object. It is also referred to as a type safe function pointer.

Advantages

  • Encapsulating the method’s call from caller
  • Effective use of delegate improves the performance of application
  • Used to call a method asynchronously

Declaration

public delegate type_of_delegatedelegate_name()

Example:

publicdelegate int mydelegate(int delvar1,int delvar2)

Note

  • You can use delegates without parameters or with parameter list
  • You should follow the same syntax as in the method
    (If you are referring to the method with two int parameters and int return type, the delegate which you are declaring should be in the same format. This is why it is referred to as type safe function pointer.)

Sample Program using Delegate

public delegate double Delegate_Prod(int a,int b);
class Class1
{    
  static double fn_Prodvalues(int val1,int val2)    
  {        
    return val1*val2;    
  }    
  static void Main(string[] args)    
  {        //Creating the Delegate Instance        
    Delegate_Prod delObj = new Delegate_Prod(fn_Prodvalues);        
    Console.Write("Please Enter Values");        
    int v1 = Int32.Parse(Console.ReadLine());        
    int v2 = Int32.Parse(Console.ReadLine());        //use a delegate for processing        
    double res = delObj(v1,v2);        
    Console.WriteLine ("Result :"+res);        
    Console.ReadLine();    
  }
}

Explanation

Here I have used a small program which demonstrates the use of delegate.

The delegate “Delegate_Prod” is declared with double return type and accepts only two integer parameters.

Inside the class, the method named fn_Prodvalues is defined with double return type and two integer parameters. (The delegate and method have the same signature and parameter type.)

Inside the Main method, the delegate instance is created and the function name is passed to the delegate instance as follows:

Delegate_Prod delObj = new Delegate_Prod(fn_Prodvalues);

After this, we are accepting the two values from the user and passing those values to the delegate as we do using method:

delObj(v1,v2);

Here delegate object encapsulates the method functionalities and returns the result as we specified in the method.

Multicast Delegate

What is Multicast Delegate?

 

It is a delegate which holds the reference of more than one method.

Multicast delegates must contain only methods that return void, else there is a run-time exception.

Simple Program using Multicast Delegate

delegate void Delegate_Multicast(int x, int y);
Class Class2
{    
 static void Method1(int x, int y)    
 {        
   Console.WriteLine("You r in Method 1");    
 }     
 static void Method2(int x, int y)    
 {        
   Console.WriteLine("You r in Method 2");    
 }    
 public static void Main()  
 {      
   Delegate_Multicast func = new Delegate_Multicast(Method1);     
   func += new Delegate_Multicast(Method2);   
   func(1,2);             // Method1 and Method2 are called     
   func -= new Delegate_Multicast(Method1);     
   func(2,3);             // Only Method2 is called    
 }
}

Explanation

In the above example, you can see that two methods are defined named method1 and method2 which take two integer parameters and return type as void.

In the main method, the Delegate object is created using the following statement:

Delegate_Multicast func = new Delegate_Multicast(Method1);

Then the Delegate is added using the += operator and removed using the -= operator.

For more information see this MSDN C# Programming Guide.

Method Overriding in C#

Method overriding in C# is a feature like the virtual function in C++. Method overriding is a feature that allows you to invoke functions (that have the same signatures) that belong to different classes in the same hierarchy of inheritance using the base class reference. C# makes use of two keywords: virtual and overrides to accomplish Method overriding.

The figure below illustrates the overview of method overriding

 

Method Overriding of Shape ( Circle, Square and Triangle are basically Shapes but having different method to draw each shape)

The concept of method overriding is simple; Circle, Square and Triangle are basic shapes, But the method to draw each of them is different. So circle is a shape but we have set of rules to draw a circle, so we are creating unique method for drawing circle.

Method Overriding in C# – Examples

Let’s understand this through small examples.

P1.cs
class BC
{
  public void Display()
  {
     System.Console.WriteLine("BC::Display");
  }
} 
class DC : BC
{
  new public void Display()
  {
     System.Console.WriteLine("DC::Display");
  }
} 
class Demo
{
  public static void Main()
  {
     BC b;
     b = new BC();
     b.Display();
   }
}
Output
BC::Display

The above program compiles and runs successfully to give the desired output. It consists of a base class BC and a derived class DC. Class BC consists of function Display(). Class DC hides the function Display() it inherited from the base class BC by providing its on implementation of Display(). Class Demo consists of entry-point function Main(). Inside Main() we first create a reference b of type BC. Then we create an object of type BC and assign its reference to reference variable b. Using the reference variable b we invoke the function Display(). As expected, Display() of class BC is executed because the reference variable b refers to the object of class BC.

Now we add a twist of lime to the above program.

P2.cs
class BC
{
  public void Display()
  {
     System.Console.WriteLine("BC::Display");
  }
} 
class DC : BC
{
  new public void Display()
  {
     System.Console.WriteLine("DC::Display");
  }
} 
class Demo
{
  public static void Main()
  {
     BC b;
     b = new BC();
     b.Display();
     b = new DC();
     b.Display();   
   }
}
Output
BC::DisplayBC::Display

Here we are creating an object of Derived class DC and storing its reference in the reference variable b of type BC. This is valid in C#. Next, using the reference variable b we invoke the function Display(). Since b contains a reference to object of type DC one would expect the function Display() of class DC to get executed. But that does not happen. Instead what is executed is the Display() of BC class. That’s because the function is invoked based on type of the reference and not to what the reference variable b refers to. Since b is a reference of type BC, the function Display()of class BC will be invoked, no matter whom b refers to. Take one more example.

P3.cs
class BC
{
  public void Display()
  {
     System.Console.WriteLine("BC::Display");
  }
} 
class DC : BC
{
  new public void Display()
  {
     System.Console.WriteLine("DC::Display");
  }
} 
class TC : BC
{
  new public void Display()
  {
     System.Console.WriteLine("DC::Display");
  }
} 
class Demo
{
  public static void Main()
  {
     BC b;
     b = new BC();
     b.Display();
     b = new DC();
     b.Display();    
     b = new TC();
     b.Display();
   }
}
Output
BC::DisplayBC::DisplayBC::Display

The output of the above program is a receipt of the fact that no matter to whom base class reference b refers, it invokes the functions of the class that matches its type. But doesn’t this sound absurd? If b contains the reference to a particular derived class object, then its supposed to invoke the function of that class. Well, C# helps us do this by the usage of keywords virtual and override as shown in the following program.

P4.cs
class BC
{
  public virtual void Display()
  {
     System.Console.WriteLine("BC::Display");
  }
} 
class DC : BC
{
  public override void Display()
  {
     System.Console.WriteLine("DC::Display");
  }
} 
class Demo
{
  public static void Main()
  {
     BC b;
     b = new BC();
     b.Display();     
     b = new DC();
     b.Display();    
  }
}
Output
BC::DisplayDC::Display

The above program compiles and runs successfully to give the expected desired output. The function Display() of Base class BC is declared as virtual, while the Derived class’s implementation of Display() is decorated with the modifier override. Doing so enables C# to invoke functions like Display() based on objects the reference variable refers to and not the type of reference that is invoking the function. Hence in the above program when b refers to the object of class BC it invokes Display() of BC and then when b refers to the object of class DC it invokes Display() of class DC. Let’s see if this holds true for the third generation of derived classes. Take the following program.

P4.cs
class BC
{
  public virtual void Display()
  {
     System.Console.WriteLine("BC::Display");
  }
} 
class DC : BC
{
  public override void Display()
  {
     System.Console.WriteLine("DC::Display");
  }
} 
class TC : DC
{
  public override void Display()
  {
     System.Console.WriteLine("TC::Display");
  }
} 
class Demo
{
  public static void Main()
  {
     BC b;
     b = new BC();
     b.Display();     
     b = new DC();
     b.Display();     
     b = new TC();
     b.Display();   
  }
}
Output
BC::DisplayDC::DisplayTC::Display

The above program compiles and runs successfully to give the expected desired output. The function Display() of Base class BC is declared as virtual, while the implementation of Display() in successive Derived classes is decorated with the modifier override. Next, we successively create objects of each class and store their reference in base class reference variable b and invoke Display(). The rite versions of Display get invoked based on the object the reference variable refers to. Time for a tiny teaser! Guess what the output would be in the following program?

P5.cs
class BC
{
  public virtual void Display()
  {
     System.Console.WriteLine("BC::Display");
  }
} 
class DC : BC
{
  public override void Display()
  {
     System.Console.WriteLine("DC::Display");
  }
} 
class TC : DC
{ 

} 
class Demo
{
  public static void Main()
  {
     BC b;
     b = new TC();
     b.Display();   
  }
}
Output
DC::Display

Since TC has no implementation of Display(), it inherits Display() from DC as TC is derived from DC. Hence Display() from Derived class DC gets executed. It’s as if the derived class TC looked like this:

class TC 
{
  public override void Display()
  {
     System.Console.WriteLine("DC::Display");
  }
}

to the compiler. Take one more example. Guess what its output will be.

P6.cs
class BC
{
  public virtual void Display()
  {
     System.Console.WriteLine("BC::Display");
  }
} 
class DC : BC
{
  public override void Display()
  {
     System.Console.WriteLine("DC::Display");
  }
} 
class TC : DC
{
  public new void Display()
  {
     System.Console.WriteLine("TC::Display");
  }
} 
class Demo
{
  public static void Main()
  {
     BC b;
     b = new TC();
     b.Display();
  }
}
Output
DC::Display

Agreed that TC defines its own new version of Display(). But its version of display is not invoked as Display() of TC does not override the Display() of the base class. With this understood we are done with Method overriding in C#.

For more information see MSDN Reference Document Method Overriding in C#