Jun 30

Abstract Class

Abstract class is a class that can not be instantiated. To use it you need to inherit it. This class can be used as a base class where you can define certain method that must be implemented in derived class (Class that is going to inherit it) along with that you can also define certain methods that is frequently used and can be directly used by Derived class or overriden in the derived class if needed.

In the abstract class, you can define following:

  1. Normal property – this property is similar to any other property we define in a normal class
  2. Abstract property – this will have only get and set accessor but no implementation.
  3. Normal method – this method is similar to any other method that you define in a normal class
  4. Abstract method – this will not have any implementation
  5. Virtual method – this will have implementation but can also be overridden in the derived class to provide additional logic or completely replace its logic

Abstract Class
In order to explain Abstract class, I am going to take a simple example of ParentClass class that has all methods and properties explained above and it looks like below :

ParentClass.cs

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

///
/// Summary description for ParentClass
///

public abstract class ParentClass
{
public ParentClass()
{
}
private int age = 0;
// Normal property
public int Age_Normal
{
get
{
return age;
}
set
{
age = value;
}
}
// Abstract property
public abstract string Address_Abstract
{
get;
set;
}
// Normal Methods
public string GetName(string firstName, string lastName)
{
return “My Name is : ” + GetName_Virtual(firstName, lastName);
}
public int Divide_NotAbstract(int a, int b)
{
return a / b;
}
// Abstract Methods
public abstract int Add_Abstract(int a, int b);
public abstract int Subtract_Abstract(int a, int b);

// Virtual method
public virtual string GetName_Virtual(string firstName, string lastName)
{
return firstName + ” ” + lastName;
}
}

As you can see, the first property I have above is Age_Normal, this is a normal property similar to other property that we define in the class that has its implementation as well and it can be simply accessed by the instance of the dervied class.

Next we have an Abstract property Address_Abstract that has only get and set accessor and no implementation.

Next we have normal method that is similar to any other method we define in a normal class.

Next we have Abstract methods that contains abstract keyword in its definition, this doesn’t have any implementation. (Defining abstract methods and properties are similar to defining properties and methods in an interface). One thing to note is that an abstract methods or properties can only be defined in Abstract class, you can’t define them in a normal class.

Next we have a virtual method that let us use its logic directly or also allow us to completely override its logic.

Derived Class
Below is my derived class (that is inheriting above abstract class), its name is DerivedClass (Some of the method or property names may look strange, I have just kept this for easy understanding, please bear with me).

DerivedClass.cs

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
///
/// Summary description for Calculate
///

public class DerivedClass : ParentClass
{
private string address = string.Empty;
public DerivedClass()
{
}
//override the abstract property
public override string Address_Abstract
{
get
{
return address;
}
set
{
address = value;
}
}
// override the abstract method
public override int Add_Abstract(int a, int b)
{
return a + b;
}
public override int Subtract_Abstract(int a, int b)
{
return a – b;
}
// override virtual method
public override string GetName_Virtual(string firstName, string lastName)
{
return “(Overriden) Name: ” + firstName + ” ” + lastName;
}
// hide normal method of the abstract class
public new string Divide_NotAbstract(int a, int b)
{
int d = a/b;
return “The division is: ” + d.ToString();
}
// use abstract property to retrieve its value
public string GetAddress()
{
return Address_Abstract;
}
}
In the above class I am doing following:

First, I am overriding the Address_Abstract property, as I had declared it as Abstract property. Note that to implement the abstract property or method, you need to use override keyword.

Next, I am overriding two methods Add_Abstract and Sub_Abstract as these methods are declared as Abstract method.

Next I had declared GetName_Virtual method as virtual method so I have freedom to either override it or use it as it is. If we want to use the original method, we can choose not to override it but if we want to modify its logic then we will have to override it. I preferred to override so I have redefined my logic here.

Next I have made Divide_NoAbstract method of Parent class as hidden by specifying new keyword in the definition of derived class. Even if I have made the original parent class method as hidden if at some place we want to use the orginial abstract class method, we can use that, I will show you how to use that later.

How to use Derived and Abstract class methods
Below is the code that shows how to use above abstract class and derived class methods or properties.

DerivedClass c = new DerivedClass();
Response.Write(“Abstract method – Sum: ” + c.Add_Abstract(50, 30).ToString() + “
“);
Response.Write(“Abstract method – Subtract: ” + c.Subtract_Abstract(50, 30).ToString() + “
“);
Response.Write(“Virtual Method – GetName_Virtual: ” + c.GetName_Virtual(“SHEO”, “NARAYAN”) + “
“);
Response.Write(“Normal Public Method – GetName: ” + c.GetName(“SHEO”, “NARAYAN”) + “
“);
Response.Write(“Normal Public Method being hidden using new keyword – Divide_NotAbstract: ” + c.Divide_NotAbstract(50, 30).ToString() + “
“);
ParentClass p = new DerivedClass();
Response.Write(“Normal Public Method from Abstract Class – Divide_NotAbstract: ” + p.Divide_NotAbstract(50, 30).ToString() + “
“);
c.Address_Abstract = “Sheo Narayan, Hitec City, Hyderabad.”;
Response.Write(“Normal Public method accessing
overriden Abstract Property – GetAddress:
” + c.GetAddress() + “

“);
Above code snippet will give following results

Abstract method – Sum: 80
Abstract method – Subtract: 20
Virtual Method – GetName_Virtual: (Overriden) Name: SHEO NARAYAN
Normal Public Method – GetName: My Name is : (Overriden) Name: SHEO NARAYAN
Normal Public Method being hidden using new keyword – Divide_NotAbstract: The division is: 1
Normal Public Method from Abstract Class – Divide_NotAbstract: 1
Normal Public method accessing
overriden Abstract Property – GetAddress: Sheo Narayan, Hitec City, Hyderabad.
In the above code snippet, first I instantiated the DerivedClass method and start calling the both Abstract methods Add_Abstract and Subtract_Abstract that were implemented in the Derived class.

Next I have called the Virtual method of the Abstract class that was overriden in the Derived class. You can see the implementation of GetName_Virtual method in the Derived class that is prefixing “(Overriden) Name” with the result.

Next line is calling a normal method GetName that was defined in the Parent abstract class.

Next line is calling the method Divide_NoAbstract that is hiding the main normal method Divide_NoAbstract of Parent class by specifying the new keyword in its definition in the derived class.

Now lets suppose, you already have made the Parent class method (as explained in the above line) hidden but still in a certain scenario, you want to call the Parent class method. To do that, we need to instantiate the Derived Class by specifying it as the ParentClass by writing it as ParentClass p = new DerivedClass();. This is giving me the reference of Parent class and when called Divide_NoAbstract method, this will call the Parent class Divide_NoAbstract method not Derived class method.

The very next line is setting the property of the Derived class that is nothing but the implementation of the ParentClass Address_Abstract property and calling the Derived class GetAddress method that is simply returning this property value.

Permanent link to this article: http://zappmania.in/2012/06/30/abstract-class.htm

Jun 28

What are session management techniques in .NET?

There are three different techniques of managing session in ASP.NET
InProc 
Session state is stored locally in memory of ASP.NET worker process.

StateServer 
Session state is stored outside ASP.NET worker process and is managed by Windows service. Location of this service is specified by stateConnectionString attribute.

SQLServer 
Session state is stored outside ASP.NET worker process in SQL Server database. Location of this database is represented by sqlConnectionString attribute.


InProc

Adv.:
1) Faster as session resides in the same process as the application
2) No need to serialize the data

DisAdv.:
1) Will degrade the performance of the application if large chunk of data is stored
2) On restart of IIS all the Session info will be lost

State Server
Adv.:
1) Faster then SQL Server session management
2) Safer then InProc. As IIS restart
won’t effect the session data

DisAdv.:
1) Data need to be serialized
2) On restart of ASP.NET State Service session info will be lost
3)Slower as compared to InProc

SQL Server
Adv.:
1) Reliable and Durable
2) IIS and ASP.NET State Service
restart won’t effect the session data
3) Good place for storing large chunk of data

DisAdv.:
1) Data need to be serialized
2) Slower as compare to InProc and State Server
3)Need to purchase Licensed
version of SQL Server

Permanent link to this article: http://zappmania.in/2012/06/28/what-are-session-management-techniques-in-net.htm

Jun 27

C# Custom Enumerators Made Simple with the Yield Keyword

An enumerator enables you to iterate over a collection in a foreach loop. You can use foreach to iterate over all C# collection classes, because all C# collection classes inherit from the IEnumerable interface (regular or generic). IEnumerable contains the GetEnumerator method, which returns an enumerator.
Occasionally you may find a need to create a custom enumerator, which used to be somewhat of a challenge until the yield keyword was introduced. Here is how Microsoft describes yield:


The yield keyword signals to the compiler that the method in which it appears is an iterator block. The compiler generates a class to implement the behavior that is expressed in the iterator block. In the iterator block, the yield keyword is used together with the return keyword to provide a value to the enumerator object. This is the value that is returned, for example, in each loop of a foreach statement.


So rather than creating your own enumerator class and managing the enumeration state — which is time consuming and tricky — you can simply write the enumeration logic in the GetEnumerator method, and the yield keyword will automagically wrap your code in a handy-dandy enumerator.



Custom Enumerator Example: Wrap a Collection

To demonstrate the power of yield, let’s create a simple custom enumerator. In this example problem, we have a collection of Base objects, but we only want to work with Derived objects.
So imagine two classes, where the “Derived” class inherits from the “Base” class:

public class Base
{
public Base( string name )
{
this.Name = name;
}
public string Name;
}
public class Derived : Base
{
public Derived( string name )
: base( name ) { }
}

We also define a collection of Base objects:

public class BaseColl : List { }

But for this sample problem, we want to work only with Derived objects in the Base collection. To make it easy for developers to use, we’ll create a Derived collection that wraps a Base collection. Notice how the DerivedColl constructor takes a reference to the BaseColl that it wraps:
public class DerivedColl : IEnumerable
{
public DerivedColl( BaseColl baseColl )
{
this.m_BaseColl = baseColl;
}
private BaseColl m_BaseColl;
}


Yield Keyword

Missing from the DerivedColl code above is the GetEnumerator method where the “yield” magic occurs:

public IEnumeratorGetEnumerator()
{
foreach (Base b in this.m_BaseColl)
{
Derived d = b as Derived;
if (d != null)
yield return d;
}
}

The foreach code above iterates over the Base objects in the wrapped BaseColl collection. If the Base object is a Derived object (d != null), then the yield keyword returns it. The effect is that the enumerator returned by this GetEnumerator method iterates over ONLY the Derived objects in the Base collection.
Quite handy! If you’ve ever spent time writing a custom enumerator class, you will welcome the yield keyword.



Sample Program

Here is a sample console program:

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

namespace CSharp411
{
class Program
{
public class Base
{
public Base( string name )
{
this.Name = name;
}
public string Name;
}
public class Derived : Base
{
public Derived( string name )
: base( name )
{
}
}

public class BaseColl : List { }
public class DerivedColl : IEnumerable
{
public DerivedColl( BaseColl baseColl )
{
this.m_BaseColl = baseColl;
}
private BaseColl m_BaseColl;
public IEnumerator GetEnumerator()
{
foreach (Base b in this.m_BaseColl)
{
Derived d = b as Derived;
if (d != null)
yield return d;
}
}
System.Collections.IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}

static void Main( string[] args )
{
BaseColl baseColl = new BaseColl();
DerivedColl derivedColl = new DerivedColl( baseColl );

Base b = new Base( “Base1” ); baseColl.Add( b );
b = new Base( “Base2” ); baseColl.Add( b );
Derived d = new Derived( “Derived1” ); baseColl.Add( d );
d = new Derived( “Derived2” ); baseColl.Add( d );
b = new Base( “Base3” ); baseColl.Add( b );
b = new Base( “Base4” ); baseColl.Add( b );
d = new Derived( “Derived3” ); baseColl.Add( d );
d = new Derived( “Derived4” ); baseColl.Add( d );

foreach (Derived derived in derivedColl)
{
Console.WriteLine( derived.Name );
}
Console.ReadLine();
}
}
}

Sample Output

The output is only the Derived objects:

Derived1
Derived2
Derived3
Derived4

Permanent link to this article: http://zappmania.in/2012/06/27/c-custom-enumerators-made-simple-with-the-yield-keyword.htm

Jun 27

Reflection in C# – List of Class Name, Method Name

Reflection is way through which we can identify metadata about assembly runtime.
Example: We have a .Net Assembly file (.dll file), which consist of 2 Class Definition and 10 Method Names, We can get information about classes and method name list through reflection.

Few Examples of Reflection

Loading Assembly File 

Assembly assem = Assembly.LoadFrom(sAssemblyFileName);

Get List of Class Name.
Type[] types = assem.GetTypes();

Get List of Method Name 

foreach (Type cls in types)
{
try
{
//Add Namespace Name
arrl.Add(cls.FullName);

//Add Class Name
if(cls.IsAbstract)
arrl.Add(“Abstract Class:” + cls.Name.ToString());
else if(cls.IsPublic)
arrl.Add(“Public Class:” + cls.Name.ToString());
else if(cls.IsSealed)
arrl.Add(“Sealed Class:” + cls.Name.ToString());
MemberInfo[] methodName = cls.GetMethods();
foreach (MemberInfo method in methodName)
{
if (method.ReflectedType.IsPublic)
arrl.Add(“tPublic – ” + method.Name.ToString());
else
arrl.Add(“tNon-Public – ” + method.Name.ToString());
}
}
catch (System.NullReferenceException)
{
Console.WriteLine(“Error msg”);
}
}


A Sample Application Showing Good Usage of Reflection in .Net
Following application shows how to identify list of Classes and Method in any .Net Assembly file with the help of .Net Reflection. For an example I am using Ajax Assembly filename to list all its classname and method name.
Step 1: Design a web form consisting of following controls.
Label – Shows text “Assembly File Name”
Textbox – Taking Input Assembly File Name.
Listbox – For displaying list of Class Names and Method Names
Button – On Button Click Event Display List of Class Name and Method Name

Step 2: Write following code on Button_Click Event.

private void btnListMethodName_Click(object sender, EventArgs e)
{
string sAssemblyFileName = txtAssemblyFileName.Text;

if (sAssemblyFileName.Length != 0)
{
Assembly assem = Assembly.LoadFrom(sAssemblyFileName);
Type[] types = assem.GetTypes();
ArrayList arrl = new ArrayList();
foreach (Type cls in types)
{
try
{
//Add Class Name
arrl.Add(cls.FullName);
if(cls.IsAbstract)
arrl.Add(“Abstract Class:” + cls.Name.ToString());
else if(cls.IsPublic)
arrl.Add(“Public Class:” + cls.Name.ToString());
else if(cls.IsSealed)
arrl.Add(“Sealed Class:” + cls.Name.ToString());

MemberInfo[] methodName = cls.GetMethods();
foreach (MemberInfo method in methodName)
{
//arrl.Add(“t” + method.Name.ToString());
if (method.ReflectedType.IsPublic)
arrl.Add(“tPublic – ” + method.Name.ToString());
else
arrl.Add(“tNon-Public – ” + method.Name.ToString());
}
}
catch (System.NullReferenceException)
{
Console.WriteLine(“Error msg”);
}
}

//Dump Data to NotePad File
FileStream fs = new FileStream(@”c:myData.txt”, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
StreamWriter sw = new StreamWriter(fs);
for (int i = 0; i < arrl.Count; i++)
{
lstInfo.Items.Add(arrl[i].ToString());
sw.WriteLine(arrl[i].ToString());
}
sw.Flush();
sw.Close();
}
}

Permanent link to this article: http://zappmania.in/2012/06/27/reflection-in-c-list-of-class-name-method-name.htm

Jun 27

Android application development beginners guide

Well, I have search lot for “Android application development tutorial for .Net Developer” and other related terms to find any tutorial for .net developer to make android application. This article is conclusion of my research and a good start up point for anyone having little java knowledge or interested in android application development.

Few things you should keep in mind (Source of Information)
It’s a know fact that Android is an operating system based upon Linux which has a Java programming interface. It offers tools, e.g. a compiler, debugger along with a device emulator combined with particular Java Virtual machine (DVM). Android is made by the Open Handset Alliance which is lead by Google. Android supports 2-D and 3-D graphics utilizing the OpenGL libraries and supports data storage inside a SQLLite database. Google provides for development the Android Development Tools (ADT) for Eclipse to produce Android applications.

Every Android application works in its own process and is isolated from all other running applications. Therefore on misbehaving application cannot harm other Android applications.

If you wish to write programs for Android then according to My online research indicates that the following steps are a good kick off point to to become a master Android programmer:
1. Learn Java. (Its very easy for C# developer)
2. Install the Android Developer Kit, Eclipse, and the Eclipse plug-in for Android programming.
3. Figure out how to use Eclipse with the Android plug-in.
4. Learn how to design Java programs for Android.

So, if you are ready to develop your first “Hello World Application for Android” then here are some good Android tutorial links to start.

 

If you are new to java or planning to refresh your past java learning then here is good quick start up tutorial for Java

Since android application development market is huge and it just a beginning, so its worth investing time behind it

Permanent link to this article: http://zappmania.in/2012/06/27/android-application-development-beginners-guide.htm