Monday, March 11, 2013

Coding Tips and Tricks

Cyclic Constructor in C#
public class Car
    {
        //Private Member
        private int m_CarID=int.MinValue;
        private string m_CarType=string.Empty;
        private string m_CarName=string.Empty;
        private string m_Color=string.Empty;
        private string m_Model=string.Empty;

        //Constructor
        public Car()
        {
            //default Constructor
        }
       
        //Parameterized Constructor
        public Car(int carID, string carName)
        {
            m_CarID = carID;
            m_CarName = carName;
        }

        //Cyclic Constructor
        public Car(int carID, string carName, string carType,string carModel):this(carID,carName)
        {
            m_CarType = carType;
            m_Model = carModel;
        }

        //Cyclic Constructor
        public Car(int carID, string carName, string carType, string carModel,string color)
            : this(carID, carName,carType,carModel)
        {
            m_Color = color;           
        }   
    }

static void main()
{
    Car objCarA=new Car();
    Car objCarB=new Car(1,"matiz");
    Car objCarC=new Car(1,"matiz","SmallCar","2000");
    Car objCarD=new Car(1,"matiz","SmallCar","2000","Dark Green");
}

Validation to Check for Comma separated EmailIDs

Regular Exp Description:


List of Email ids separated with [,] Email ID may contain character set as [._-']

Regular Expression


^((\w+([-_.']\w+)*@\w+([-_.']\w+)*\.\w+([-_.']\w+)*)*([,])*)*$


Regular expression Rules:


Finite automata rule Values should proceed with email Ids with Comma Separated. No comma will precede the email IDs.

Matches:


abc.xyz@anonymous.com
abc.xyz@anonymous.com,abc-xyz@anonymous.com,abc_xyz@anonymous.com
abc.xyz@anonymous.com,com,D'Souza@anonymous.com

Non-Matches:


abc.xyz
,abc.xyz@anonymous.com
abc.xyz@anonymous.com,
abc

Javascript
function CheckForCommaSeperatedEmailIDs( fieldValue )  
       {      
     
         var regex = /^((\w+([-_.']\w+)*@\w+([-_.]\w+)*\.\w+([-_.]\w+)*)*([,])*)*$/;      
         if( !fieldValue.match( regex ) )      
           {         
             alert('The Email IDs Invalid');
            
                     return false;      
                       
            }     
               return true; 
         }




Validation to check UserID with Period/Dot seperated



Regular Expression Rules:

Finite automata rule, Values should precede with characters of set [A-Za-z] and followed with period(.) and character set [A-Za-z]

Regular Expression:

^[a-zA-Z]+(\.[a-zA-Z]+)+$


Matches



1) Ratan.Tata
2) Anil.Dhiru.Ambhani

Non-Matches



Ratan.
1) .Mukesh.
2) Amir.khan.

Regular Expression Logic in Javasctipt




function CheckForPeriodSeperatedUserID( fieldValue ) 
     {
        var regex = /^[a-zA-Z]+(\.[a-zA-Z]+)+$/;
        if( !fieldValue.match( regex ) ) 
        {
            alert('The UserID is not desired format,XXX.YYYY XXX.YYYY.ZZZZ');
            return false;
        }
        return true;
    }
Real Time Use Of Static Constructor
if you look at above class it is an Utility class and it is consume by Business entity class instance say object Date that has minute component in it.

If we have 10 screens that requires minutes to be displayed in dropdownlist in such cases rather then calling 10 calls to database or constructing this collection we prefer calling one instance at the very load of the application which in turns consume by all the pages and across all the users. In the process we have one instance available for all users and across pages. If one see in normal constructor ,one can notice it is invoked after instance is created whereas static constructor is invoked always first and when it is referenced.
use System.collection.generics;

public class Utility
{
public static IDictionary
m_Minute = null;
static Utility()
{
m_Minute=new IDictionary
();
m_Minute.Add(1,"00");
m_Minute.Add(2,"15");
m_Minute.Add(3,"30");
m_Minute.Add(3,"45");
}
public static IDictionary
GetMinute()
{
return m_Minute;
}
}




Validation to Check for special Character

Description :


Below javascript code function returns false for entered special character and true for non special character.



 
function CheckForSpecialCharacter( controlValue ) 
     {
        var regex = /^[a-zA-Z0-9\s]+$/;
        if( !controlValue.match( regex ) ) 
        {
            alert('Special Character is not allowed due potential security threat.');
            return false;
        }


Problem Statement:

We have scenario where we have data stored in arraylist collection and want to pass this as data as input to Webservice method in string array format.


Convert ArrayList() Collection to String [] Array

Namespace: System.collections




Solution:




private string[] ConvertArrayListToStringArray(ArrayList arrList)
{

 for (int iIter=0;iIter<5 br="" iiter=""> {
  arrList.Add("StringValue"+iIter);
 }
 return string[]arrList.ToArray(typeof(string)); 
}


 

Iterator,Delegate,Predicates,Anonymous method and Generics C#2.0

A perfect blend of Iterator,Delegate,Predicates,Anonymous method and Generics C#2.0. One can make use of these in real world scenario to save memory and increase performance of an application.

Delegates defines signature of any method that takes one input parameter and returns a single object of another type.



public delegate Tout Action(Tin element);
protected void Page_Load(object sender, EventArgs e)
{
    foreach (string str in GetFormatedCustomerName())
            Response.Write(str);
}
public IEnumerable GetFormatedCustomerName()
{ 
     List customerList=new List();
     customerList.Add(new Customer("001", "Santosh",3552));
     customerList.Add(new Customer("002", "Poojari", 42424));
     customerList.Add(new Customer("005", "Arjun", 42424));

     return BuildFormattedName(customerList,
     delegate(Customer objCustomer)
     {
          return string.Format("{0} - {1}
", objCustomer.CustomerId, objCustomer.CustomerName);
     });
}
public IEnumerable BuildFormattedName(IEnumerable list, Action handler)
{
    foreach (Tin entry in list)
           yield return handler(entry);
}        



Post a Comment