Search This Blog

Wednesday, December 16, 2009

Ref and Out Parameters In C#


Value Parameters

Passing Value Types by Value

We often call the class methods through the class instances and by passing parameters. These parameters have all been passed by value. While we pass the value types of a parameter, this means that a copy of the value's contents has been passed. As only a copy of the contents is available, the external variable's value cannot be modified from within the method.

The following example code demonstrates the use of value parameters with variables that are value types. In this sample, a value type variable is declared and its value is assigned. This variable is then used as the value of a parameter. The variable is passed to the method parameter by value and the parameter's value is changed within the method, but the original variable remains unaffected.

Public class CallMathod
{

public void CallMethod()
{
    int original = 100;
    CallingMathod obj = new CallingMathod();           
    obj.showValue(original);
    Label1.Text="Original: "+ original.ToString();;
}
}
 
Public class CallingMathod
{
 
static void showValue(int valueToShow)
{
    valueToShow *=2;
    Label2.Text="Double: "+ valueToShow.ToString();
}
}
 OUTPUT
 
Double: 200
Original: 100
 

Passing Reference Types by Value

When we pass the reference types by value rather value types by value, a copy of the reference is made. This means that any changes to the object's properties that occur within the method will be reflected outside of the method too. This is because both the external variable and the variable within the method contain the same references to the same underlying object data in memory. However, if the variable inside the method is assigned a completely new value, and therefore a different reference to the external variable, this change is not reflected outside of the method.

To demonstrate, consider the following code. This uses a "StudentClass" class that contains a single property for the student's roll number. When calling the GetRollNumber method, the Student is passed by reference. Increasing the Roll Number property within the method is visible outside of the method too. However, when the GetNewNumber method is called, the reassigned object is not seen externally to the method.

Public class CallMathod
{

public void CallMethod()
{
        Student objStudent = new Student ();
        objStudent.rollNumber = 004512;
 
        GetRollNumber(objStudent);
        Label1.Text ="Roll Number: "+ objStudent.rollNumber;
 
        GetNewNumber(objStudent);
        Console.WriteLine("Roll Number: {0}", objStudent.rollNumber);
 
         OUTPUT
 
        Diameter: 004513
        Diameter: 004513
 
        
 
}
 
    static void GetRollNumber(Student objSt)
    {
        objSt.rollNumber++;
    }
 
    static void GetNewNumber(Student objSt)
    {
        objSt = new Student();
        objSt.rollNumber = 1;
    }
 
}
 
Public class Student
{
 
    private int _rollNumber;
    
    public int rollNumber
    {
        get
        {
            return _rollNumber;
        }
        set
        {
            _rollNumber = value;
        }
    }
 
 
}
 


 
 

Reference Parameters

Passing Value Types by Reference

An alternative to passing parameters by value is passing by reference. When using reference parameters for value types a copy of the value is not made. Instead, the variable used in the parameter is itself passed to the called method. This makes the behaviour similar to using reference types in value parameters; any changes to the value of the parameter variable is also seen outside of the method.

A reference parameter is declared using the ref keyword before the parameter type and name. This prefix is also used when calling the method.

The following sample code is based upon the first example in this article but by using a reference parameter rather than a value parameter, the results seen are different.

static void CalleeMethod()
{
    int original = 100;
    CallingMathod obj = new CallingMathod();         
    obj.showValue(ref original);              
    Label1.Text = "Original: "+original.ToString();
}
 
Public class CallingMathod
{
 
static void showValue(int valueToShow)
{
    valueToShow *=2;
    Label2.Text="Double: "+ valueToShow.ToString();
}
}
 OUTPUT
 
Double: 200
Original: 200
 


Passing Reference Types by Reference:

Reference type data can be passed to reference parameters. In this case, rather than passing a copy of the reference to the method, as when using value parameters, the reference variable itself is passed. In this situation, property changes within the method are reflected outside of the method as expected. However, if the variable is reassigned within the method, the variable outside of the method is also reassigned.

By modifying the earlier example relating to the Student class to use reference parameters, this can be demonstrated. In the following code the student’s rollNumber is increased by 1 as is was previously with the reference parameters showing no apparent difference in functionality. When the GetNewNumber method is called, the student variable is reassigned as a completely new object.

Public class CallMathod
{

public void CallMethod()
{
        Student objStudent = new Student ();
        objStudent.rollNumber = 004512;
 
        GetRollNumber(ref objStudent);
        Label1.Text ="Roll Number: "+ objStudent.rollNumber;
 
        GetNewNumber(objStudent);
        Console.WriteLine("Roll Number: {0}", objStudent.rollNumber);
 
         OUTPUT
 
        Diameter: 004513
        Diameter: 000001
 
        
 
}
 
    static void GetRollNumber(ref Student objSt)
    {
        objSt.rollNumber++;
    }
 
    static void GetNewNumber(ref Student objSt)
    {
        objSt = new Student();
        objSt.rollNumber = 000001;
    }
 
}
 
Public class Student
{
 
    private int _rollNumber;
    
    public int rollNumber
    {
        get
        {
            return _rollNumber;
        }
        set
        {
            _rollNumber = value;
        }
    }
 
 
}
 


Output Parameters

When we need to return more than one value from a method, one value can be returned using the normal return command with additional values being extracted using output parameters.

An output parameter is declared using the out keyword before the parameter type and name. When called, the out keyword is used again as a prefix to the variable being passed as a parameter. The behavior seen is similar to passing by reference in that the variable must be assigned a value within the method. This value will then be reflected in the output parameter.

static void CalleeMethod()
{
    decimal x = 10.00;
    decimal y = 200.00;
    decimal area;
    decimal perimeter;
 
    CallingMathod obj = new CallingMathod();         
    area =obj.GetArea(x,y,out perimeter);     
        
    Label1.Text = "Area: "+ area.ToString();
    Label2.Text = "Perimeter: "+ perimeter.ToString();
 
}
 
Public class CallingMathod
{
 
static decimal GetArea(int x,int y,out int perimeter)
{
    perimeter = 2*(x+y);
    return (x*y);
}
}
 OUTPUT
 
Area: 2000.00
Perimeter: 420.00
 



Colclussion:
OUT :

Variable gets value initialized after going into the method.
Later the same value is returned to the main method.
Ref :
Variable should be initialized before going into the method.
Later same value or modified value will be returned to the main method

Tuesday, September 8, 2009

Data Insert By XML


I have created two types of Xml based data insert Update etc..here.Basically for Bulck insert we use such process to enter or update data inside database and can avoide the hectick parameter passing process by passing the whole xml as a single string.We collect data and generate the dynamic xml and pass it to the stolred procedure.

Here is my class architecture.

For the Faculty there exists one to many mapping between Faculty - College (Consider guest lecturer) and Faculty-Department.So List collections are taken for College and Department to save Faculty data.
have a look at my Faculty class methods

#endregion
#region Internal Methods
internal string GetXML()
{
XmlDocument xDoc = new XmlDocument();
XmlElement xStudentDetail;
xStudentDetail = (XmlElement)xDoc.CreateElement("FacultyDetails");
//this.IsActive = true;
xStudentDetail.SetAttribute("FacultyDetailsID", this.IdNo.ToString());
xStudentDetail.SetAttribute("PersonalAddress", this.PersonalAddress.ToString());
xStudentDetail.SetAttribute("Name", this.Name.ToString());
xStudentDetail.SetAttribute("OtherCharges", this.OtherCharges.ToString());
if (this.CollegeDetails != null)
{
XmlElement xStudentDetails;
xStudentDetails = (XmlElement)xDoc.CreateElement("CollegeDetails");
foreach (College objCollegeDetails in this.CollegeDetails)
{
xStudentDetails.InnerXml = xStudentDetails.InnerXml + objCollegeDetails.GetXML();
}
xRentAgreement.AppendChild(xStudentDetails);
}
xDoc.AppendChild(xStudentDetail);
return xDoc.InnerXml;
}
///
/// This internal method is used for saving the Student details into the database
///

///
internal int SaveFacultyInfo()
{
DataAccess dataAccess = null;
DataSet dsFaculty;
int iFunctionId = 0;
try
{
DataAccess = new DataAccess(_connectionString);
SqlParameter[] sqlParams = new SqlParameter[1];
sqlParams[0] = new SqlParameter("@sFacultyXML", this.GetXML());
dsFaculty = dataAccess.ExecuteDataSet("spSaveFacultyDetails", CommandType.StoredProcedure, sqlParams);
foreach (DataRow dr in dsFaculty.Tables[0].Rows)
{
iFunctionId = Convert.ToInt32(dr[0]);
}
}
finally
{
if (dataAccess != null)
{
if (dataAccess.DataConn != null)
{
//Close the dataset connection
dataAccess.DataConn.Close();
}
}
}
return iFunctionId;
}

///
/// This internal method is used for getting the student details from the database
///

///
internal void GetFacultyInfo()
{
DataAccess dataAccess = null;
DataSet dsFaculty;
DataRow[] drs;
try
{
DataAccess = new DataAccess(_connectionString);
SqlParameter[] sqlParams = new SqlParameter[1];
sqlParams[0] = new SqlParameter("@sFId", studentId);
dsFaculty = dataAccess.ExecuteDataSet("spGetFacultyDetails", CommandType.StoredProcedure, sqlParams);
}
finally
{
if (dataAccess != null)
{
if (dataAccess.DataConn != null)
{
//Close the dataset connection
dataAccess.DataConn.Close();
}
}
}
}
#endregion
}
}




the GetXML() method will collect the information and populate it into a XML

#region Internal Methods
internal string GetXML()
{
XmlDocument xDoc = new XmlDocument();
XmlElement xStudentDetail;
xStudentDetail = (XmlElement)xDoc.CreateElement("FacultyDetails");
//this.IsActive = true;
xStudentDetail.SetAttribute("FacultyDetailsID", this.IdNo.ToString());
xStudentDetail.SetAttribute("PersonalAddress", this.PersonalAddress.ToString());
xStudentDetail.SetAttribute("Name", this.Name.ToString());
xStudentDetail.SetAttribute("OtherCharges", this.OtherCharges.ToString());
if (this.CollegeDetails != null)
{
XmlElement xStudentDetails;
xStudentDetails = (XmlElement)xDoc.CreateElement("CollegeDetails");
foreach (College objCollegeDetails in this.CollegeDetails)
{
xStudentDetails.InnerXml = xStudentDetails.InnerXml + objCollegeDetails.GetXML();
}
xRentAgreement.AppendChild(xStudentDetails);
}
xDoc.AppendChild(xStudentDetail);
return xDoc.InnerXml;
}

For Collecting the College information there is also a GetXML method inside College Class.It will add the ollege info as a child node to the faculty XML.

#region Internal Methods
///
/// this method will get the object in xml format
///

///
/// Subhamay Sur
internal string GetXML()
{
XmlDocument xDoc = new XmlDocument();
XmlElement xCollege;
xCollege = (XmlElement)xDoc.CreateElement("CollegeInfo");
xCollege.SetAttribute("CollegeInfo", this.CollegeID.ToString());
xCollege.SetAttribute("UniversityRegNo", this.UniversityRegNo.ToString());
xCollege.SetAttribute("CollegeName", this.CollegeName.ToString());
xCollege.SetAttribute("CollegeAddress", this.CollegeAddress.ToString());
xCollege.SetAttribute("CollegeStatus", this.CollegeStatus.ToString());
xCollege.SetAttribute("IsAICTEApproved", this.IsAICTEApproved.ToString());
xCollege.SetAttribute("IsWBSEBApproved", this.IsWBSEBApproved.ToString());
if (this.DepartmentDetails != null)
{
XmlElement xDeparmentDetails;
xDeparmentDetails = (XmlElement)xDoc.CreateElement("DepartmentDetails");
foreach (Department objDepartmentDetails in this.FacultyDetails)
{
xDeparmentDetails.InnerXml = xDeparmentDetails.InnerXml + objDepartmentDetails.GetXML();
}
xCollege.AppendChild(xCollegeDetails);
}
xDoc.AppendChild(xCollege);
return xDoc.InnerXml;
}

#endregion

To save this string formatted string the Stored Procedure will be like

INSERT INTO #TempFaculty
(
[PersonalAddress],
[Department],
[Name],
[OtherCharges]
)
SELECT
T.F.value('@PersonalAddress','VARCHAR(200)'),
T.F.value('@Name','VARCHAR(200)'),
T.F.value('@OtherCharges','decimal(14, 2)')
FROM @sFacultyXML.nodes('/FacultyDetails') T(F)



CREATE TABLE #TempTableRentAgreementVendorMap
(
[RentAgreementID] INT,
[VendorNo] VARCHAR(200),
[AmountShareRent] DECIMAL(14, 2),
[AmountShareMaintenance] DECIMAL(14, 2),
[AmountShareOthers] DECIMAL(14, 2)
)
INSERT INTO #TempTableFacultyCollegeMap
(
[CollegeId],
[UniversityRegNo],
[CollegeName],
[CollegeAddress],
[IsAICTEApproved] ,
[IsWBSEBApproved]
)
SELECT
T.F.value('@CollegeId','INT'),
T.F.value('@UniversityRegNo','VARCHAR(200)'),
T.c.value('@CollegeName','decimal(14, 2)'),
T.F.value('@CollegeAddress','decimal(14, 2)'),
T.F.value('@IsAICTEApproved','decimal(14, 2)') ,
T.F.value('@IsWBSEBApproved','decimal(14, 2)')
FROM @sFacultyXML.nodes('/FacultyDetails/CollegeInfo') T(F)






Thursday, September 3, 2009

Bind DropDownList Using Cache Value

Here I have created an AppCacheManager Class where i define some methods for Insert to Cache,Remove From Cache,Refresh Cache etc..
We need to use a synchronization primitive lock which is provided by the .NET Framework. Basically this mechanism allows a thread to acquire a lock on an instance of an object. Which means, only one thread can acquire a lock on the object and other threads have to wait until the original thread releases the lock .But if we lock the cache object directly it will be a huge performance issue.Acctullay we have to make sure that a)multiple threads can read cache data simultaneously, b)only one thread is allowed to update the cache at a time c) When a thread is updating the cache, all the threads that want to read the cache data should wait until the update is complete
The .NET framework provides another thread synchronization primitive called ReaderWriterLock
My Cache Manager Class is like that
using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using System.Data;
using System.Web.Caching;
using System.Threading;
using System.Reflection;
using AppConfigurationManagement
namespace CacheManagement
{
// contains the methods for cache management for Add ,Remove,Refresh
public static class AppCacheManager
{
private static System.Web.Caching.Cache _CacheManager = System.Web.HttpContext.Current.Cache;
private static ReaderWriterLock _ReadWriteLock;
static AppCacheManager ()
{
_ReadWriteLock = new ReaderWriterLock();
if (System.Web.HttpContext.Current != null)
{
_CacheManager = System.Web.HttpContext.Current.Cache;
}
else
{
_CacheManager = System.Web.HttpRuntime.Cache;
}
}
// Method to add object in cache
public static void AddToCache(EnumeratorsConfiguration.CacheKey key, object keyData)
{
try
{
// Aquire Writer Lock
_ReadWriteLock.AcquireWriterLock(60000);
_CacheManager.Insert(key.ToString(), keyData);
}
finally
{
if (_ReadWriteLock.IsWriterLockHeld)
{
_ReadWriteLock.ReleaseWriterLock();
}
}
}
/// Method to remove object from cache,
/// it removes object for all keys which starts with value of key
public static void RemoveFromCache(EnumeratorsConfiguration.CacheKey key)
{
try
{
_ReadWriteLock.AcquireWriterLock(60000);
System.Collections.IDictionaryEnumerator dicEnum;
dicEnum = _CacheManager.GetEnumerator();
while(dicEnum.MoveNext() == true)
{
if (((string)dicEnum.Key).StartsWith(key.ToString()))
{
_CacheManager.Remove((string)dicEnum.Key);
}
}
}
finally
{
//Release the write lock
if (_ReadWriteLock.IsWriterLockHeld)
{
_ReadWriteLock.ReleaseWriterLock();
}
}
}
/// Method to remove object from cache,
/// it removes object for all keys which starts with value of key
public static void RemoveFromCache()
{
try
{
_ReadWriteLock.AcquireWriterLock(60000);
System.Collections.IDictionaryEnumerator dicEnum;
dicEnum = _CacheManager.GetEnumerator();
while (dicEnum.MoveNext() == true)
{
if (IsCacheable(dicEnum.Key.ToString()))
_CacheManager.Remove((string)dicEnum.Key);
}
}
finally
{
//Release the write lock
if (_ReadWriteLock.IsWriterLockHeld)
{
_ReadWriteLock.ReleaseWriterLock();
}
}
}
public static DataTable GetCacheList()
{
try
{
_ReadWriteLock.AcquireWriterLock(60000);
System.Collections.IDictionaryEnumerator dicEnum;
dicEnum = _CacheManager.GetEnumerator();
DataTable dtCache = new DataTable();
dtCache.Columns.Add("Key");
while (dicEnum.MoveNext() == true)
{
if (IsCacheable(dicEnum.Key.ToString()))
{
DataRow drCache = dtCache.NewRow();
drCache["Key"] = dicEnum.Key.ToString();
dtCache.Rows.Add(drCache);
}
}
return dtCache;
}
finally
{
//Release the write lock
if (_ReadWriteLock.IsWriterLockHeld)
{
_ReadWriteLock.ReleaseWriterLock();
}
}
}
// It retrieves a object from cache for a key
public static object RetrieveFromCache(EnumeratorsConfiguration.CacheKey key)
{
try
{
_ReadWriteLock.AcquireReaderLock(60000);
return _CacheManager.Get(key.ToString());
}
finally
{
if (_ReadWriteLock.IsReaderLockHeld)
{
_ReadWriteLock.ReleaseReaderLock();
}
}
}
/// Rerurns whether the specified key Exists in cache.
public static bool ExistsInCache(EnumeratorsConfiguration.CacheKey key)
{
try
{
if (_CacheManager.Get(key.ToString()) != null)
{
return true;
}
else
{
return false;
}
}
catch (Exception ex)
{
return false;
}
}
}
}

Now let us say I want to bind a dropdownlist by the values stored in the cache.Here is way how I can do thatHere we are taking an Enum for the Cache Key Settings. If there exists various Chache Key ,we can use an Enum for that

using System;
using System.Collections.Generic;
using System.Text;
namespace AppConfigurationManagement
{
public static class EnumeratorsConfiguration
{
#region Enum
public enum CacheKey
{
Location = 1,
Region =2,
Branch = 3
}
#endregion
}
}

Now let us call the Cache Methods.If the data for the specified cache key remains in the cache then we will call it ,otherwise we will add the value to the cache.

using System;
using System.Collections.Generic;
using System.Text;
using AppConfigurationManagement;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using BusinessEntity;
namespace BusinessLogic
{
public static class AppMetadataManager
{
#region Public Methods
/// Contains the methods for Metadata Management
public static object GetMetadata(EnumeratorsConfiguration.CacheKey key)
{
object metadata = null;
try
{
if (AppCacheManager.ExistsInCache(key) && ConfigurationManager.AppSettings["EnableCache"].ToString() == "1")
{
/*if the data is in cache returns that from the cache*/
metadata = AppCacheManager.RetrieveFromCache(key);
if (metadata == null)
metadata = GetMetadataFromDB(key);
}
else
{
metadata = GetMetadataFromDB(key);
}
}
catch (Exception e)
{
throw new Exception() ;
}
return metadata;
}
/// Flushes the Metadata
public static void FlushMetadata(EnumeratorsConfiguration.CacheKey key)
{
if (AppCacheManager.ExistsInCache(key))
{
AppCacheManager.RemoveFromCache(key);
}
}
private static object GetMetadataFromDB(EnumeratorsConfiguration.CacheKey key)
{
object metadata = null;
/*data is not in cache, so get the data from the database and put that in cache*/
switch (key)
{
case EnumeratorsConfiguration.CacheKey.Location:
DataSet dsLocation = BackEndManager.GetLocationList();
AppCacheManager.AddToCache(key, dsLocation);
metadata = dsLocation;
break;
case EnumeratorsConfiguration.CacheKey.Region :
List lstRegion = BackEndManager.GetRegionList();
AppCacheManager.AddToCache(key, lstRegion);
metadata = lstRegion;
break;
}
return metadata;
}
#endregion
}
}

Now in our Page_Load Event we can do the following
protected void Page_Load(object sender, EventArgs e)
{
ddlRegion.Items.Clear();
ddlRegion.Items.Add(new ListItem("---Select---", "0"));
List lstRegion = (List)MetadataManager.GetMetadata(ConfigurationEnumerators.CacheKey.Region);
foreach (Region objRegion in lstRegion)
{
ListItem li = new ListItem();
li.Text = objRegion.Name.ToString();
li.Value = objRegion.RegionID.ToString();
ddlRegion.Items.Add(li);
}
ddlRegion.DataBind();
}
I will post Upadte and Remove Cache very soon
However, the problem with the MS Caching application block is that it carries a lot of overhead and has a lot of features that may not be useful for your application








Thursday, August 27, 2009

Bind DropdownList by an Enum

i have an enum like using System;using System.Collections.Generic;using System.Text; namespace ConfigurationManager{ public static class ConfigurationEnumerators
{
public enum EventTypeValues
{
Red= 1,
Green= 2,
Yellow= 3,
White= 4,
Blue = 5,
Violate = 0
}

}
}
This is a color type enum.Now i am going to populate a dropdown list by this Color Enumarator ddlColorType.Items.Insert(0, "------Select------");
foreach (string str in Enum.GetNames(typeof(ConfigurationEnumerators.EventTypeValues)))

{
ddlCarType.Items.Insert((int)Enum.Parse(typeof( ConfigurationEnumerators.EventTypeValues), str ),str.ToString());
}

The dropdownlist is populated by the enum with the string at its TextField and the int value at its Index fieldNow it is possible to collect the selected dropdownlist value by ddlColorType.SelectedIndex property

Monday, August 24, 2009

Commma Elemination from Comma Separatoe


string ids= string.Empty;
foreach (User objUser in dtUser)
{
ids= ids+ obiUser.UserId.ToString() + ",";
}
if (ids.Length > 0)
{
ids= ids.Substring(0, ids.Length - 1);
}

Just devide the whole string into a substring upto the leangth -1 and place it to a string

Sunday, August 23, 2009

Enumaretion with C#

Enums Defined

Enums are lists of strongly typed constants with members that has symbolic names, corresponding integral values.
The System.Enum .NET Framework Class Library type is the base class of enum types and contains methods that allow you to work with enums in different ways, such as working with a list of names or values, converting from value to name, and converting from name to value.
Enum base types can be changed and member values can be specified.
Enums make working with strongly typed constants via symbolic names easy.
Enums are value types, which mean they contain their own value, can't inherit or be inherited from, and assignment copies the value of one enum to another.

Simply if a single number needs a definition to make it easier to read then weuse a constant like

public const int myVar = 0;
if more than one related number needs a definition, then we can use an Enumeration


Difference Between ‘Enum’ and ‘enum’

The C# type, enum, inherits the Base Class Library type, Enum. Use the C# type, enum, to define new enums and use Enum, to implement static enum methods.

Creating an Enum
Declaration
[attributes] [modifiers] enum identifier [:base-type]
{
enumerator-list [,]
}

· The attributes is optional and is used to hold additional declarative information.
The modifier is optional. The allowed modifiers are new, public, protected, internal and private.
The keyword enum must be followed by an identifier that names the enum.
The base-type of an enumeration may be one of the following; byte, sbyte, short, ushort, int, uint, long or ulong. If no base-type is declared, than the default of int is used.
The enumerator-list contains the identifiers which are separated by commas
The first enumerator begins at zero by default and each enumerator following is increased by 1. This can be overridden so that each member of the enumerator-list contains its own unrelated value.
Two items in an enumeration can hold the same value, however, this will cause problems if you use an automated switch statement where all elements are added.

Example
using System;
using System.Collections.Generic;
using System.Text;

// declares the enum

public enum Universe{

Planet,

Stars,

Satellite

}

// demonstrates how to use the enum

class CreateEnum{

static void Main()

{

// create and initialize

// instance of enum type

Universe varUniverse = Universe.Planet;

// make decision based

// on enum value

switch (varUniverse)

{

case varUniverse.Planet:

Console.WriteLine("Enum Picks the planet.");

break;

case varUniverse.Stars:

Console.WriteLine("Enum pics the Stars.");

break;

case varUniverse.Satellite:

Console.WriteLine("Enum picks the Satellite.");

break;

}

Console.ReadLine();

}

}
Here I have declared an enum by using the enum keyword having a type identifier (Universe).The enum contains a comma separated list of values enclosed within curly braces.
This enum is of type Universe and we use it to declare the varUniverse variable in the Main method. Since an enum is a value type, we can assign a value (Universe.Planet) to it directly, similar to the simple types such as int or double.

Using Enums
Enum can be customized by changing its base type and its member values. By default, the list type of an enum is int.During enum declaration you can change this default by the base types include byte, sbyte, short, ushort, int, uint, long, and ulong.
Another modification you can make to an enum is to set the value of any enum member. By default, the first member of an enum takes zero.You can change it to any number you want.Two or more list member can have the same value.But it would some logical error through your programme thereafter.
using System;

// declares the enum

public enum Universe

{

Planet=1,

Stars,

Satellite

}

// demonstrates how to use the enum
class CreateEnum{
static void Main()
{
// create and initialize
// instance of enum type
Universe varUniverse = Universe.Planet;
// make decision based
// on enum value
switch (varUniverse)
{
case varUniverse.Planet:
Console.WriteLine("Enum Picks the planet.");
break;
case varUniverse.Stars:
Console.WriteLine("Enum pics the Stars.");
break;
case varUniverse.Satellite:
Console.WriteLine("Enum picks the Satellite.");
break;
}
Console.ReadLine();
}
}

The first member of the Universe enum, Planet, has its value changed to 1. You are restricted from creating forward references, circular references, and duplicate references in enum members.

As the default value of Planet is changed to 1, so the rest values are Stars=2, Satellite=3

Changing Enum Base Type

using System;
// declares the enum
public enum Universe : byte
{
Planet=1,
Stars,
Satellite
}
// demonstrates how to use the enumclass CreateEnum{ static void Main() { // create and initialize // instance of enum type Universe varUniverse = Universe.Planet; // make decision based // on enum value switch (varUniverse) { case varUniverse.Planet: Console.WriteLine("Enum Picks the planet."); break; case varUniverse.Stars: Console.WriteLine("Enum pics the Stars."); break; case varUniverse.Satellite: Console.WriteLine("Enum picks the Satellite."); break; } Console.ReadLine(); }}

Thursday, July 2, 2009

Read Child Node From a XML and Bind a DropDown List By this

My xml file is Like that

Root Node := Weather_Data
Parent Nade : = Weather

Child Node Under Parent "Weather"
ChildNode : City
ChildNode :Weather

public ArrayList ReadValue(string tag, string key)
{
string _file = "Weather.xml";
ArrayList arr = new ArrayList();
string _path = Server.MapPath("~/");
//load the document into a stream
FileStream stream = new FileStream(_path + _file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
XmlDocument doc = new XmlDocument();
//load the stream into an XML Document
doc.Load(stream);
//variable to hold the value
string returnValue = string.Empty;
//get all the elements for the specified tag
XmlNodeList nodeList = doc.GetElementsByTagName(tag);
//loop through the document
for (int i = 0; i < nodeList.Count; i++)
{
for (int j = 0; j < nodeList[i].ChildNodes.Count; j++)
{
//check to see if we have a match
if (nodeList[i].ChildNodes[j].Name == key)
{
returnValue = nodeList[i].ChildNodes[j].InnerText;
arr.Add(nodeList[i].ChildNodes[j].InnerText);
//break;
}
}
}
return arr;
}

Call the above method for bind your DropdownList Like

ArrayList arrList= ReadValue("Weather", "City");
DropDownList1.DataSource =
arrList;
DropDownList1.DataBind();



Hope This will help you

Wednesday, July 1, 2009

HTTPWeb Request and Responses With Source Code

HTTP REQUEST /RESPONSES

Basically, an HTTP client initiates a request through web browser. It establishes a Transmission Control Protocol (TCP) connection to a particular port on a host server (port 80 by default). An HTTP server that port waits for the client's request message. After receiving the request, the server sends back a status line, such as "HTTP/1.1 200 OK", and a message of its own, the body of which is may be the requested resource, an error message, or some other information.

Resource accessing by the HTTP are identified using Uniform Resource Identifier (URI)or, more specifically, Uniform Resource Locator (URL) by the http: or https URI schemas.

HTTP REQUEST STYLE

1.
Request line (such as GET)
2.Header ( such as Accept-Language: en)
3.Empty Line
4.Optional message body


HTTP REQUEST METHODS

Hyper Text Transfer Protocol (HTTP) defines eight methods for the next action for existing resource.I am giving you a short description on that eight methods.


HEAD
It is almost like a get request without the response body. This is useful for retrieving meta-information written in response headers, without sending the entire content.

GET
Get requests a representation of the specified resource.

POST
Post submits data to be processed from your form to the requesting resources. The data is included in the body of the request. It may create a new resource or update the existing resources or both.

PUT
Put uploads a representation of the specified resource.

DELETE
It deletes the specified resource.

TRACE
It returns back to the received request, so that a client can see what intermediate servers are adding or changing in existing the request.

OPTIONS
It returns the HTTP methods that the server supports for specified URL. This can be used to check the functionality of a web server by requesting '*' instead of a specific resource.

CONNECT
Converts the request connection to a transparent TCP/IP tunnel, usually to facilitate SSL-encrypted communication (HTTPS) through an unencrypted HTTP proxy.

CREATING REQUEST AND GETTING RESPONSES

// Create a request for the URL.
WebRequest request = WebRequest.Create("http://www.google.com");
// If required by the server, set the credentials.
request.Credentials = CredentialCache.DefaultCredentials;
// Get the response.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// Display the status.
if (response.StatusDescription == "OK")
{
// Get the stream containing content returned by the server.
Stream dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine(responseFromServer);
// Cleanup the streams and the response.
reader.Close();
dataStream.Close();
response.Close();
}


CREATING REQUEST AND GETTING RESPONSES WITH AUTHENTICATION
 strId = UserId_TextBox.Text;
string strName = Name_TextBox.Text;

ASCIIEncoding encoding=new ASCIIEncoding();
string postData="userid="+strId;
postData += ("&username="+strName);
byte[] data = encoding.GetBytes(postData);

// Prepare web request...
HttpWebRequest myRequest =
(HttpWebRequest)WebRequest.Create("https://www.sandbox.paypal.com/cgi-bin/webscr");
myRequest.Method = "POST";
myRequest.ContentType="application/x-www-form-urlencoded";
myRequest.ContentLength = data.Length;
Stream newStream=myRequest.GetRequestStream();
// Send the data.
newStream.Write(data,0,data.Length);
newStream.Close();
// Write the request back IPN strings
StreamWriter stOut = new StreamWriter(req.GetRequestStream(), Encoding.ASCII);
stOut.Write(strNewValue);
stOut.Close();

//send the request, read the response
HttpWebResponse strResponse = (HttpWebResponse)req.GetResponse();
Stream IPNResponseStream = strResponse.GetResponseStream();
Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
StreamReader readStream = new StreamReader(IPNResponseStream, encode);

char[] read = new char[257];
// Reads 256 characters at a time.
int count = readStream.Read(read, 0, 256);
readStream.Close();
strResponse.Close();


Check URL Exsists Or Not(HttpWebResponse Status)

Import the base class "System.Net" at the begining

string URL = TextBox1.Text;
try
{
//Create a HTTP Web Request for the URL.
WebRequest request = WebRequest.Create(URL);
request.Proxy = null;
//Get the HTTP Web Response.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
//Display the status.
Response.Write(response.StatusDescription);

if (response.StatusDescription == "OK")
{
Response.Write("\n Site Exists.");
}
else
{
Response.Write("Does Not Exists.");
}
}
catch (Exception ex)
{
throw new Exception("Request Incomplete..Please Contact with your System Administrator :" + ex);
}

Saturday, June 27, 2009

Asp.Net Authentication

Authentication is a process to check the user’s identity.The authenticated user information is stored in HttpContext.User.Identity

There are three types of authentication in Asp.Net

. Forms authentication

· Windows authentication

· Passport authentication

. Custom Authentication

Forms authentication

This authentication is based on cookies where the user name and the password are stored either in a file or in the database. After a user get authenticated, the credentials are stored in a cookie to in that session. This authentication supports both session and persistent cookies.

Windows authentication

This authentication relies upon IIS.After IIS authenticates a client, it passes a security token key to ASP.NET. ASP.NET constructs and attaches an object of the WindowsPrincipal Class to the application context based on the security token it receives from IIS

Pussport authentication

Passport authentication provider is a centralized authentication service provided by Microsoft that offers a single logon and core profile services for member sites. Passport is basically a forms-based authentication service. In this mode of authentication the Passport service grants a site-specific key. The Passport logon server uses this key to encrypt and decrypt the query strings passed between the member site and the Passport logon server.

Authentication modes can be specified in the application’s web.config file as shown below:

Example1

configuration


authentication mode="[Windows/Forms/Passport/None]">
authentication>

configuration

OR

Example2

configuration


authentication mode="Forms"
forms name="UserLogin"loginUrl="UserLogin.aspx"
authorization
deny users="?"
authorization

configuration

OR
Example3

if (Verify (txtUserName.Text, txtPassword.Text))

{
FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, False);
else
lblMessage.Text
= "Invalid UserName/Password specified...";
}

private Verify(string userName, string password)
{
//Usual Code to connect to the DB
// and verify the user's credentials
}

Friday, June 26, 2009

Get Text Box/Dropdown Value By Javascript

function GetValue()
{

// var test = document.getElementById('<%=txtMyTextBox.ClientID %>').value;
var test2 = document.getElementById('<%=DropDownList1.ClientID %>').value;
alert(test2);

}