How to create windows azure mobile service??

//

windows azure mobile service

1. Just log in to your windows azure portal here with your live credentials.

clip_image002

2. If you don’t have windows azure account, you can create a trial account here

 

clip_image004

3. Once you are in windows azure portal click on the MOBILE SERVICES tab in left panel.

 

clip_image005

4. Click on the +NEW in left below corner.

 

clip_image006

5. A new popup screen comes up as below.

 

clip_image008

6. Click on Create and enter the service name in URL field. The service name must be unique as its going to be used as a subdomain name suffix to .azure-mobile.net

Ex: https://demomobileserviceforblog.azure-mobile.net in my case. Select the database from DATABASE dropdown if you have already created one the select the option Use an existing SQL database, if you don’t have then you can select a free with 20 mb otherwise create one according your requirement. Lastly select the region.I have selected existing one database.

clip_image010

7. Click on next arrow. We get Database Settings screen provide your databse password her and click right button.

 

clip_image012

8. We can observe the progress of creating mobile service as shown in below screen.Once the mobile service is up and live the status changes to Ready.

 

clip_image014

9. Once the service is ready click on the mobile service name that we have just created it will take us to mobile service dashboard as shown in below image.

 

clip_image016

Hence the our mobile service is ready now you can access it from different mobile platform as showing in above image and you can configure mobile service, sees logs, crate the table in DATA tab.

Naked Domain?

naked domain

What is it? A naked domain is basically a domain without the ‘www’ prefix. For instance, ganeshsattawan.com (naked) instead of http://www.ganeshsattawan.com (non-naked). To make simpler domain mapping configuration.in additional manner a naked domain, too called a zone apex domain, is a domain that absences a subdomain, excluding the www.

Examples: www.ganeshsattawan.com -not naked

ftp.ganeshsattawan.com -not naked

ganeshsattawan.com -naked or zone apex domain

What is www in a domain name? it is subdomain of Domain. In detail, first portion of your domain that come first to example.com can be entitled a subdomain.Naked domains can turn out to be problematic if your DNS records are not configured properly.

HOW DO I MAKE THE NAKED TYPE OF MY URL WORK? Domain mapping maps http://www.example.com to your site. To allow example.com (short of the ‘www’) you need to set a redirect (forward) from example.com to http://www.example.com at your registrar. In what way this is set closely depends on your registrar/ host.

OOPS Concept

//
What’s it oops   : It is a methodology to write the programs in oops supported (like C#, F#, java and many to name here) languages where we specify the code in form of classes and objects.

Why should one use OOPs in programming?

OOP provides us many benefits over not using any OOP techniques. You will find some of the following benefits:

  • Eliminate Global Variables
  • Modularity: Related data and methods together in one place(just like a wrapper for them)
    • Allows for better unit testing
    • Allows you to focus on a smaller set of data & functionality
  • Better reusability
  • Easier to extend functionality
  • Hide Complexity

As you can see, these are some of benefits! We all understand that global variables kill our productivity and make tracking down bugs very difficult. The ability to move data and the functions that operate upon that data into one place make reading code easier, and also contributes to better testing. You are better able to reuse code that is in classes.

Class:

A class is a collection of objects, a class is a blueprint or template or set of instructions to build a specific type of object. Every object is built from a class. Each class should be designed and programmed to accomplish one, and only one, thing.

Object:

Objects are elements from the script that are defined to perform the instructions written in a class, and can use the properties and methods defined in the class.
- For example, to understand, you can think of a class as a blueprint for constructing an house. Many houses can be built from the same blueprint, so, the object is the house created according to that blueprint. You can build multiple objects that have the properties defined in the class.

More about the Object:

An object can be considered a “thing” that can perform a set of related activities. The set of activities that the object performs defines the object’s behavior. For example, the hand can grip something or a Student(object) can give the name or address. In pure OOP terms an object is an instance of a class

The above template describe about object Student

Class is composed of three things name, attributes, and operations

public class student

{

}

student objstudent=new student ();

According to the above sample we can say that Student object, named objstudent, has created out of the student class.

In real world you will often find many individual objects all of the same kind. As an example, there may be thousands of other bicycles in existence, all of the same make and model. Each bicycle has built from the same blueprint. In object-oriented terms, we say that the bicycle is an instance of the class of objects known as bicycles. In the software world, though you may not have realized it, you have already used classes. For example, the Textbox control, you always used, is made out of the Textbox class, which defines its appearance and capabilities. Each time you drag a Textbox control, you are actually creating a new instance of the Textbox class.

Encapsulation:

Encapsulation is a process of binding the data members and member functions into a single unit.

Example for encapsulation is class. A class can contain data structures and methods.

Consider the following class

public class Aperture

{

public Aperture ()

{

}

protected double height;

protected double width;

protected double thickness;

public double get volume()

{

Double volume=height * width * thickness;

if (volume<0)

return 0;

return volume;

}

}
In this example we encapsulate some data such as height, width, thickness and method Get Volume. Other methods or objects can interact with this object through methods that have public access modifier

Abstraction:

Abstraction is a process of hiding the implementation details and displaying the essential features.

Example1: A Laptop consists of many things such as processor, motherboard, RAM, keyboard, LCD screen, wireless antenna, web camera, usb ports, battery, speakers etc. To use it, you don’t need to know how internally LCD screens, keyboard, web camera, battery, wireless antenna, speaker’s works.  You just need to know how to operate the laptop by switching it on. Think about if you would have to call to the engineer who knows all internal details of the laptop before operating it. This would have highly expensive as well as not easy to use everywhere by everyone.

So here the Laptop is an object that is designed to hide its complexity.

How to abstract: – By using Access Specifiers

.Net has five access Specifiers

Public — Accessible outside the class through object reference.
Private — Accessible inside the class only through member functions.
Protected — Just like private but Accessible in derived classes also through member functions.
Internal – Visible inside the assembly. Accessible through objects.
Protected Internal — Visible inside the assembly through objects and in derived classes outside the assembly through member functions.
Let’s try to understand by a practical example:-

public class Class1

{

int  i;                                                                //No Access specifier means private

public int j;                                                 // Public

protected int k;                                         //Protected data

internal int m;                                        // Internal means visible inside assembly

protected internal int n;                  //inside assembly as well as to derived classes outside assembly

static int x;                                          // This is also private

public static int y;                           //Static means shared across objects

[DllImport("MyDll.dll")]

public static extern int MyFoo();       //extern means declared in this assembly defined in some other assembly

public void myFoo2()

{

//Within a class if you create an object of same class then you can access all data members through object reference even private data too

Class1 obj = new Class1();

obj.i =10; //Error can’t access private data through object.But here it is accessible.:)

obj.j =10;

obj.k=10;

obj.m=10;

obj.n=10;

//     obj.s =10;  //Errror Static data can be accessed by class names only

Class1.x = 10;

//   obj.y = 10; //Errror Static data can be accessed by class names only

Class1.y = 10;

}

}

Now lets try to copy the same code inside Main method and try to compile

[STAThread]

static void Main()

{

//Access specifiers comes into picture only when you create object of class outside the class

Class1 obj = new Class1();

//     obj.i =10;             //Error can’t access private data through object.

obj.j =10;

//      obj.k=10;     //Error can’t access protected data through object.

obj.m=10;

obj.n=10;

//     obj.s =10;  //Errror Static data can be accessed by class names only

Class1.x = 10;  //Error can’t access private data outside class

//   obj.y = 10; //Errror Static data can be accessed by class names only

Class1.y = 10;

}

What if Main is inside another assembly

[STAThread]

static void Main()

{

//Access specifiers comes into picture only when you create object of class outside the class

Class1 obj = new Class1();

//     obj.i =10;             //Error can’t access private data through object.

obj.j =10;

//      obj.k=10;     //Error can’t access protected data through object.

//     obj.m=10; // Error can’t access internal data outside assembly

//      obj.n=10; // Error can’t access internal data outside assembly

//     obj.s =10;  //Errror Static data can be accessed by class names only

Class1.x = 10;  //Error can’t access private data outside class

//   obj.y = 10; //Errror Static data can be accessed by class names only

Class1.y = 10;

}

In object-oriented software, complexity is managed by using abstraction.

Abstraction is a process that involves identifying the critical behavior of an object and eliminating irrelevant and complex details.

Inheritance:

Inheritance is a process of deriving the new class from already existing class

C# is a complete object oriented programming language. Inheritance is one of the primary concepts of object-oriented programming. It allows you to reuse existing code. Through effective use of inheritance, you can save lot of time in your programming and also reduce errors, which in turn will increase the quality of work and productivity. A simple example to understand inheritance in C#.

Using System;

Public class BaseClass

{

Public BaseClass ()

{

Console.WriteLine (“Base Class Constructor executed”);

}

Public void Write ()

{

Console.WriteLine (“Write method in Base Class executed”);

}

}

Public class ChildClass: BaseClass

{

Public ChildClass ()

{

Console.WriteLine(“Child Class Constructor executed”);

}

Public static void Main ()

{

ChildClass CC = new ChildClass ();

CC.Write ();

}

}

· In the Main () method in ChildClass we create an instance of childclass. Then we call the write () method. If you observe the ChildClass does not have a write() method in it. This write () method has been inherited from the parent BaseClass.

· The output of the above program is
Output:
Base Class Constructor executed
Child Class Constructor executed
Write method in Base Class executed
this output proves that when we create an instance of a child class, the base class constructor will automatically be called before the child class constructor. So in general Base classes are automatically instantiated before derived classes.

· In C# the syntax for specifying BaseClass and ChildClass relationship is shown below. The base class is specified by adding a colon, “:”, after the derived class identifier and then specifying the base class name.

Syntax:  class ChildClassName: BaseClass
{
//Body
}

· C# supports single class inheritance only. What this means is, your class can inherit from only one base class at a time. In the code snippet below, class C is trying to inherit from Class A and B at the same time. This is not allowed in C#. This will lead to a compile time error: Class ‘C’ cannot have multiple base classes: ‘A’ and ‘B’.

public class A

{

}

public class B

{

}

public class C : A, B

{

}

· In C# Multi-Level inheritance is possible. Code snippet below demonstrates mlti-level inheritance. Class B is derived from Class A. Class C is derived from Class B. So class C, will have access to all members present in both Class A and Class B. As a result of multi-level inheritance Class has access to A_Method(),B_Method() and C_Method().
Note: Classes can inherit from multiple interfaces at the same time. Interview Question: How can you implement multiple inheritance in C#? Ans : Using Interfaces. We will talk about interfaces in our later article.

Using System;

Public class A

{

Public void A_Method ()

{

Console.WriteLine (“Class A Method Called”);

}

}

Public class B: A

{

Public void B_Method ()

{

Console.WriteLine (“Class A Method Called”);

}

}

Public class C: B

{

Public void C_Method ()

{

Console.WriteLine (“Class A Method Called”);

}

Public static void Main ()

{

C C1 = new C ();

C1.A_Method ();

C1.B_Method ();

C1.C_Method ();

}

}

· When you derive a class from a base class, the derived class will inherit all members of the base class except constructors. In the code snippet below class B will inherit both M1 and M2 from Class A, but you cannot access M2 because of the private access modifier. Class members declared with a private access modifier can be accessed only with in the class. We will talk about access modifiers in our later article.
Common Interview Question: Are private class members inherited to the derived class?
Ans: Yes, the private members are also inherited in the derived class but we will not be able to access them. Trying to access a private base class member in the derived class will report a compile time error.

Using System;

Public class A

{

Public void M1 ()

{

}

Private void M2 ()

{

}

}

Public class B: A

{

Public static void Main ()

{

B B1 = new B ();

B1.M1 ();

//Error, Cannot access private member M2

//B1.M2 ();

}

}

Method Hiding and Inheritance We will look at an example of how to hide a method in C#. The Parent class has a write () method which is available to the child class. In the child class I have created a new write () method. So, now if I create an instance of child class and call the write () method, the child class write () method will be called. The child class is hiding the base class write () method. This is called method hiding.
If we want to call the parent class write () method, we would have to type cast the child object to Parent type and then call the write () method as shown in the code snippet below.

Using System;

Public class Parent

{

Public void Write ()

{

Console.WriteLine (“Parent Class write method”);

}

}

Public class Child: Parent

{

Public new void Write ()

{

Console.WriteLine (“Child Class write method”);

}

Public static void Main ()

{

Child C1 = new Child ();

C1.Write ();

//Type caste C1 to be of type Parent and call Write () method

((Parent) C1).Write ();

}

}

Polymorphism:

When a message can be processed in different ways is called polymorphism. Polymorphism means many forms.

Polymorphism is one of the fundamental concepts of OOP.

Polymorphism provides following features:

· It allows you to invoke methods of derived class through base class reference during runtime.

· It has the ability for classes to provide different implementations of methods that are called through the same name.

Polymorphism is of two types:

1. Compile time polymorphism/Overloading

2. Runtime polymorphism/Overriding

Compile Time Polymorphism

Compile time polymorphism is method and operators overloading. It is also called early binding.

In method overloading method performs the different task at the different input parameters.

Runtime Time Polymorphism

Runtime time polymorphism is done using inheritance and virtual functions. Method overriding is called runtime polymorphism. It is also called late binding.

When overriding a method, you change the behavior of the method for the derived class.  Overloading a method simply involves having another method with the same prototype.

Caution: Don’t confused method overloading with method overriding, they are different, unrelated concepts. But they sound similar.

Method overloading has nothing to do with inheritance or virtual methods.

Following are examples of methods having different overloads:

void area(int side);

void area(int l, int b);

void area(float radius);

Practical example of Method Overloading (Compile Time Polymorphism)

using System;

namespace method_overloading

{

class Program

{

public class Print

{

public void display(string name)

{

Console.WriteLine (“Your name is : ” + name);

}

public void display(int age, float marks)

{

Console.WriteLine (“Your age is : ” + age);

Console.WriteLine (“Your marks are :” + marks);

}

}

static void Main(string[] args)

{

Print obj = new Print ();

obj.display (“George”);

obj.display (34, 76.50f);

Console.ReadLine ();

}

}

}

Note: In the code if you observe display method is called two times. Display method will work according to the number of parameters and type of parameters.

When and why to use method overloading

Use method overloading in situation where you want a class to be able to do something, but there is more than one possibility for what information is supplied to the method that carries out the task.

You should consider overloading a method when you for some reason need a couple of methods that take different parameters, but conceptually do the same thing.

Method overloading showing many forms.

using System;

namespace method_overloading_polymorphism

{

Class Program

{

Public class Shape

{

Public void Area (float r)

{

float a = (float)3.14 * r;

// here we have used function overload with 1 parameter.

Console.WriteLine (“Area of a circle: {0}”,a);

}

Public void Area(float l, float b)

{

float x = (float)l* b;

// here we have used function overload with 2 parameters.

Console.WriteLine (“Area of a rectangle: {0}”,x);

}

public void Area(float a, float b, float c)

{

float s = (float)(a*b*c)/2;

// here we have used function overload with 3 parameters.

Console.WriteLine (“Area of a circle: {0}”, s);

}

}

Static void Main (string[] args)

{

Shape ob = new Shape ();

ob.Area(2.0f);

ob.Area(20.0f,30.0f);

ob.Area(2.0f,3.0f,4.0f);

Console.ReadLine ();

}

}

}

Things to keep in mind while method overloading

If you use overload for method, there are couple of restrictions that the compiler imposes.

The rule is that overloads must be different in their signature, which means the name and the number and type of parameters.

There is no limit to how many overload of a method you can have. You simply declare them in a class, just as if they were different methods that happened to have the same name.

Constructors and Destructors:

Classes have complicated internal structures, including data and functions, object initialization and cleanup for classes is much more complicated than it is for simple data structures. Constructors and destructors are special member functions of classes that are used to construct and destroy class objects. Construction may involve memory allocation and initialization for objects. Destruction may involve cleanup and deallocation of memory for objects.

· Constructors and destructors do not have return types nor can they return values.

· References and pointers cannot be used on constructors and destructors because their addresses cannot be taken.

· Constructors cannot be declared with the keyword virtual.

· Constructors and destructors cannot be declared static, const, or volatile.

· Unions cannot contain class objects that have constructors or destructors.

Constructors and destructors obey the same access rules as member functions. For example, if you declare a constructor with protected access, only derived classes and friends can use it to create class objects.

The compiler automatically calls constructors when defining class objects and calls destructors when class objects go out of scope. A constructor does not allocate memory for the class object it’s thispointer refers to, but may allocate storage for more objects than its class object refers to. If memory allocation is required for objects, constructors can explicitly call the new operator. During cleanup, a destructor may release objects allocated by the corresponding constructor. To release objects, use the delete operator.

Example of Constructor

class C

{

private int x;

private int y;

public C (int i, int j)

{

x = i;

y = j;

}

public void display ()

{

Console.WriteLine(x + “i+” + y);

}

}
Example of Destructor

class D

{

public D ()

{

// constructor

}

~D ()

{

// Destructor

}

}

What is O/RM?

//
O/RM is an acronym that stands for object/relational mapping. Basically, an O/RM framework is used to persist model objects in a relational database and retrieve them. It uses metadata information to interface with the database. This way, your data-layer code knows nothing about the database structure. The O/RM tool becomes middleware that completely hides the complexity.

The heart of O/RM is the mapping—the mapping technique is what binds the object and relational worlds. By mapping, you express how a class and its properties are related to one or more tables in the database. This information is used by the O/RM tool’s engine to dynamically build SQL code that retrieves data and transforms it into objects. Similarly, by tracking changes to objects’ properties, it can use mapping data to send updates back to the database. The mapping information is generally expressed as an XML file. As an alternative, some O/RM tools use attributes on the classes and their properties to maintain mapping data.

Below image shows the Entity Framework Architecture:

entity framework orm model

Complete Scene of Constructor in c#

//

Introduction

The constructor plays significant role in the nay kind of programming language. Here I explained the types of constructor and its limitation with suitable examples. Let us see the constructor.

Constructors:

The constructor is a special method to the class and structs. This constructor is used to initialize the types and objects. The complier consider as constructor when the constructor have the same name as class name. Every class has the default constructor in the class (default constructor). Which can be called as implicit constructor. This can be used to define the default values the data types when there are not defined.
The user can use the default constructor for explicitly to create the instance of the classes. The constructor access modifier is public then it will be executed when the object is instantiated. The private constructor cannot be declaring. When object instantiate the outside class then it will throw an error like protection level. The internal also can be defined access modifier to the class constructor that will support up to that current assembly.

Limitations:

  • The constructor should have the same as the class or struct name.
  • It cannot return any values to the calling program or function.
  • It static constructor cannot have any parameters.
  • It should have public or internal access modifiers. It can be declared as private but no use of it. When we instantiate the object it must throw compilation error like inaccessible due to protection level.
  • It can be used to capture the parameters and initialize the values rather than do the complex logics.

Constructor:

The simple constructor can be used to instantiate the object and define the data type values.
The syntax of the constructor is the following
access-modifier Class_Name(data type Parameter1,data type Parameter 2, [Classes Obj])
{
//Code here
}
using System;
public class SimpCons
{
private int a;
private int b;
public SimpCons(int x, int y)
{
a = x;
b = y;
Display();
}
public void Display()
{
Console.WriteLine(“The value of a is ” + a);
Console.WriteLine(“The value of b is ” + b);
}
}
class SimpleConstructor
{
public static void Main()
{
SimpCons oSimpCons = new SimpCons(5, 5);
}
}
In the above code, the constructor is used to initialize the values to the variables.
The constructor can be called the user defined the method in the both base and inherited class. Suppose I have not used the constructor then it will use the implicit constructor to initialize the values for the variables.

Overload Constructor

The constructor can be overloaded. As you know the constructor should be same as class name. But it can be overloaded just like method overloading. The same polymorphism concept can be applicable for the constructor. The same method name with different arguments.

Overload Constructor with different data types

The constructor can be overloaded with the same name of the constructor with different signature. The compiler only considers the signature type of the constructor. The arguments may be like int, string, char, float, double, etc..,
using System;
class OverCons
{
public OverCons()
{
Console.WriteLine(“Hi! Welcome to Overload Constructor”);
Console.WriteLine(“———————————–”);
}
public OverCons(int a, int b)
{
Console.WriteLine(“The addition of ” + a + ” and ” + b + ” is ” + (a + b));
}
public OverCons(string str1, string str2)
{
Console.WriteLine(“Your full name is ” + (str1 + str2));
}
}
class ConstuctorOverload
{
public static void Main(string[] args)
{
OverCons oOverCons = new OverCons();
OverCons oOverCons1 = new OverCons(90, 10);
OverCons oOverCons2 = new OverCons(“Senthil”, “kumar”);
}
}
This example shows there are three overloaded constructors. One is default constructor, second one is it accepts two integer values. Final constructor accepts the string. It can be any different combination of data types of parameter to the functions. It will not allow the constructor with the same signature types with different variable name. Because the compiler identifies the constructor based on the type of signature matches.

Overload Constructor with different class objects

When overload the constructors it accepts the different types of class objects. It can be overloaded with the objects.
using System;
using System.Collections;
using System.Text;

class ObjOver
{
public ObjOver(ArrayList oArrayList)
{
Console.WriteLine(“Constructor – ArrayList”);
Console.WriteLine(“———————–”);
for (int i = 0; i < oArrayList.Count; i++)
{
Console.WriteLine(oArrayList[i].ToString());
}
}
public ObjOver(Stack oStack)
{
Console.WriteLine(“Constructor – Stack”);
Console.WriteLine(“——————-”);
foreach (string str in oStack)
{
Console.WriteLine(str);
}
}
public ObjOver(StringBuilder oSB)
{
Console.WriteLine(“Constructor – StringBuilder”);
Console.WriteLine(“—————————”);
Console.WriteLine(oSB.ToString());
}
}

class ObjOverCons
{
public static void Main(string[] args)
{
ArrayList oArrayList = new ArrayList();
for (int i = 0; i < 10; i++)
{
oArrayList.Add(i);
}
Stack oStack = new Stack();
oStack.Push(“Senthil”);
oStack.Push(“Kumar”);
StringBuilder oSB = new StringBuilder();
oSB.Append(“Welcome To Object Overload Constructor”);
oSB.Append(Environment.NewLine);
oSB.Append(“Sample programs developed by Erode Senthilkumar”);
ObjOver oObjOver1 = new ObjOver(oArrayList);
ObjOver oObjOver2 = new ObjOver(oStack);
ObjOver oObjOver3 = new ObjOver(oSB);
}
}
Here the constructor has overloaded with the class objects.

Private Constructor

The private constructor is a special method in the class. It can be only defined when the class has only the static members.
using System;
public class StaticBase
{
private StaticBase()
{
Console.WriteLine(“Hi”);
}
public static void Display()
{
Console.WriteLine(“Display() method”);
}
}

class PrivateStatic
{
public static void Main(string[] args)
{
StaticBase.Display();
}
}
Here the below code cannot be executed. Here inherited class “DeriveCons” when try to access the properties of the “BaseCons” then the constructor method is defined as private access modifier. So it will throw exception like due to protection level.
using System;

public class BaseCons
{
private BaseCons()
{
Console.WriteLine(“BaseCons Constructor”);
}
}
public class DeriveCons : BaseCons
{
public DeriveCons()
{
Console.WriteLine(“DeriveCons – Constructor”);
}
}
class PrivateCons
{
public static void Main(string[] args)
{
DeriveCons oDeriveCons = new DeriveCons();
}
}

Static Constructor:

Used for initializing only the static members of the class. These will be invoked for the very first time the class is being loaded on the memory. They cannot accept any arguments. Static Constructors cannot have any access modifiers.
using System;
class BaseStatic
{
public static int i;
static BaseStatic()
{
i = 100;
Console.WriteLine(“BaseStatic Constructor”);
Console.WriteLine(“i value is ” + i);
}
}
class StaticCons
{
public static void Main(string[] args)
{
Console.WriteLine(“Static Constructor”);
Console.WriteLine(“——————”);
BaseStatic oBaseStatic = new BaseStatic();
}
}
In the above example, the static constructor will allow us to initialize the values for that static variable. It will not allow to use any other type variable.
The below will throw an error. Because I have tried to initialize the non static variable.
using System;
class BaseClass
{
public static int i;
public int a = 0;
static BaseClass()
{
i = 10;
a = 15;
}
public void Print()
{
Console.WriteLine(“The value of i is ” + i);
Console.WriteLine(“The value of a is ” + a);
}
}
class StaticCons1
{
public static void Main(string[] args)
{
BaseClass oBaseClass = new BaseClass();
oBaseClass.Print();
}
}

Behavior of the Constructor in the Inheritance

As you know the constructor can call the method of the class. In the below mentioned code there are two classes. One is base class and another one is Derived class. The derived class inherited from the base class. In the main program we have instantiated the Derived class. The Base class has the virtual method name called Display. It has overridden in the Derived Class. If I instantiate the Derived class then which constructor will call first?
using System;
public class BaseClass
{
public string _ClassState;
public BaseClass()
{
_ClassState = “Base Class”;
Console.WriteLine(_ClassState);
Display();
}
public virtual void Display()
{
Console.WriteLine(“Base Class – Display()”);
}
}
class DerivedClass : BaseClass
{
public DerivedClass()
{
_ClassState = “Derived Class”;
Console.WriteLine(_ClassState);
}
public override void Display()
{
Console.WriteLine(“Derived Class – Display()”);
}
}
class InherVirtualCons
{
public static void Main(string[] args)
{
DerivedClass oDerivedClass = new DerivedClass();
}
}
Yes! You are right!! The base class constructor will call first. Again I have called the method name in the Display. Actually I was expecting the base class Display method call first. But without call the Derived Class constructor it has called the Derived class Display method. In this scenario it considers only the current derived object method.

Exception Handling in the Constructors

The constructor will allow handling the exception. Before that we no need to write the more complex logics in the constructors. It has to be used to initialize the data types and create the object for the built in classes.
using System;
class ConsExcep
{
public ConsExcep(int numer, int dinom)
{
try
{
int Result = numer / dinom;
Console.WriteLine(“Result is:” + Result);
}
catch (Exception oEx)
{
Console.WriteLine(“Error :” + oEx.Message);
}
}
}
class ExcepConstructor
{
public static void Main(string[] arsg)
{
ConsExcep oConsExcep = new ConsExcep(5, 0);
}
}
Here it handles the divide by zero exception.

Constructor in Partial Class

As we know this partial class is the new feature from C# 2.0 onwards. The same class name can be divided into multiple classes with the same class name and different class file name along with partial keyword.
Here a class can have the constructor in the different file name. As we know while compilation the compiler will build the same class name in the different file as single code unit.
using System;
public partial class PartialClass
{
public PartialClass()
{
Console.WriteLine(“PartialClass Constructor”);
}
public void Display()
{
Console.WriteLine(“PartialClass – Display()”);
}
}
public partial class PartialClass
{
/*
public PartialClass()
{
Console.WriteLine(“PartialClass Constructor1″);
}
*/
public PartialClass(string strName)
{
Console.WriteLine(“Name: ” + strName);
}
public void Print()
{
Console.WriteLine(“PartialClass – Print()”);
}
}
class PartialCons
{
public static void Main(string[] args)
{
PartialClass oPartialClass = new PartialClass();
oPartialClass.Display();
oPartialClass.Print();
PartialClass oPartialClass1 = new PartialClass(“Erode Senthilkumar”);
}
}
Here the example shows the same default signature cannot have more than once in the every class. Because it will became ambiguity method while compiler compile these files into the single unit. But we can load the constructor in the different signatures in the every partial class.

Constructors in Struct

The struct can have the constructors. But it differs from the classes. The struct is value type. It will be stored on the stack. We have seen that class can have the default constructor explicitly. But here stack will not allow writing the default constructor. It should contain the parameter. But we can overload the constructor in the struct. Every struct has the default implicit constructor. It will get execute internally to initialize the default value to the variables. . But we cannot have the default constructor with out any parameter in the struct like the following.
struct Employee
{
public Employee()
{
Console.WriteLine(“Default Constructor in struct”);
}
}
The struct should contain the constructor with the parameters like the following.
using System;
struct structstudent
{
private string _Sname;
private string _Class;
private string _Age;
public structstudent(string sname, string sclass, string sage)
{
_Sname = sname;
_Class = sclass;
_Age = sage;
}
public void PrintReport()
{
Console.WriteLine(“Student Report”);
Console.WriteLine(“————–”);
Console.WriteLine(“Student Name: ” + _Sname);
Console.WriteLine(“Student Class: ” + _Class);
Console.WriteLine(“Student Age: ” + _Age);
}
}
class StructCons
{
public static void Main(string[] args)
{
structstudent oSD = new structstudent(“Rama”, “1st Std”, “6″);
oSD.PrintReport();
}
}
In the above struct is a valid one

Conclusion:

I have explained the constructors with the different scenarios. I hope that this article has given a good idea about the constructor. I have not covered few things in this article. I try to update this article with missed things. I expect your valuable comments and feedback about my article.
I have attached the code snippet of this article.

Asynchronous Programming in C#

//

When your user interface is unresponsive or your server doesn’t scale, chances are you need your code to be more asynchronous. With today’s .NET Framework and language features, though, that is easier said than done.

The Microsoft Visual Studio Async CTP proposes a new language feature in C#  and a new framework pattern to go with it, that will make asynchronous programming similar to – and about as straightforward as –synchronous programming.

Why asynchronous?

For decades programming with remote resources has presented a conundrum. As the level of abstraction in “local” programming has been steadily rising, there has been a push for transparency of remote operations – they should look just like local ones, so that a developer doesn’t need to grapple with conceptual overhead, architectural impedance mismatch and leaky abstractions.

The problem is that remote operations are different from local ones. They have orders of magnitude more latency even at the best of times, may fail in new ways or simply never come back, depend on a variety of external factors beyond the developer’s control or even perception, etc. So while they can be represented like “just method calls,” it is not desirable to do so because the developer is left without handles to manage the special conditions arising from their remoteness – managing cancellation and timeouts, preserving threading resources during blocking waits, predicting and handling threats to responsiveness, etc.

On .NET we have not ignored this challenge. In fact we have not just one but several patterns for how to do asynchronous programming; that is, dealing with I/O and similar high latency operations without blocking threads. Most often there is both a synchronous (i.e. blocking transparently) and an asynchronous (i.e. latency-explicit) way of doing things. The problem is that these current patterns are very disruptive to program structure, leading to exceedingly complex and error prone code or (more commonly) developers giving up and using the blocking approach, taking a responsiveness and performance hit instead.

The goal should be to bring the asynchronous development experience as close to the synchronous paradigm as possible, without letting go of the ability to handle the asynchrony-specific situations. Asynchrony should be explicit and non-transparent, but in a very lightweight and non-disruptive manner. Composability, abstraction and control structures should all work as simply and intuitively as with synchronous code.

This is the goal of the features of the Async CTP.

How bad is it?

The problem is best understood in the common scenario of a UI that has just one thread to run all its user interface code on, but applies equally in, for example, server scenarios where thread resources may be a scaling bottleneck and having thousands of threads spend most of their time doing nothing is a bad strategy.

A client app that doesn’t react to mouse events or update the display for user-recognizable periods of time is likely the result of code holding on to the single UI thread for far too long. Maybe it is waiting for network IO or maybe it is performing an intensive computation. Meanwhile, other events just can’t get processing time, and the user-perceived world grinds to a halt. What’s a more frustrating user experience than losing all contact with an app that is “busy” standing still, staring down a pipe for a response that may be seconds away?

Easy to say, hard to fix. For years the recommended approach to these issues has been asynchrony: don’t wait for that response. Return as soon as you issue the request, letting other events take place in the meantime, but have the eventual response call you back when it arrives so that you can process the result as a separate event. This is a great approach: your UI thread is never blocked waiting, but is instead blazing through small, nimble events that easily interleave and never have to wait long for their turn.

The problem: Asynchronous code totally blows up your control flow. The call you back part needs a callback – a delegate describing what comes after. But what if you wanted to “wait” inside a while loop? An if statement? A try block or using block? How do you then describe “what comes after”?

Look at this simple example:

public int SumPageSizes(IList<Uri> uris) {
    int total = 0;
    foreach (var uri in uris) {
        statusText.Text = string.Format("Found {0} bytes ...", total);
        var data = new WebClient().DownloadData(uri);
        total += data.Length;
    }
    statusText.Text = string.Format("Found {0} bytes total", total);
    return total;
}

The method downloads a number of URI’s, totaling their sizes and updating a status text along the way.

Clearly this method doesn’t belong on the UI thread because it may take a very long time to complete, while holding up the UI completely. Just as clearly it does belong on the UI thread because it repeatedly updates the UI. What to do?

We can put it on a background thread, making it repeatedly “post” back to the UI thread to do the UI updates. That seems wasteful in this case, since a thread will be occupied spending most of its time just waiting for downloads, but sometimes it is really the only thing you can do. In this case, however, WebClient offers an asynchronous version of DownloadData – DownloadDataAsync – which returns promptly, and then fires an event – DownloadDataCompleted – when it is done. This allows us to write an asynchronous version of our method that splits it up into little callbacks and runs the next one on the UI thread whenever the download initiated by the previous one completes. Here’s a first attempt:

The original code returned the total as well as display it. Our new asynchronous version returns to its caller way before the total has even been computed. How do we get a result back to our caller? The answer is: our caller must provide a callback to us – which we can then invoke with the total when ready. The caller must in turn have its code restructured so that it consumes the total in a callback instead of as a return value.
Already this is bad. We have to break up the neat foreach loop and manually get an enumerator. Each call to the private helper method hooks up an event handler for the completion of its download, that will eventually call the private helper again for the next element – if any. The code looks recursive instead of iterative. Still you may squint and be able to discern the intent of this code. But we are not nearly done yet.

And what about exceptions? The original code said nothing about exceptions; they were just silently propagated to the caller. In the async case, though, exceptions will arise after we returned to the caller. We must extend the callback from the caller to also tell it about exceptions, and we have to explicitly propagate those, wherever they may arise.

Together, these requirements will further clutter the code:

public void SumPageSizesAsync(IList<Uri> uris, Action<int, Exception> callback) {
    SumPageSizesAsyncHelper(uris.GetEnumerator(), 0, callback);
}

  private void SumPageSizesAsyncHelper(IEnumerator<Uri> enumerator, int total, 
    Action<int, Exception> callback) {
    try {
        if (enumerator.MoveNext()) {
            statusText.Text = string.Format("Found {0} bytes ...", total);
            var client = new WebClient();
            client.DownloadDataCompleted += (sender, e) => {
                if (e.Error != null) 
                {
                    enumerator.Dispose();
                    callback(0, e.Error);
                }
                else SumPageSizesAsyncHelper(
                    enumerator, total + e.Result.Length, callback);
            };
            client.DownloadDataAsync(enumerator.Current);
        }
        else {
            statusText.Text = string.Format("Found {0} bytes total", total);
            enumerator.Dispose();
            callback(total, null);
        }
    }
    catch (Exception ex) {
        enumerator.Dispose();
        callback(0, ex);
    }
}

Is this code now correct? Did we expand the foreach statement correctly, and propagate all exceptions? In fact when you look at it can you tell what it does?

Unlikely. And this corresponds to a synchronous method with just one blocking call to replace with an asynchronous one (DownloadData), and one layer of control structure around it (the foreach loop). Imagine trying to compose more asynchronous calls, or having more complex control structure! And we haven’t even started on the callers of SumPageSizesAsync!

The real problem here is that we can no longer describe the logical flow of our method using the control flow constructs of the language. Instead of describing the flow, our program becomes about describing the wiring up of the flow. “Where to go next” becomes a matter not of the execution of a loop or conditional or try-block, but of which callback you installed.

Hence, making your code asynchronous with today’s tools is extremely ungrateful: After a lot of hard work the result is unappealing, hard to read and likely full of bugs.

A new approach

With the proposed new features, the asynchronous version of the code will instead look like this:

public async Task<int> SumPageSizesAsync(IList<Uri> uris) {
    int total = 0;
    foreach (var uri in uris) {
        statusText.Text = string.Format("Found {0} bytes ...", total);
        var data = await new WebClient().DownloadDataAsync(uri);
        total += data.Length;
    }
    statusText.Text = string.Format("Found {0} bytes total", total);
    return total;
}

Notice first how similar it is to the synchronous code. The highlighted parts are added, the rest stays the same. The control flow is completely unaltered, and there are no callbacks in sight. That doesn’t mean that there are no callbacks, but the compiler takes care of creating and signing them up, as we shall see.

The method is asynchronous by virtue of returning a Task<int> instead of an int. The Task and Task<T> types are in the framework today, and are good at representing ongoing work. The caller of SumPageSizesAsync can later use the returned Task<int> to inquire whether the work is complete, wait for the int result synchronously or sign up callbacks to get it when it is ready. So instead of taking a callback as a parameter, an asynchronous method now returns a representation of the ongoing work.

The asynchronous method has no extra parameters. By convention and to distinguish it from its synchronous counterpart (if we keep that in our code) we append “Async” to the method name.

The method is also marked as async. This means that the method body is compiled specially, allowing parts of it to be turned into callbacks, and automatically creating the Task<int> that is returned.

Here’s how that works: Inside of the method body we call another asynchronous method, DownloadDataAsync. This quickly returns a Task<byte[]> that will eventually complete when the downloaded data is available. However, we don’t want to do anything else until we have that data, so we immediately await the task, something that is only allowed inside of async methods.

By the time execution reaches the return statement, we have already been suspended and resumed several times by await’ing in the foreach loop, and have returned to the original caller long ago. We returned them not a result, because we didn’t have one yet (we were still in the process of computing the total) but a Task<int> that they could await if and when they wanted to. The effect of the return statement is to complete that task, so that whoever is looking at it – e.g. by await’ing it – can now get the result.
At first glance the await keyword looks like it blocks the thread until the task is complete and the data is available, but it doesn’t. Instead it signs up the rest of the method as a callback on the task, and immediately returns. When the awaited task eventually completes, it will invoke that callback and thus resume the execution of the method right where it left off!

In the following we will go into details with the different components of this approach.

Tasks

The Task and Task<TResult> types are already in the .NET Framework 4. A Task represents an ongoing activity, which may be CPU intensive work running on a separate thread, but may also represent an I/O operation, for example an outstanding response for an internet request. Task represents an activity without a result, and Task<TResult>, which derives from Task, represents an activity with a result of type TResult.

Tasks are often used to represent CPU-bound work running on a separate thread. Saying

Task<double> task = Task.Run(() => LongRunningComputation(x, y, z));
is an easy way to schedule the work in the lambda on a thread pool thread, immediately returning a task that will complete when the work is done.
var tcs = new TaskCompletionSource<double>();
  return tcs.Task;
…
tcs.TrySetResult(result);
Manually creating a Task that does not run on a separate thread is also easy:Once you have a TaskCompletionSource you can immediately hand out its associated Task, and complete it later when the work is done and the result is ready. The tasks generated by the async language feature are of the latter sort – they don’t occupy a thread of their own.

Tasks can represent exceptional as well as successful completion. If a Task ends up in a faulted state, the relevant Exception will be available, and awaiting the Task will result in its exception being propagated.

The easiest way to consume a Task is to await it in an async method, but there are also plenty of more “manual” ways to consume it – synchronously or asynchronously. These are outside the scope of this document (you can learn more about tasks in the MSDN documentation at http://msdn.microsoft.com/en-us/library/dd537609.aspx).

The Task-based asynchronous pattern

Part of this proposal is a shift to a new model for what asynchronous methods should look like – the Task-based Asynchronous Pattern (TAP). Current patterns offer one method for launching the operation and another method or event for obtaining the result. By returning a Task or Task<T> instead, as in the example above, only one method is needed, and all further interaction with the future result is done through the Task.

There are a couple of other conventions around the TAP, including how to handle cancellation and progress. These are further described in the Task-based Asynchronous Pattern document included in the Async CTP.

Async methods and awaiting

It is important to understand that async methods like SumPageSizesAsync do not run on their own thread. In fact if you write an async method without any await’s in it, it will be completely synchronous:

public async Task<int> TenToSevenAsync() {
    Thread.Sleep(10000);
    return 7;
}
If you call this method you will be blocked for ten seconds and then get an already completed Task<int> back with a result of 7. This is probably not what you expect, and async methods without await’s do yield a warning because they are almost never what you want.

Only when an async method gets to the first await will it return to its original caller. Even then, in fact, it won’t return until it await’s a task that is not yet complete. This means that you should write your async methods so that they do not do a lot of work, or perform blocking calls, before their first await – or indeed between await’s. Async methods are for doing things that don’t need a lot of thread time. If you want to get intensive work or unavoidable blocking calls off your thread – e.g. off the UI thread – you should explicitly put them on the thread pool using Task.Run.

Instead the right way to write the above method uses await:

public async Task<int> TenToSevenAsync() {
    await Task.Delay(10000);
    return 7;
}

Task.Delay is essentially the asynchronous version of Thread.Sleep: it returns a Task which completes after the specified amount of time. Given that, let us look in detail at how this very simple async method runs.

When the async method is first invoked, a Task<int> is immediately created. The method then executes up to the first (and in this case only) await. This means evaluating the “operand” to await, i.e. the call to Task.Delay, which quickly returns us an as-yet uncompleted Task.

Now we await that Task. This involves a number of steps, which are undertaken in an intricate collaboration between the compiler-generated code and the Task type:

1)      We check to see if the Task is already completed. If so, there’s nothing to wait for: we can just keep going. In this example, however, it is reasonable to assume that it is not yet completed.

2)      We capture the context we are running in. To a loose approximation this means a representation of where we are running. (Typically this is represented either as a SynchronizationContext or as a TaskScheduler, but you probably didn’t want to know that). Let us say that we were called on the UI thread: the context then represents that fact.

3)      We now sign up a callback to the Task, saying “when you complete, please do ‘this’.” We’ll see in a bit what ‘this’ actually does.

4)      Finally we return to the caller. Since this is the first await, we are returning to the original caller of TenToSevenAsync, and we make sure to return them the Task<int> that we started out by creating.

5)      About ten seconds later the Task we got from Task.Delay completes. It checks to see if it had any callbacks registered in the meantime. Indeed it has ours, which it calls.

6)      This probably happens on some kind of system thread that has to do with timers – a thread we don’t care about and definitely don’t want to be resumed on. However, all the callback does here is to ask the context that we captured before to resume the method execution there. So we quickly get off of the “random” thread that resumed us.

7)      The context schedules the resumption of the method according to its specific scheduling semantics. For the UI context this means queuing up the work in its message queue, from where it soon gets pumped onto the UI thread to be executed there.

8)      Back on the UI thread, the compiler-generated resumption code – often known as the continuation – knows how to jump into the middle of the execution of our method, right where we left off ten seconds before. In fact the compiler turned the async method into a state machine object just so that it would be able to do this. (This transformation is similar to what is done to implement iterators in C#.)

9)      The last action of the await expression is to consume the await’ed task’s result. In this case the task doesn’t produce a result, but we still check to see if the task was faulted – i.e. ended up completing with an exception. If that is the case, the exception is thrown again from the await expression.

We are now back in our method’s code following the await expression, and next up is the return statement, which also has special meaning in an async method. While it does return (in our case to the message pump that put us on the UI thread), it doesn’t return to our original caller: we already did that previously! Instead the return statement completes the already-returned Task<int> with a final result: the value seven.

The execution of the method is now finally complete. If the calling code signed up on the Task<int> in the meantime – e.g. by await’ing it – these callbacks in turn will now get invoked, and the cycle continues.

The execution of await looks – and is – somewhat complex. While the observable result is simple (you “wait” for something without occupying a thread), there is quite a bit of work going on under the hood to make it work. It is worth remembering that async methods are an alternative to having long-blocking calls. In comparison to the cost that such blocking incurs, the overhead of the bookkeeping involved in executing async methods is typically insignificant.

Further details about the syntax and semantics of the async language feature can be found in the C# and Visual Basic Language Specifications included in the Async CTP.

Event handlers and void returning async methods

Async methods can be built from other async methods using await. But where does the asynchrony end? What kind of top level synchronous methods call asynchronous ones to start with?

In a client application the typical answer is that asynchronous operations are set off by events. The user clicks a button, and an asynchronous activity is set in motion that keeps trickling little chunks of work onto the UI thread in between awaits, until it is finally done. The event itself does not care when the asynchronous operation is done – in fact no-one does. It is what we call “fire and forget.”

To accommodate this pattern, async methods can be explicitly written to be fire and forget – by returning void instead of Task or Task<TResult>. This lets the method have a signature that allows it to be signed up directly as an event handler. When a void async method runs, no Task is produced and returned, and it is therefore not possible for the caller to track its completion.

private async void sumButton_Click(object sender, RoutedEventArgs e) {
sumButton.IsEnabled = false;
await SumPageSizesAsync(GetUrls()));
sumButton.IsEnabled = true;
}

Often the UI needs to change for the duration of an operation caused by a user event. In this case for instance, the button clicked is temporarily disabled. The very natural and symmetric pattern of just enclosing the core operation in the code to change the UI and change it back is possible now only because of await.

Asynchronous lambda expressions

Not only methods but also lambda expressions can be async. Among other things this allows event handlers to be anonymous:

sumButton.Click += async (sender, e) => {
sumButton.IsEnabled = false;
await SumPageSizesAsync(GetUrls());
sumButton.IsEnabled = true;
};
Another useful application of asynchronous lambdas is for running asynchronous work on a background thread. Task.Run has overloads that expect delegates of type Func<Task> and Func<Task<TResult>> so that you can easily express this.
Follow

Get every new post delivered to your Inbox.

Join 379 other followers

%d bloggers like this: