Thursday, May 28, 2009

OracleHelper.cs

This OracleHelper class is intended to encapsulate high performance, scalable best practices for common uses of OracleClient

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.OracleClient;
using System.Data;

namespace Trans829115.DAL
{
public class OracleHelper
{
private string strConnectionString;
private OracleConnection oConnection;
private OracleCommand oCommand;
private int iTimeOut = 30;

public enum ExpectedType
{

StringType = 0,
NumberType = 1,
DateType = 2,
BooleanType = 3,
ImageType = 4
}

public OracleHelper()
{
try
{

strConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();

oConnection = new OracleConnection(strConnectionString);
oCommand = new OracleCommand();
oCommand.CommandTimeout = iTimeOut;
oCommand.Connection = oConnection;

}
catch (Exception ex)
{
throw new Exception("Error initializing OracleHelper class." + Environment.NewLine + ex.Message);
}
}


public OracleHelper(string MyConnectionString)
{
try
{

strConnectionString = MyConnectionString;

oConnection = new OracleConnection(strConnectionString);
oCommand = new OracleCommand();
oCommand.CommandTimeout = iTimeOut;
oCommand.Connection = oConnection;

}
catch (Exception ex)
{
throw new Exception("Error initializing OracleHelper class." + Environment.NewLine + ex.Message);
}
}

public void Dispose()
{
try
{
//Dispose off connection object
if (oConnection != null)
{
if (oConnection.State != ConnectionState.Closed)
{
oConnection.Close();
}
oConnection.Dispose();
}

//Clean Up Command Object
if (oCommand != null)
{
oCommand.Dispose();
}

}

catch (Exception ex)
{
throw new Exception("Error disposing OracleHelper class." + Environment.NewLine + ex.Message);
}

}

public void CloseConnection()
{
if (oConnection.State != ConnectionState.Closed) oConnection.Close();
}

public int GetExecuteScalarByCommand(string Command)
{

object identity = 0;
try
{
oCommand.CommandText = Command;
oCommand.CommandTimeout = iTimeOut;
oCommand.CommandType = CommandType.StoredProcedure;

oConnection.Open();

oCommand.Connection = oConnection;
identity = oCommand.ExecuteScalar();
CloseConnection();
}
catch (Exception ex)
{
CloseConnection();
throw ex;
}
return Convert.ToInt32(identity);
}

public void GetExecuteNonQueryByCommand(string Command)
{
try
{
oCommand.CommandText = Command;
oCommand.CommandTimeout = iTimeOut;
oCommand.CommandType = CommandType.StoredProcedure;

oConnection.Open();

oCommand.Connection = oConnection;
oCommand.ExecuteNonQuery();

CloseConnection();
}
catch (Exception ex)
{
CloseConnection();
throw ex;
}
}

public void GetExecuteNonQueryBySQL(string strSQL)
{
try
{
oCommand.CommandText = strSQL;
oCommand.CommandTimeout = iTimeOut;
oCommand.CommandType = CommandType.Text;

oConnection.Open();

oCommand.Connection = oConnection;
oCommand.ExecuteNonQuery();

CloseConnection();
}
catch (Exception ex)
{
CloseConnection();
throw ex;
}
}

public DataSet GetDatasetByCommand(string Command)
{
try
{
oCommand.CommandText = Command;
oCommand.CommandTimeout = iTimeOut;
oCommand.CommandType = CommandType.StoredProcedure;

oConnection.Open();

OracleDataAdapter adpt = new OracleDataAdapter(oCommand);
DataSet ds = new DataSet();
adpt.Fill(ds);
return ds;
}
catch (Exception ex)
{
throw ex;
}
finally
{
CloseConnection();
}
}

public DataSet GetDatasetBySQL(string strSQL)
{
try
{
oCommand.CommandText = strSQL;
oCommand.CommandTimeout = iTimeOut;
oCommand.CommandType = CommandType.Text;

oConnection.Open();

OracleDataAdapter Adapter = new OracleDataAdapter(strSQL, oConnection);
DataSet ds = new DataSet();
Adapter.Fill(ds);
return ds;
}
catch (Exception ex)
{
throw ex;
}
finally
{
CloseConnection();
}
}


public OracleDataReader GetReaderBySQL(string strSQL)
{
oConnection.Open();
try
{
OracleCommand myCommand = new OracleCommand(strSQL, oConnection);
return myCommand.ExecuteReader();
}
catch (Exception ex)
{
CloseConnection();
throw ex;
}
}

public OracleDataReader GetReaderByCmd(string Command)
{
OracleDataReader objOracleDataReader = null;
try
{
oCommand.CommandText = Command;
oCommand.CommandType = CommandType.StoredProcedure;
oCommand.CommandTimeout = iTimeOut;

oConnection.Open();
oCommand.Connection = oConnection;

objOracleDataReader = oCommand.ExecuteReader() ;
return objOracleDataReader;
}
catch (Exception ex)
{
CloseConnection();
throw ex;
}

}

public void AddParameterToSQLCommand(string ParameterName, OracleType ParameterType)
{
try
{
oCommand.Parameters.Add(new OracleParameter(ParameterName, ParameterType));
}

catch (Exception ex)
{
throw ex;
}
}
public void AddParameterToSQLCommand(string ParameterName, OracleType ParameterType,int ParameterSize)
{
try
{
oCommand.Parameters.Add(new OracleParameter(ParameterName, ParameterType, ParameterSize));
}

catch (Exception ex)
{
throw ex;
}
}
public void SetSQLCommandParameterValue(string ParameterName, object Value)
{
try
{
oCommand.Parameters[ParameterName].Value = Value;
}

catch (Exception ex)
{
throw ex;
}
}
}

}

Wednesday, May 27, 2009

Attributes in C#.Net

Attributes are a new kind of declarative information. We can use attributes to define both design-level information (such as help file, URL for documentation) and run-time information (such as associating XML field with class field). We can also create "self-describing" components using attributes.

"An attribute is a piece of additional declarative information that is specified for a declaration."
- MSDN

Attributes
C# allows you to add declarative information to a program in the form of an attribute. An attribute defines additional information (metadata) that is associated with a class, structure, method, and so on. For example, you might define an attribute that determines the type of button that a class will display. Attributes are specified between square brackets, preceding the item to which they apply. Thus, an attribute is not a member of a class. Rather, an attribute specifies supplemental information that is attached to an item.
When do we need attributes ?

The advantage of using attributes resides in the fact that the information that it contains is inserted into the assembly. This information can then be consumed at various times for all sorts of purposes:
1. An attribute can be consumed by the compiler. The System.ObsoleteAttribute attribute that we have just described is a good example of how an attribute is used by the compiler, certain standard attributes which are only destined for the compiler are not stored in the assembly. For example, the SerializationAttribute attribute does not directly mark a type but rather tells the compiler that type can be serialized. Consequently, the compiler sets certain flags on the concerned type which will be consumed by the CLR during execution such attributes are also named pseudo-attributes.
2. An attribute can be consumed by the CLR during execution. For example the .NET Framework offers the System.ThreadStaticAttribute attribute. When a static field is marked with this attribute the CLR makes sure that during the execution, there is only one version of this field per thread.
3. An attribute can be consumed by a debugger during execution. Hence, the System.Diagnostics.DebuggerDisplayAttribute attribute allows personalizing the display of an element of the code(the state of an object for example) during debugging.
4. An attribute can be consumed by a tool, for example, the .NET framework offers the System.Runtime.InteropServices.ComVisibleAttribute attribute. When a class is marked with this attribute, the tlbexp.exe tool generates a file which will allow this class to be consumed as if it was a COM object.
5. An attribute can be consumed by your own code during execution by using the reflection mechanism to access the information. For example, it can be interesting to use such attributes to validate the value of fields in your classes. Such a field must be within a certain range. Another reference field must not be null. A string field can be atmost 100 character. Because of the reflection mechanism, it is easy to write code to validate the state of any marked fields. A little later, we will show you such an example where you can consume attributes by your own code.
6. An attribute can be consumed by a user which analyses an assembly with a tool such as ildasm.exe or Reflector. Hence you could imagine an attribute which would associate a character string to an element of your code. This string being contained in the assembly, it is then possible to consult these comments without needing to access source code.
Things to know about attributes
1. An attribute must be defined by a class which derives from System.Attribute.
2. An Instance of the attribute class is only instantiated when the reflection mechanism accesses one of its representatives, Depending on its use, an attribute class in not necessarily instantiated(as with the System.ObsoleteAttribute class which does not need to be used by the reflection mechanism).
3. The .NET framework puts several attributes to your disposition. Certain attributes are destined to be used by the CLR. Other are consumed by the compiler or tools supplied by Microsoft.
4. You have the possibility of creating your own attribute classes, They will then necessarily be consumed by your program as you cannot tinker the compiler or the CLR.
5. By convention, the name of an attribute class is suffixed by Attribute. However, an attribute named XXXAttribute can be used in c# both using the XXXAttribute expression but also with the XXX expression when it marks an element of the code.
Reference:
Practical .NET2 and C#2 By Patrick Smacchia


Attribute Basics

An attribute is supported by a class that inherits System.Attribute. Thus, all attribute classes must be subclasses of Attribute. Although Attribute defines substantial functionality, this functionality is not always needed when working with attributes. By convention, attribute classes often use the suffix Attribute. For example, ErrorAttribute would be a name for an attribute class that described an error.
When an attribute class is declared, it is preceded by an attribute called AttributeUsage. This built-in attribute specifies the types of items to which the attribute can be applied. Thus, the usage of an attribute can be restricted to methods, for example.
Creating an Attribute
In an attribute class, you will define the members that support the attribute. Often attribute classes are quite simple, containing just a small number of fields or properties. For example, an attribute might define a Note that describes the item to which the attribute is being attached. Such an attribute might look like this:
[AttributeUsage(AttributeTargets.All)]
public class NoteAttribute : Attribute {
string strNote;

public NoteAttribute(string comment) {
strNote = comment;
}

public string Note {
get {
return strNote;
}
}
}
Let’s look at this class, line by line.
The name of this attribute is NoteAttribute. Its declaration is preceded by the AttributeUsage attribute, which specifies that NoteAttribute can be applied to all types of items. Using AttributeUsage, it is possible to narrow the list of items to which an attribute can be attached, and we will examine its capabilities later in this chapter.
Next, NoteAttribute is declared and it inherits Attribute. Inside NoteAttribute there is one private field, strNote, which supports one public, read-only property: Note. This property holds the description that will be associated with the attribute. There is one public constructor that takes a string argument and assigns it to Note.
At this point, no other steps are needed, and NoteAttribute is ready for use.
Attaching an Attribute
Once you have defined an attribute class, you can attach the attribute to an item. An attribute precedes the item to which it is attached and is specified by enclosing its constructor inside square brackets. For example, here is how NoteAttribute can be associated with a class:
[NoteAttribute("This class uses an attribute.")]
class UseAttrib {
// ...
}
This constructs a NoteAttribute that contains the comment “This class uses an attribute.” This attribute is then associated with UseAttrib.
When attaching an attribute, it is not actually necessary to specify the “Attribute” suffix. For example, the preceding class could be declared this way:
[Note("This class uses an attribute.")]
class UseAttrib {
// ...
}
Here, only the name Note is used. Although the short form is correct, it is usually refer to use the full name when attaching attributes, because it avoids possible confusion and ambiguity.
Obtaining an Object’s Attributes
Once an attribute has been attached to an item, other parts of the program can retrieve the attribute. To retrieve an attribute, you will usually use one of two methods. The first is GetCustomAttributes( ), which is defined by MemberInfo and inherited by Type. It retrieves a list of all attributes attached to an item. Here is one of its forms:
object[ ] GetCustomAttributes(bool searchBases)
If searchBases is true, then the attributes of all base classes through the inheritance chain will be included. Otherwise, only those classes defined by the specified type will be found.
The second method is GetCustomAttribute( ), which is defined by Attribute. One of its forms is shown here:
static Attribute GetCustomAttribute(MemberInfo mi, Type attribtype)
Here, mi is a MemberInfo object that describes the item for which the attributes are being obtained. The attribute desired is specified by attribtype. You will use this method when you know the name of the attribute you want to obtain, which is often the case. For example, assuming that the UseAttrib class has the NoteAttribute, to obtain a reference to the NoteAttribute, you can use a sequence like this:
// Get a MemberInfo instance associated with a
// class that has the NoteAttribute.
Type t = typeof(UseAttrib);

// Retrieve the NoteAttribute.
Type tRemAtt = typeof(NoteAttribute);
NoteAttribute ra = (NoteAttribute)
Attribute.GetCustomAttribute(t, tRemAtt);
This sequence works because MemberInfo is a base class of Type. Thus, t is a MemberInfo instance.
Once you have a reference to an attribute, you can access its members. Thus, information associated with an attribute is available to a program that uses an element to which an attribute is attached. For example, the following statement displays the Note field:
Console.WriteLine(ra.Note);
The following program puts together all of the pieces and demonstrates the use of NoteAttribute:
// A simple attribute example.

using System;
using System.Reflection;

[AttributeUsage(AttributeTargets.All)]
public class NoteAttribute : Attribute {
string strNote;
public NoteAttribute(string comment) {
strNote = comment;
}

public string Note {
get {
return strNote;
}
}
}

[NoteAttribute("This class uses an attribute.")]
class UseAttrib {
// ...
}

class AttribDemo {
public static void Main() {
Type t = typeof(UseAttrib);

Console.Write("Attributes in " + t.Name + ": ");

object[] attribs = t.GetCustomAttributes(false);
foreach(object o in attribs) {
Console.WriteLine(o);
}

Console.Write("Note: ");

// Retrieve the NoteAttribute.
Type tRemAtt = typeof(NoteAttribute);
NoteAttribute ra = (NoteAttribute)
Attribute.GetCustomAttribute(t, tRemAtt);

Console.WriteLine(ra.Note);
}
}
The output from the program is shown here:
Attributes in UseAttrib: NoteAttribute
Note: This class uses an attribute.

Saturday, May 23, 2009

SortedLIst in .Net

Published article on eggheadcafe.com

using System;

using System.Collections.Generic;

using System.Text;

using System.Collections;

namespace ConsoleApps

{

public class ClsSortedList

{

// create a SortedList object

SortedList mySortedList = new SortedList();

// add elements containing US state abbreviations and state

// names to mySortedList using the Add() method


public void MainFunction()

{

mySortedList.Add("NY", "New York");

mySortedList.Add("FL", "Florida");

mySortedList.Add("AL", "Alabama");

mySortedList.Add("WY", "Wyoming");

mySortedList.Add("CA", "California");

// display the keys for mySortedList using the Keys property

foreach (string myKey in mySortedList.Keys)

{

Console.WriteLine("myKey = " + myKey);

}

// display the values for mySortedList using the Values property

foreach (string myValue in mySortedList.Values)

{

Console.WriteLine("myValue = " + myValue);

}

// use the ContainsKey() method to check if mySortedList

// contains the key "FL"

if (mySortedList.ContainsKey("FL"))

{

Console.WriteLine("mySortedList contains the key FL");

}

// use the ContainsValue() method to check if mySortedList

// contains the value "Florida"

if (mySortedList.ContainsValue("Florida"))

{

Console.WriteLine("mySortedList contains the value Florida");

}

// use the Remove() method to remove FL from mySortedList

Console.WriteLine("Removing FL from mySortedList");

mySortedList.Remove("FL");

// get the key at index 3 using the GetKey() method

string keyAtIndex3 = (string)mySortedList.GetKey(3);

Console.WriteLine("The key at index 3 is " + keyAtIndex3);

// get the index of the element with the key "NY"

// using the IndexOfKey() method

int myIndex = mySortedList.IndexOfKey("NY");

Console.WriteLine("The index of NY is " + myIndex);

// get the index of the element with the value "New York"

// using the IndexOfValue() method

myIndex = mySortedList.IndexOfValue("New York");

Console.WriteLine("The index of New York is " + myIndex);

// replace the value of the element at myIndex with "New York State"

// using the SetByIndex() method

Console.WriteLine("Replacing the value New York with New York State");

mySortedList.SetByIndex(myIndex, "New York State");

// get the key list using the GetKeyList() method

Console.WriteLine("Getting the key list");

IList myKeyList = mySortedList.GetKeyList();

foreach (string myKey in myKeyList)

{

Console.WriteLine("myKey = " + myKey);

}

// get the value list using the GetValueList() method

Console.WriteLine("Getting the value list");

IList myValueList = mySortedList.GetValueList();

foreach (string myValue in myValueList)

{

Console.WriteLine("myValue = " + myValue);

}

}

}


}

Visit: http://www.eggheadcafe.com/tutorials/aspnet/c5681544-1f64-4977-8367-4803511f6c84/sortedlist-in-cnet.aspx

Friday, May 22, 2009

How to Read text file as database

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.OleDb;
using System.Data;


namespace PubishApps
{
public class ReadTextFileAsDB
{
/************************************************
* Topic : How to Read text file as database
* Use : Client code could implement DB-Query on text file.
* Author : kalit sikka
* For : http://eggheadcafe.com
* **********************************************/

OleDbConnection oConnection = new OleDbConnection();

private bool OpenConnection(string InputTextFileName)
{
if(!string.IsNullOrEmpty(InputTextFileName))
{
oConnection.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source='"+InputTextFileName+"'; Extended Properties=text;HDR=yes;FMT=Delimited";
oConnection.Open();

if(oConnection.State == System.Data.ConnectionState.Open)
return true;
else
return false;
}

return false;
}

public void BindingDataToGridView(string InputTextFileName, string Query, DataSet ds)
{
try
{
OpenConnection(InputTextFileName);

// Create the data adapter to retrieve all rows from text file.
OleDbDataAdapter da =
new OleDbDataAdapter(Query, oConnection);

// Create and fill the table.
DataSet dt = new DataSet("MyData");
da.Fill(dt);
ds = dt.Copy();

// Bind the default view of the table to the grid.
// DBview.DataSource = dt.DefaultView;


}catch(Exception ex)
{
Console.WriteLine("Error Occured: "+ ex.Message);
}
finally
{
if(oConnection.State == System.Data.ConnectionState.Open)
{
oConnection.Close();
}
}


}


}
}

Visit: http://www.eggheadcafe.com/tutorials/aspnet/8ce269f0-9654-4e61-937e-8f591434e2bd/how-to-read-text-file-as.aspx

Collection of Code Snippet: http://kalit-codesnippetsofnettechnology.blogspot.com/

To Extract Unique/All Sub-Strings from the string

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;

namespace PubishApps
{
class FindSubStringRegex
{

/************************************************
* Topic : To Extract Unique/All Sub-Strings from the string
* Reference Required: System.Text.RegularExpressions.
* Author : kalit sikka
* For : http://eggheadcafe.com
* **********************************************/


///
/// To Extract Unique/All Sub-Strings from the string
///

///
///
///
///

public Match[] FindSubstrings(string source, string matchPattern,
bool findAllUnique)
{
SortedList uniqueMatches = new SortedList( );
Match[] retArray = null;

Regex RE = new Regex(matchPattern, RegexOptions.Multiline);
MatchCollection theMatches = RE.Matches(source);

if (findAllUnique)
{
for (int counter = 0; counter < theMatches.Count; counter++)
{
if (!uniqueMatches.ContainsKey(theMatches[counter].Value))
{

uniqueMatches.Add(theMatches[counter].Value,
theMatches[counter]);
}
}
retArray = new Match[uniqueMatches.Count];
uniqueMatches.Values.CopyTo(retArray, 0);
}
else
{
retArray = new Match[theMatches.Count];
theMatches.CopyTo(retArray, 0);
}

return (retArray);

}


static void Main(string[] args)
{

// Sample Text
string Text=@"Search Tutorials & Message Boards
Silverlight WPF WCF WWF LINQ
JavaScript AJAX ASP.NET XAML
C# VB.NET VB 6.0 GDI+ IIS XML
.NET Generics Anonymous Methods Delegate
Visual Studio .NET Expression Blend Virus
Windows Vista Windows XP Windows Update
Windows 2003 Server Windows 2008 Server
SQL Server Microsoft Excel Microsoft Word
SharePoint BizTalk Virtual Earth
.NET Compact Framework Web Service

Recent Articles & Code Samples
Scheduling SSIS packages as job

Appending data to an existing file in VB.NET

Writing to a file using FileStream in VB.NET

Copy, delete and move files in VB.NET

Error handling in SSIS

Error connecting to FTP server using SSIS FTP task

Embedding an image in a mail

Sending email in SSIS using script task

ASP.NET Cache dependency example

How Export Data from DataGrid to Excel

Data Compression in SQL SERVER 2008";

string matchPattern = "ASP.NET";



FindSubStringRegex oFind = new FindSubStringRegex();
Console.WriteLine("UNIQUE MATCHES");
Match[] x1 = oFind.FindSubstrings(Text, matchPattern, true);
foreach(Match m in x1)
{
Console.WriteLine(m.Value);
}

Console.WriteLine( );
Console.WriteLine("ALL MATCHES");
Match[] x2 = oFind.FindSubstrings(Text, matchPattern, false);
foreach(Match m in x2)
{
Console.WriteLine(m.Value);
}



}


}
}


Visit: http://www.eggheadcafe.com/tutorials/aspnet/b6277277-89d0-4b4d-9bac-2cd77e929f19/to-extract-uniqueall-sub.aspx

How to get all URLs of the page

Topic : How to get all URLs of the page
namespace PubishApps
{
class FetchURLsFromSite
{

/************************************************
* Topic : How to fetch all URLs of the site.
* Author : kalit sikka
* For : http://eggheadcafe.com
* **********************************************/

///
/// To fetch all URLs name from the site
///

///
public void FetchUrls( string webPage )
{
GetAllUrls(GetContent(webPage));
}


///
/// Get the content of the web page
///

///
///
private string GetContent(string webPage)
{
HttpWebResponse response = null;//used to get response
StreamReader respStream = null;//used to read response into string
try
{
//create a request object using the url passed in
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(webPage);
request.Timeout = 10000;

//go get a response from the page
response = (HttpWebResponse)request.GetResponse();

//create a streamreader object from the response
respStream = new StreamReader(response.GetResponseStream());

//get the contents of the page as a string and return it
return respStream.ReadToEnd();
}
catch (Exception ex)
{
throw ex;
}
finally
{
//close it down, we're going home!
response.Close();
respStream.Close();
}
}

///
/// Use regular expression to filter required URLs
///

///

private void GetAllUrls(string content)
{

// Address of local LogFile
string LocalFile = @"C:\Documents and Settings\kalit.20413\My Documents\LogFile.txt";

//regular expression
string pattern = @"(?:href\s*=)(?:[\s""']*)(?!#|mailto|location.|javascript|.*css|.*this\.)(?
.*?)(?:[\s>""'])";

//Set up regex object
Regex RegExpr = new Regex(pattern, RegexOptions.IgnoreCase);

//get the first match
Match match = RegExpr.Match(content);

//loop through matches
while (match.Success)
{

//output the match info
Console.WriteLine("href match: " + match.Groups[0].Value);
WriteToLog(LocalFile, "href match: " + match.Groups[0].Value + "\r\n");

Console.WriteLine("Url match: " + match.Groups[1].Value);

//get next match
match = match.NextMatch();
}
}

///
/// Write log at local machine
///

///
///
private void WriteToLog(string file, string message)
{
using (StreamWriter w = File.AppendText(file))
{
w.WriteLine(DateTime.Now.ToString() + ": " + message);
w.Close();
}
}
}

}


Visit: http://www.eggheadcafe.com/tutorials/aspnet/23ce657b-87a9-45b3-856d-1c891803fcbd/how-to-get-all-urls-of-th.aspx

Message Queuing in .Net

Message Queuing in C#.net
Creating a Message Queue
Message queues can be created programmatically with the Create() method of the MessageQueue class.
With the Create() method, the path of the new queue must be passed. The path consists of the host name where the queue is located and the name of the queue. In the example, the queue MyNewPublicQueue is created on the local host. To create a private queue the path name must include Private$; for example, c:\kalit\Private$\MyNewPrivateQueue.
After the Create() method is invoked, properties of queue can be changed. For example, using the Label property, the label of the queue is set to Demo Queue. The sample program writes the path of the queue and the format name to the console. The format name is automatically created with a UUID that can be used to access the queue without the name of the server:

using System;
using System.Messaging;

namespace MessageQueuingInDot
{
class Program
{
static void Main()
{
using (MessageQueue queue = MessageQueue.Create(@".\MyNewPublicQueue"))
{
queue.Label = "Demo Queue";
Console.WriteLine("Queue created:");
Console.WriteLine("Path: {0}", queue.Path);
Console.WriteLine("FormatName: {0}", queue.FormatName);
}
}
}
}
Finding a Queue
The path name and the format name can be used to identify queues. To find queues, you must differentiate between public and private queues. Public queues are published in the Active Directory. For these queues, it is not necessary to know the system where they are located. Private queues can be found only if the name of the system where the queue is located is known.
You can find public queues in the Active Directory domain by searching for the queue’s label, category, or format name. You can also get all queues on a machine. The class MessageQueue has static methods to search for queues: GetPublicQueuesByLabel(), GetPublicQueuesByCategory(), and GetPublicQueuesByMachine(). The method GetPublicQueues() returns an array of all public queues in the domain:
using System;
using System.Messaging;

namespace MessageQueuingInDot
{
class Program
{
static void Main()
{
foreach (MessageQueue queue in MessageQueue.GetPublicQueues())
{
Console.WriteLine(queue.Path);
}
}
}
}
The method GetPublicQueues() is overloaded. One version allows passing an instance of the MessageQueueCriteria class. With this class, you can search for queues created or modified before or after a certain time, and you can also look for a category, label, or machine name.
Private queues can be searched with the static method GetPrivateQueuesByMachine(). This method returns all private queues from a specific system.
Opening Known Queues
If the name of the queue is known, it is not necessary to search for it. Queues can be opened by using the path or format name. They both can be set in the constructor of the MessageQueue class.
Path Name
The path specifies the machine name and the queue name to open the queue. This code example opens the queue MyPublicQueue on the local host. To be sure that the queue exists, you use the static method MessageQueue.Exists():
using System;
using System.Messaging;

namespace MessageQueuingInDot
{
class Program
{
static void Main()
{
if (MessageQueue.Exists(@".\MyPublicQueue"))
{
MessageQueue queue = new MessageQueue(@".\MyPublicQueue");
//...
}
else
{
Console.WriteLine("Queue .\MyPublicQueue not existing");
}
}
}
}
Depending on the queue type, different identifiers are required when queues are opened. The following table shows the syntax of the queue name for specific types.
Open table as spreadsheet Queue Type Syntax
Public queue MachineName\QueueName
Private queue MachineName\Private$\QueueName
Journal queue MachineName\QueueName\Journal$
Machine journal queue MachineName\Journal$
Machine dead-letter queue MachineName\DeadLetter$
Machine transactional dead-letter queue MachineName\XactDeadLetter$
When you use the path name to open public queues, it is necessary to pass the machine name. If the machine name is not known, the format name can be used instead. The path name for private queues can only be used on the local system. The format name must be used to access private queues remotely.
Format Name
Instead of the path name, you can use the format name to open a queue. The format name is used for searching the queue in the Active Directory to get the host where the queue is located. In a disconnected environment where the queue cannot be reached at the time the message is sent, it is necessary to use the format name:

MessageQueue queue = new MessageQueue(
@"FormatName:PUBLIC=");
The format name has some different uses. It can be used to open private queues and to specify a protocol that should be used:
• To access a private queue, the string that has to be passed to the constructor is FormatName:PRIVATE=MachineGUID\QueueNumber. The queue number for private queues is generated when the queue is created. You can see the queue numbers in the \System32\msmq\storage\lqs directory.
• With FormatName:DIRECT=Protocol:MachineAddress\QueueName you can specify the protocol that should be used to send the message. The HTTP protocol is supported with Message Queuing 3.0.
• FormatName:DIRECT=OS:MachineName\QueueName is another way to specify a queue using the format name. This way you don’t have to specify the protocol but still can use the machine name with the format name.
Sending a Message
You can use the Send method of the MessageQueue class to send a message to the queue. The object passed as an argument of the Send() method is serialized to the associated queue. The Send() method is overloaded so that a label and a MessageQueueTransaction object can be passed. Transactional behavior of Message Queuing is discussed later.
The code example first checks if the queue exists. If it doesn’t exist, a queue is created. Then the queue is opened and the message Sample Message is sent to the queue using the Send() method.
The path name specifies “.” for the server name, which is the local system. Path names to private queues only work locally.
using System;
using System.Messaging;

namespace MessageQueuingInDot
{
class Program
{
static void Main()
{
try
{
if (!MessageQueue.Exists(@".\Private$\MyPrivateQueue"))
{
MessageQueue.Create(@".\Private$\MyPrivateQueue");
}
MessageQueue queue = new MessageQueue(@".\Private$\MyPrivateQueue");
queue.Send("Sample Message", "Label");
}
catch (MessageQueueException ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
Following shows the Computer Management admin tool where you can see the message that arrived in the queue.



By opening the message and selecting the Body tab (see below) of the dialog, you can see that the message was formatted using XML. How the message is formatted is the function of the formatter that’s associated with the message queue.



Message Formatter
The format in which messages are transferred to the queue depends on the formatter. The MessageQueue class has a Formatter property through which a formatter can be assigned. The default formatter, XmlMessageFormatter, will format the message in XML syntax as shown in the previous example.
A message formatter implements the interface IMessageFormatter. Three message formatters are available with the namespace System.Messaging:
• The XmlMessageFormatter is the default formatter. It serializes objects using XML.
• With the BinaryMessageFormatter, messages are serialized in a binary format. These messages are shorter than the messages formatted using XML.
• The ActiveXMessageFormatter is a binary formatter, so that messages can be read or written with COM Objects. Using this formatter, it is possible to write a message to the queue with a .NET class and to read the message from the queue with a COM object or vice versa.



Sending Complex Messages
Instead of passing strings, it is possible to pass objects to the Send() method of the MessageQueue class. The type of the class must fulfill some specific requirements, but they depend on the formatter.
For the binary formatter the class must be serializable with the [Serializable] attribute. With the .NET runtime serialization all fields are serialized (this includes private fields). Custom serialization can be defined by implementing the interface ISerializable.
XML serialization takes place with the XML formatter. With XML serialization all public fields and properties are serialized. The XML serialization can be influenced by using attributes from the System.Xml.Serialization namespace.
Receiving Messages
To read messages, again the MessageQueue class can be used. With the Receive() method a single message is read and removed from the queue. If messages are sent with different priorities, the message with the highest priority is read. Reading messages with the same priority may mean that the first message sent is not the first message read because the order of messages across the network is not guaranteed. For a guaranteed order, transactional message queues can be used.
In the following example, a message is read from the private queue MyPrivateQueue. Previously a simple string was passed to the message. When you read a message using the XmlMessageFormatter, you have to pass the types of the objects that are read to the constructor of the formatter. In the example, the type System.String is passed to the argument array of the XmlMessageFormatter constructor. This constructor allows either a String array that contains the types as strings to be passed or a Type array.
The message is read with the Receive() method and then the message body is written to the console:
using System;
using System.Messaging;

namespace MessageQueuingInDot
{
class Program
{
static void Main(string[] args)
{
MessageQueue queue = new MessageQueue(@".\Private$\MyPrivateQueue");
queue.Formatter = new XmlMessageFormatter(
new string[] {"System.String"});

Message message = queue.Receive();
Console.WriteLine(message.Body);
}
}
}
The Receive() message behaves synchronously and waits until a message is in the queue if there is none.
Enumerating Messages
Instead of reading message by message with the Receive() method, an enumerator can be used to walk through all messages. The MessageQueue class implements the interface IEnumerable and thus can be used with a foreach statement. Here, the messages are not removed from the queue, but you get just a peek at the messages to get their content:

MessageQueue queue = new MessageQueue(@".\Private$\MyPrivateQueue");
queue.Formatter = new XmlMessageFormatter(
new string[] {"System.String"});
foreach (Message message in queue)
{
Console.WriteLine(message.Body);
}
Instead of using the IEnumerable interface, the class MessageEnumerator can be used. MessageEnumerator implements the interface IEnumerator, but has some more features. With the IEnumerable interface, the messages are not removed from the queue. The method RemoveCurrent() of the MessageEnumerator removes the message from the current cursor position of the enumerator.
In the example, the MessageQueue method GetMessageEnumerator() is used to access the MessageEnumerator. With the MessageEnumerator the method MoveNext() takes a peek message by message. The MoveNext() method is overloaded to allow a timespan as an argument. This is one of the big advantages when using this enumerator. Here, the thread can wait until a message arrives in the queue, but only for the specified timespan. The Current property, which is defined by the IEnumerator interface, returns a reference to a message:
MessageQueue queue = new MessageQueue(@".\Private$\MyPrivateQueue");
queue.Formatter = new XmlMessageFormatter(
new string[] {"System.String"});

using (MessageEnumerator messages = queue.GetMessageEnumerator())
{
while (messages.MoveNext(TimeSpan.FromMinutes(30)))
{
Message message = messages.Current;
Console.WriteLine(message.Body);
}
}
Asynchronous Read
The Receive method of the MessageQueue class waits until a message from the queue can be read. To avoid blocking the thread, a timeout can be specified in an overloaded version of the Receive method. To read the message from the queue after the timeout, Receive() must be invoked again. Instead of polling for messages, the asynchronous method BeginReceive() can be called. Before starting the asynchronous read with BeginReceive(), the event ReceiveCompleted should be set. The ReceiveCompleted event requires a ReceiveCompletedEventHandler delegate that references the method that is invoked when a message arrives with the queue and can be read. In the example the method MessageArrived is passed to the ReceivedCompletedEventHandler delegate:
MessageQueue queue = new MessageQueue(@".\Private$\MyPrivateQueue");
queue.Formatter = new XmlMessageFormatter(
new string[] {"System.String"});

queue.ReceiveCompleted +=
new ReceiveComletedEventHandler(MessageArrived);
queue.BeginReceive();
// thread does not wait
The handler method MessageArrived requires two parameters. The first parameter is the origin of the event, the MessageQueue. The second parameter is of type ReceiveCompletedEventArgs that contains the message and the async result. In the example, the method EndReceive() from the queue is invoked to get the result of the asynchronous method, the message:

public static void MessageArrived(object source,
ReceiveCompletedEventArgs e)
{
MessageQueue queue = (MessageQueue)source;
Message message = queue.EndReceive(e.AsyncResult);
Console.WriteLine(message.Body);
}


Visit: http://www.eggheadcafe.com/tutorials/aspnet/923491b3-00ae-4a51-926c-14039007684d/message-queuing-in-cnet.aspx

Tuesday, May 19, 2009

What is Searialization in .Net

Serialization (known as pickling in python) is an easy way to convert an object to a binary representation that can then be e.g. written to disk or sent over a wire.
It's useful e.g. for easy saving of settings to a file.
You can serialize your own classes if you mark them with [Serializable] attribute. This serializes all members of a class, except those marked as [NonSerialized].
.NET offers 2 serializers: binary, SOAP, XML. The difference between binary and SOAP is:
• binary is more efficient (time and memory used)
• binary is completely human-unreadable. SOAP isn't much better.
XML is slightly different:
• it lives in System.Xml.Serialization
• it uses [XmlIgnore] instead of [NonSerialized] and ignores [Serializable]
• it doesn't serialize private class members
An example of serialization/deserialization to a file:
using System.IO;
using System.Diagnostics;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters;
using System.Runtime.Serialization.Formatters.Binary;

[Serializable]
public class MySettings {
public int screenDx;
public ArrayList recentlyOpenedFiles;
[NonSerialized]public string dummy;
}

public class Settings {
const int VERSION = 1;
static void Save(MySettings settings, string fileName) {
Stream stream = null;
try {
IFormatter formatter = new BinaryFormatter();
stream = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None);
formatter.Serialize(stream, VERSION);
formatter.Serialize(stream, settings);
} catch {
// do nothing, just ignore any possible errors
} finally {
if (null != stream)
stream.Close();
}
}

static MySettings Load(string fileName) {
Stream stream = null;
MySettings settings = null;
try {
IFormatter formatter = new BinaryFormatter();
stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.None);
int version = (int)formatter.Deserialize(stream);
Debug.Assert(version == VERSION);
settings = (MySettings)formatter.Deserialize(stream);
} catch {
// do nothing, just ignore any possible errors
} finally {
if (null != stream)
stream.Close();
}
return settings;
}
}

Friday, May 15, 2009

How to use FileSystemWatcher in .Net

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading;

namespace PubishApps
{
public class ClsFileSystemWatcher
{

/************************************************
* Topic : How to use FileSystemWatcher in .Net
* Reference Required: System.IO, System.Threading.
* Author : kalit sikka
* Usage: This class can use to track for filesystem changes on the local machine, a networked drive, and even a remote machine.
* Generally use in window services to track changes in background.
* **********************************************/

public void FileWatcher(string InputDir)
{
using (FileSystemWatcher fsw = new FileSystemWatcher( ))
{
fsw.Path = InputDir; // Input Path
fsw.Filter = @"*.txt"; // Filter for files
fsw.IncludeSubdirectories = true;

fsw.NotifyFilter = NotifyFilters.FileName |
NotifyFilters.Attributes |
NotifyFilters.LastAccess |
NotifyFilters.LastWrite |
NotifyFilters.Security |
NotifyFilters.Size |
NotifyFilters.CreationTime|
NotifyFilters.DirectoryName;

fsw.Changed += new FileSystemEventHandler(OnChanged);
fsw.Created += new FileSystemEventHandler(OnCreated);
fsw.Deleted += new FileSystemEventHandler(OnDeleted);
fsw.Renamed += new RenamedEventHandler(OnRenamed);
fsw.Error += new ErrorEventHandler(OnError);

fsw.EnableRaisingEvents = true;

string strOldFile = InputDir + "OldFile.txt";
string strNewFile = InputDir + "CreatedFile.txt";

// Making changes in existing file

using (FileStream stream = File.Open(strOldFile, FileMode.Append))
{
StreamWriter sw = new StreamWriter(stream);
sw.Write("Appending new line in Old File");
sw.Flush();
sw.Close();

}

// Writing new file on FileSystem

using (FileStream stream = File.Create(strNewFile))
{
StreamWriter sw = new StreamWriter(stream);
sw.Write("Writing First line into the File");
sw.Flush();
sw.Close();
}

File.Delete(strOldFile);
File.Delete(strNewFile);


// Minimum time given to event handler to track new events raised by the filesystem.

Thread.Sleep(1000);
}
}

public static void OnChanged(object source, FileSystemEventArgs e)
{
Console.WriteLine("File " + e.FullPath + " :" + e.ChangeType);
}

public static void OnDeleted(object source, FileSystemEventArgs e)
{
Console.WriteLine("File " + e.FullPath + " :" + e.ChangeType);
}

public static void OnCreated(object source, FileSystemEventArgs e)
{
Console.WriteLine("File " + e.FullPath + " :" + e.ChangeType);
}

public static void OnRenamed(object source, RenamedEventArgs e)
{
Console.WriteLine("File " + e.OldFullPath + " [Changed to] " + e.FullPath);
}

public static void OnError(object source, ErrorEventArgs e)
{
Console.WriteLine("Error " + e.ToString( ));
}



static void Main(string[] args)
{
ClsFileSystemWatcher FSysWatcher = new ClsFileSystemWatcher();
FSysWatcher.FileWatcher(@"D:\kalit\");
}


}




}

Wednesday, May 6, 2009

Attributes of OOPS in .Net

User-Defined Value Types (Structures)
Applications often require types to encapsulate essentially numeric quantities such as currencies, screen coordinates, and temperatures,
which are not represented by the available primitive types.
Using classes in these scenarios would be like using a hammer to crack a nut; the run-time overhead for garbage-collecting these simple objects would be unnecessarily high.

The .NET Framework provides user-definable value types as a solution to this problem.
In C#, a value type is written as a struct. Remember that like value types, instances of structs are stored wherever they are used.
using System;

struct Money
{
// private instance field
private int centsAmount;

// private class field
private const string currencySymbol = "$";

// public constructor
public Money(int dollars, int cents)
{
centsAmount = (dollars * 100) + cents;
}
// another public constructor
public Money(double amount)
{
centsAmount = (int)((amount * 100.0) + 0.5);
}
}

class MyClass
{
static void Main()
{
Money freebie;
Money salary = new Money(20000, 0);
Money carPrice = new Money(34999.95);
}
}




Although structures cannot explicitly inherit from an arbitrary class, they can implement interfaces. For example, it is quite common to implement standard .NET Framework interfaces such as IComparable, which allows us to specify how objects should be compared, and so enables sorting. Value types will often implement this to interoperate well with other classes in the .NET Framework.

We'll be covering interfaces in more detail later in this chapter, but the following preview demonstrates how easily we can change our Money value type to implement an interface, and override the ToString() method inherited from System.Object:

// value_type_inheritance.cs
using System;

struct Money : IComparable
{
// private fields
private int centsAmount;
private const string currencySymbol = "$";

// public constructors
public Money(int dollars, int cents)
{
centsAmount = (dollars * 100) + cents;
}

public Money(double amount)
{
centsAmount = (int)((amount * 100.0) + 0.5);
}

// compare with another Money
public int CompareTo(object other)
{
Money m2 = (Money)other;
if (centsAmount < m2.centsAmount)
return -1;
else if (centsAmount == m2.centsAmount)
return 0;
else
return 1;
}

// return value as a string
public override string ToString()
{
return currencySymbol + (centsAmount / 100.0).ToString();
}
}


Enumerations
Enumerations are .NET value types that represent integral types with a limited set of permitted values. They may also be used to map bit flags onto an integer type to allow a convenient way to represent a combination of options using a single variable. Enumerations are present in many programming languages, but in .NET they are also object-oriented. This means that developers now have access to additional features, which are not present in other languages.

Enumerated Types
To declare an enumerated type, we use the enum keyword and specify symbolic names to represent the allowable values. We can also specify an underlying integral data type to be used for the enumeration (byte, short, int, or long), and optionally assign a specific number to each of the names.

The following example, enumerations.cs, declares a simple enumeration to represent medals in a competition:

// enumerations.cs
using System;

enum Medal : short
{
Gold,
Silver,
Bronze
}

Enumerations inherit implicitly from System.Enum, and so inherit all of its members. Having defined an enumerated type, we can use it in our code as follows:


class MyClass
{
static void Main()
{
Medal myMedal = Medal.Bronze;
Console.WriteLine("My medal: " + myMedal.ToString());
}
}

Medal[] medals = (Medal[])Enum.GetValues(typeof(Medal));
foreach (Medal m in medals)
{
Console.WriteLine("{0:D}\t{1:G}", m, m);
}

class MyClass
{
// Field (usually private, for encapsulation)
private int aField;

// Property (usually public, for ease of use)
public int AProperty
{
get { return aField; }
set { aField = value; }
}

// Constant (class-wide, read-only field)
private const int aConstant = 43;

// Delegate (defines a method signature)
public delegate void ADelegate(int aParameter);

// Event (to alert event receiver objects)
public event ADelegate AnEvent;

// Method
public void AMethod()
{
// Method implementation code
}

// Instance constructor (to initialize new objects)
public MyClass(int aValue)
{
aField = aValue;
}

// Destructor method (to tidy up unmanaged resources)
~MyClass()
{
// Finalization code
}

// Nested class definition
private class aNestedClass
{
// class definition
}
}

Properties
Properties represent state in a class. However, properties are quite different from fields. Whereas a field stores data, a property provides a specific access point to that data. Properties extend the concept of the field by being able to restrict the incoming values and provide read-only and write-only data members.

using System;

public class Account
{
private double balance;
public double Balance
{
get
{
return balance;
}
set
{
if (value < 0)
throw
new ArgumentOutOfRangeException("value","Balance must
be greater than 0");
balance=value;
}
}
}

Static Type Members
The fields, properties, and methods we have seen so far in this chapter are accessible only with a reference to an instance of a class. However, not all functionality is best implemented tied to an instance of a class. .NET allows us to define type members that are callable directly from the class without requiring an instance of the class to be created. Fields, methods, and properties can all be declared in this fashion.

Static type members are useful if a particular action is not tied to an instance of the class, but is functionality that can be used as a standalone. For example, a Time class may define a GetCurrentTime() method that returns the current system clock time. Creating an instance of Time just to call GetCurrentTime() is not ideal since all classes would return the same value. Since this method is general to the Time class and is not specific to each instance, it is best implemented as a static member.

Static type members are commonplace with the .NET base class library. A trivial example of a static type member can be found with the System.DateTime class. System.DateTime.Now is a static function returning the system date, as seen in static_time_example.cs. Note that the DateTime class is used directly; we do not need to create an instance of DateTime to call the Now type member. The Now property within the DateTime class is declared as static:

using System;

public class static_time_example
{
[STAThread]
static void Main(string[] args)
{
Console.WriteLine(DateTime.Now);
}
}

Generally speaking, it is useful to think of static members as belonging to classes. Non-static, or instance members belong to objects, or instances of classes. If you'll recall, this is exactly how constants and static read-only fields perform. In fact, a constant is a special type of static field.

Remember, a field is a storage location for an object's data. A new storage location is created for each instance of an object. It is slightly different if a field is static. A static field denotes exactly one storage location. No matter how many instances of a class are created, there is only ever one copy of a static field.

Let's make one small change to our Account class to further explore how static fields affect our program. The following code is located in static_bankaccount.cs:


using System;

public class Account
{
private static double balance;

public double Balance
{
get
{
return balance;
}
set
{
balance=value;
}
}
}

class AtTheBank
{
[STAThread]
static void Main(string[] args)
{
Account mySavings= new Account();
Account myChecking=new Account();

mySavings.Balance=500;

Console.WriteLine("Savings balance: " + mySavings.Balance);
Console.WriteLine("Checking balance: " + myChecking.Balance);
}
}

The only change we've made to the Account class is in how we define the balance field:

private static double balance;

However, while this change is small, the corresponding effect on the program is quite noticeable. Look again at the two instances of Account, mySavings and myChecking:

Account mySavings= new Account();
Account myChecking=new Account();

mySavings.Balance=500;

Console.WriteLine("Savings balance: " + mySavings.Balance);
Console.WriteLine("Checking balance: " + myChecking.Balance);

If balance were an instance variable, then mySavings and myChecking would each have their own balance field. We would expect that the output of the above program would show that the mySavings instance had a balance of 500 while myChecking only had the default value of 0. However, balance is not an instance field. Rather, it is a static field. Because of this, the value of balance is shared across all instances of Account.

If a method is declared as static, then that method will perform an action on the class, not an instance of the class. A static member can only access and modify static fields. Let's modify the account one more time to show off the use of a static method. The following code is in static_bankaccount2.cs:

using System;

public class Account
{
private static double balance;

public double Balance
{
//...omitted for brevity
}

public static void addTen()
{
balance=balance+10;
}
}

class AtTheBank
{
[STAThread]
static void Main(string[] args)
{
Account mySavings= new Account();
Account myChecking=new Account();

mySavings.Balance=500;
Account.addTen();

Console.WriteLine("Savings balance: " + mySavings.Balance);
Console.WriteLine("Checking balance: " + myChecking.Balance);
}
}

Static methods act on the class, not the instances of the class. Static methods can access static fields, static properties, and other static methods. As such, you cannot call AddTen() through the mySavings or myChecking instances of the Account class. Rather, you must make the call directly against the Account class. However, as you can see from the output, the call does still affect the balance of every instance. This is because AddTen() adds to the static balance field. Here is the output of the above program:


C:\Class Design\Ch 02>static_bankaccount2.exe
Savings balance: 500
Checking balance: 500
Savings balance: 510
Checking balance: 510

Care must be taken when using static methods and fields. Only fields that truly must be shared across all instances should be marked as static. Similarly, only methods and properties that must act on static fields should be marked as static. An ideal situation to use static methods and fields is in conjunction with the read-only attribute.

Passing by Reference
Passing arguments by reference involves copying a reference to the data instead of the data itself. We think of this as if we are passing a pointer to the location in memory where the data is to the method. Both the client code and the method hold separate references to the same data. Because of this, changes made to the parameter by the method are visible to the client code. The changes a method makes to a parameter that can affect the client code are called side effects. When an argument is passed by reference, think of the parameter as an alias to the argument.

What actually happens is that the value is copied in to the method, just as it is when passed by value; when the method terminates, the value is copied back out again into the location from which it came, along with any changes that have been made to the value in the course of the method executing.

Passing an argument by reference requires the use of the additional ref keyword in both the method declaration, and the calling client code. Failure to use the ref keyword in the calling program results in a compile-time error:

Argument 'n': cannot convert from '' to 'ref '.

The ref keyword overrides the default pass by value behavior. The following example demonstrates passing data by reference:

using System;

namespace parameter_types
{
public class Calculator
{
public static decimal CalculateInterest(ref decimal balance)
{
decimal interest = (decimal)45.11;
balance = balance + interest;
return (balance);
}
}

class BatchRun
{
static void Main()
{
decimal balance = (decimal)4566.54;

Console.WriteLine("Balance = " + balance);
Console.WriteLine("Balance + Interest = " +
Calculator.CalculateInterest(ref balance));
Console.WriteLine("Balance = " + balance);
}
}
}

Output Parameters
Output parameters solve the problem of getting a method to simulate the manipulation and passing back of more than one value. Similar to ref parameters, output parameters are also passed by reference and the out parameter also behaves like an alias to the argument, but there is one subtle and important difference to ref arguments, and that is that:

Important Arguments passed by reference using the out keyword do not have to be initialized before being passed to the method.


By implication, if an argument has no value (or if it is a null reference), then the method cannot inadvertently do any harm to the argument. Output parameters are also considered unassigned within a method; methods with out parameters must therefore initialize all out parameters before the method returns.

The following example parameter_types.cs demonstrates passing data by reference using out parameters:


using System;

public class Calculator
{
public static decimal CalculateInterest(out decimal balance)
{
decimal interest = (decimal)45.11;
balance = (decimal)4566.54;
balance += interest;
return (balance);
}
}

class BatchRun
{
static void Main()
{
decimal balance;

Console.WriteLine("Balance + Interest = " +
Calculator.CalculateInterest(out balance));
}
}

using System;

class MSILMethods
{
static void Main()
{
int result = 0;
int total;
int net = 0;

MethodExamples examples = new MethodExamples();

result = examples.ByValueMethod(7);
examples.ByRefMethod(ref result);
examples.OutputMethod(out total, result);
result = result + examples.OverloadMethod(total);
total = examples.OverloadMethod(result, total);
net = examples.ParamsMethod(result, total);

Console.WriteLine(net);
}
}

class MethodExamples
{
public int ByValueMethod(int a)
{
return a++;
}

public void ByRefMethod(ref int b)
{
b = b * 2;
}

public void OutputMethod(out int c, int d)
{
c = d / 4;
}

public int OverloadMethod(int e)
{
return e + 2;
}

public int OverloadMethod(int e, int f)
{
return e + f;
}

public int ParamsMethod(params int[] g)
{
int total = 0;

foreach(int num in g)
{
total = total + num;
}

return total + 1;
}
}

Tuesday, May 5, 2009

How to Read text file as database

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.OleDb;
using System.Data;


namespace PubishApps
{
public class ReadTextFileAsDB
{
/************************************************
* Topic : How to Read text file as database
* Use : Client code could implement DB-Query on text file.
* Author : kalit sikka
* **********************************************/

OleDbConnection oConnection = new OleDbConnection();

private bool OpenConnection(string InputTextFileName)
{
if(!string.IsNullOrEmpty(InputTextFileName))
{
oConnection.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source='"+InputTextFileName+"'; Extended Properties=text;HDR=yes;FMT=Delimited";
oConnection.Open();

if(oConnection.State == System.Data.ConnectionState.Open)
return true;
else
return false;
}

return false;
}

public void BindingDataToGridView(string InputTextFileName, string Query, DataSet ds)
{
try
{
OpenConnection(InputTextFileName);

// Create the data adapter to retrieve all rows from text file.
OleDbDataAdapter da =
new OleDbDataAdapter(Query, oConnection);

// Create and fill the table.
DataSet dt = new DataSet("MyData");
da.Fill(dt);
ds = dt.Copy();

// Bind the default view of the table to the grid.
// DBview.DataSource = dt.DefaultView;


}catch(Exception ex)
{
Console.WriteLine("Error Occured: "+ ex.Message);
}
finally
{
if(oConnection.State == System.Data.ConnectionState.Open)
{
oConnection.Close();
}
}


}


}
}

How Export Data from DataGrid to Excel

In-line Code:

"http://www.w3.org/1999/xhtml" >
"server">




Top of Form
"form1" runat="server">


"Table" AlternatingRowStyle-BackColor="Lavender" PageSize="10" CellPadding="4" runat="server" AllowPaging="True" BackColor="#CCCCCC" BorderColor="#999999" BorderStyle="Solid" BorderWidth="3px" ForeColor="Black">
"TopAndBottom" />
"#CCCCCC" />
"White" />
"#000099" Font-Bold="True" ForeColor="White" />
"Left" BackColor="#CCCCCC" ForeColor="Black" />
"Black" Font-Bold="True" ForeColor="White" />





"BtnExport" runat="server" OnClick="BtnExport_Click"
Text="Export_Data_To_Excel" />


Bottom of Form




Code-Behind:


using System;
using System.Data;
using System.Configuration;
using System.Collections;
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;
using System.Data.OracleClient;

public partial class ExportGridViewDataIntoExcel : System.Web.UI.Page
{

OracleConnection oOrcCon = new OracleConnection();

protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
BindDataToGrid(GetDataSetFromSource()); // Binding Data to the Table
}
protected void BtnExport_Click(object sender, EventArgs e)
{
string FileName = "ExportedExcel.xls";
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename="+FileName+"");
Response.Charset = "";

Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter oWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(oWriter);
Table.RenderControl(htmlWrite);
Response.Write(oWriter.ToString());
Response.End();
}

///
/// Property for setting ConnectionString
///
private string LocalString
{
get { return @"Password=XXXX;User ID=Intranet;Data Source=XXXX;Persist Security Info=True"; }
}

///
/// Open the connection
///
private void OpenConnection()
{
if (oOrcCon.State != ConnectionState.Open && !string.IsNullOrEmpty(LocalString))
oOrcCon.ConnectionString = LocalString;
oOrcCon.Open();
}
///
/// Close Connection
///
private void CloseConnection()
{
if (oOrcCon.State == ConnectionState.Open)
oOrcCon.Close();
}

///
/// Extacting DataSet from resultant of Query
///
///
public System.Data.DataSet GetDataSetFromSource()
{
DataSet ds = new DataSet();
try
{
OpenConnection();
string str = @"select * from Project order by Project_Name";
OracleCommand Cmd = new OracleCommand(str, oOrcCon);
OracleDataAdapter apter = new OracleDataAdapter(Cmd);
apter.Fill(ds);
return ds;
}
catch (Exception ex)
{
Response.Write("Error in extracting Dataset: " + ex.ToString());
return null;
}
finally
{
CloseConnection();
}
}

///
/// Bind to the DataGrid
///
///
private void BindDataToGrid(DataSet ds)
{
if (ds != null)
{
Table.DataSource = ds;
Table.DataBind();

}

}

public override void VerifyRenderingInServerForm(Control Table)
{

}

}

Friday, May 1, 2009

Introduction to LINQ in .Net

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace PubishApps
{
public class IntroWithLINQ
{
/************************************************
* Topic : Introduction to LINQ in .Net
* Reference Required: System.Linq.
* Author : kalit sikka
* Summary: This article include different methods to show some simple features of LINQ that could make a life of a developer quit easlier in his day-to-day work.
* **********************************************/
public List GetDeveloperList()
{
List oList = new List();
oList.Add(new Developer(1001, "Sri Ram", Designation.Project_Lead, 10));
oList.Add(new Developer(1020, "Amit Narang", Designation.Team_Lead, 8));
oList.Add(new Developer(1056, "Mohit singh", Designation.Sr_Software_Engineer, 7));
oList.Add(new Developer(1081, "Kalit Sikka", Designation.Sr_Software_Engineer, 6));
oList.Add(new Developer(1102, "Sunil Mittal", Designation.Software_Engineer, 4));
oList.Add(new Developer(1106, "Jaswinder saini", Designation.Software_Engineer, 3));
oList.Add(new Developer(1108, "Varinder Pal", Designation.Software_Engineer, 3));
return oList;
}
///
/// Simple LINQ method using where clause
///

public void Linq_WhereClause() {
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
var lowNums =
from n in numbers
where n < 5
select n;
Console.WriteLine("Numbers < 5:");
foreach (var x in lowNums) {
Console.WriteLine(x);
}
}
///
/// Using where clause on List object
///

public void ListWithWhere()
{
List oDeveloper = GetDeveloperList();
var Experienced =
from d in oDeveloper
where d.Experience > 5
select d;
Console.WriteLine("Experienced Developers");
foreach (var Developer in Experienced) {
Console.WriteLine(string.Format("Name {0} - Experience {1}", Developer.Name, Developer.Experience));
}
}
///
/// Using where clause and And clause on List object
///

public void ListWithWhereClause_AndClause() {
List oDeveloper = GetDeveloperList();
var ExperiencedSeniorDeveloper =
from d in oDeveloper
where d.Experience > 5 && d.eDesgination == Designation.Sr_Software_Engineer
select d;
Console.WriteLine("Senior Experienced Developers");
foreach (var Developer in ExperiencedSeniorDeveloper) {
Console.WriteLine(string.Format("Name {0} - Experience {1} and Desgination {2}", Developer.Name, Developer.Experience, Developer.eDesgination));
}
}
///
/// Using Lambda in Linq on List
///

public void LinqWithLambda() {
List oDeveloper = GetDeveloperList();
//Lambda expressions allow us to write functions that can be passed
//as arguments to methods, for example, to supply predicates for
//subsequent evaluation.
var MaxExperience = oDeveloper.Where(x => x.Experience > 5).OrderBy(x => x);
Console.WriteLine("Most Experienced Developer");
foreach (var Developer in MaxExperience) {
Console.WriteLine(string.Format("Name {0} - Experience {1} and Desgination {2}", Developer.Name, Developer.Experience, Developer.eDesgination));
}
}
///
/// Add info into List object
///

public void AddValuesIntoList() {
List oDeveloper = GetDeveloperList();
var AddOneYearofTrainingInExperience =
from d in oDeveloper
select d.Experience+1;
Console.WriteLine("Extended Experienced");
foreach (var Developer in AddOneYearofTrainingInExperience) {
Console.WriteLine(string.Format("Name {0} - Experience {1}", Developer.Name, Developer.Experience));
}
}
///
/// Changing Case
///

public void ChangeTheCaseOfText() {
string[] words = { "aMit", "BalWinDer", "cHeRry", "haRRY", "NaraGh" };
var upperLowerWords =
from w in words
select new {Upper = w.ToUpper(), Lower = w.ToLower()};
foreach (var ul in upperLowerWords) {
Console.WriteLine("Uppercase_Names: {0}, Lowercase_Names: {1}", ul.Upper, ul.Lower);
}
}
///
/// Giving Alias name to fields
///

public void GivingAliasNames()
{
List oDeveloper = GetDeveloperList();
var ChangeNames =
from d in oDeveloper
select new {Developer_Name = d.Name, Developer_Desg = d.eDesgination};
Console.WriteLine("Developer Details");
foreach (var Developer in ChangeNames)
{
Console.WriteLine(string.Format("Name {0} - Desgination {1}", Developer.Developer_Name, Developer.Developer_Desg));
}
}
///
/// Getting values from Differnet arrays
///

public void GetValueFromArrays() {
int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 };
int[] numbersB = { 1, 3, 5, 7, 8 };
var pairs =
from a in numbersA
from b in numbersB
where a < b
select new {a, b};
Console.WriteLine("Pairs where a < b:");
foreach (var pair in pairs) {
Console.WriteLine("{0} is less than {1}", pair.a, pair.b);
}
}
///
/// Skipping the values from the collection
///

public void Linq22() {
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
var allButFirst4Numbers = numbers.Skip(4);
Console.WriteLine("All but first 4 numbers:");
foreach (var n in allButFirst4Numbers) {
Console.WriteLine(n);
}
}
///
/// TakeWhile to return elements starting from the
/// beginning of the array until a number is hit that is not less than 5
///

public void Linq2TakeWhile() {
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
var firstNumbersLessThan6 = numbers.TakeWhile(n => n < 5);
Console.WriteLine("First numbers less than 5:");
foreach (var n in firstNumbersLessThan6) {
Console.WriteLine(n);
}
}
///
/// Sorting Values in List
///

public void SortingVaues()
{
List oDeveloper = GetDeveloperList();
var SortByDesgAndExperience =
from d in oDeveloper
orderby d.eDesgination, d.Experience descending
select d;
Console.WriteLine("Sorted Data");
foreach (var Developer in SortByDesgAndExperience) {
Console.WriteLine(string.Format("Name {0} - Experience {1}", Developer.Name, Developer.Experience));
}
}
///
/// Getting distinct values from the array
///

public void DistinctValues() {
int[] vals = { 2, 4, 7, 9, 5, 4, 2, 2 , 2, 3, 5, 5 };
var unique = vals.Distinct();
Console.WriteLine("Distinct Values:");
foreach (var v in unique) {
Console.WriteLine(v);
}
}
///
/// Union of two arrays
///

public void UnionLINQ() {
int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 };
int[] numbersB = { 1, 3, 5, 7, 8 };
var uniqueNumbers = numbersA.Union(numbersB);
Console.WriteLine("Unique numbers from both arrays:");
foreach (var n in uniqueNumbers) {
Console.WriteLine(n);
}
}
///
/// First match from the List
///

public void FirstMatch() {
List oDeveloper = GetDeveloperList();
var FirstMatch =
(from d in oDeveloper
where d.Experience > 2 && d.eDesgination == Designation.Software_Engineer
select d).First();
Console.WriteLine("FirstMatch");
Console.WriteLine(string.Format("Name {0}", FirstMatch.Name));
}
}
public class Developer
{
public int ID;
public string Name;
public Designation eDesgination;
public WorkStatus eWorkStatus;
public double Salary;
public string ProjectManager;
public int Experience;
public Developer(int ID, string Name)
{
this.ID = ID;
this.Name = Name;
}
public Developer(int ID, string Name, Designation eDesgination, int Experience)
{
this.ID = ID;
this.Name = Name;
this.eDesgination = eDesgination;
this.Experience = Experience;
}
}
public enum WorkStatus
{
ProjectInHand,
OnBench
}

public enum Designation
{
Software_Engineer,
Sr_Software_Engineer,
Team_Lead,
Project_Lead
}

}

Regular Expression in .Net

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace PubishApps
{
/************************************************
* Topic : Usage of RegularExpression in .Net
* Reference System.Text.RegularExpressions.
* Author : kalit sikka
* Summary: This regex helper class is design to provide set of static methods to validate commonly used patterns like Email-ID, URL, IP Address, Social Security number, Zip codes etc.
* You just need to add this .cs file in your project to use any of the method in it.
* For : Personal Blog
* **********************************************/
///
/// This helper class contain general regex static methods which in today to today coding tasks
///

public class RegexHelper
{
public static bool IsValidEmailID(string sEmailID)
{
Regex oEmail =
new Regex(@"^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$");
return oEmail.IsMatch(sEmailID);
}
public static bool IsValidURL(string sUrl)
{
Regex oURL =
new Regex(@"^[a-zA-Z0-9\-\.]+\.(comorgnetmileduCOMORGNETMILEDU)$"); // you add more here like au, in
return oURL.IsMatch(sUrl);
}
public static bool IsValidPhoneNumber(string sPhone)
{
Regex oPhone =
new Regex(@"^[2-9]\d{2}-\d{3}-\d{4}$"); // US Phone - like 800-555-5555 333-444-5555 212-666-1234
return oPhone.IsMatch(sPhone);
}
public static bool IsValidIndianMobile(string sMobile)
{
Regex oMobile =
new Regex(@"^((\+){0,1}91(\s){0,1}(\-){0,1}(\s){0,1}){0,1}98(\s){0,1}(\-){0,1}(\s){0,1}[1-9]{1}[0-9]{7}$"); // Indian Mobile - like +919847444225 +91-98-44111112 98 44111116
return oMobile.IsMatch(sMobile);
}

public static bool IsValidUKMobile(string sMobile)
{
Regex oMobile =
new Regex(@"^07([\d]{3})[(\D\s)]?[\d]{3}[(\D\s)]?[\d]{3}$"); // UK Mobile - like 07976444333 07956-514333 07988-321-213
return oMobile.IsMatch(sMobile);
}
public static bool IsValidUSZipCode(string sZipCode)
{
Regex oZipCode =
new Regex(@"^\d{5}$"); // ZipCode - like 33333 55555 23445
return oZipCode.IsMatch(sZipCode);
}
public static bool IsValidIPAddress(string sIPAddress)
{
Regex oIP =
new Regex(@"^(25[0-5]2[0-4][0-9][0-1]{1}[0-9]{2}[1-9]{1}[0-9]{1}[1-9])\.(25[0-5]2[0-4][0-9][0-1]{1}[0-9]{2}[1-9]{1}[0-9]{1}[1-9]0)\.(25[0-5]2[0-4][0-9][0-1]{1}[0-9]{2}[1-9]{1}[0-9]{1}[1-9]0)\.(25[0-5]2[0-4][0-9][0-1]{1}[0-9]{2}[1-9]{1}[0-9]{1}[0-9])$"); // IP Address - like 127.0.0.1 255.255.255.0 192.168.0.1
return oIP.IsMatch(sIPAddress);
}

public static bool IsValidTime(string sTime)
{
Regex oTime =
new Regex(@"^(20212223[01]dd)(([:][0-5]d){1,2})$");
return oTime.IsMatch(sTime);
}
public static bool Is24HourTimeFormat(string sTime)
{
Regex oTime =
new Regex(@"^(([0-1]?[0-9])([2][0-3])):([0-5]?[0-9])(:([0-5]?[0-9]))?$"); // like - 12:15 10:26:59 22:01:15 - Seconds are optional here
return oTime.IsMatch(sTime);
}
public static bool Is12HourTimeFormat(string sTime)
{
Regex oTime =
new Regex(@" ^ *(1[0-2][1-9]):[0-5][0-9] *(apAP)(mM) *$"); // like - 12:00am 1:00 PM 12:59 pm
return oTime.IsMatch(sTime);
}
public static bool DataFormat(string sDate)
{
// dd/MM/yyyy format with leap year validations
Regex oDate =
new Regex(@"^(((0[1-9][12]\d3[01])\/(0[13578]1[02])\/((1[6-9][2-9]\d)\d{2}))((0[1-9][12]\d30)\/(0[13456789]1[012])\/((1[6-9][2-9]\d)\d{2}))((0[1-9]1\d2[0-8])\/02\/((1[6-9][2-9]\d)\d{2}))(29\/02\/((1[6-9][2-9]\d)(0[48][2468][048][13579][26])((16[2468][048][3579][26])00))))$");
return oDate.IsMatch(sDate);
}
public static bool IsNumeric(string sNum)
{
// Natural Number
Regex oNum =
new Regex(@"0*[1-9][0-9]*");
return oNum.IsMatch(sNum);
}
public static bool IsAlpha(string sValue)
{
// Alpha value
Regex oValue =
new Regex(@"[^a-zA-Z]");
return oValue.IsMatch(sValue);
}
public static bool IsAlphaNumeric(string strToCheck)
{
Regex oCheck=new Regex("[^a-zA-Z0-9]");
return oCheck.IsMatch(strToCheck);
}

public static bool IsStrongPassword(string sPassword)
{
// Check Password with atleast 8 characters, no more than 15 characters, and must include atleast one upper case letter, one lower case letter, and one numeric digit.
Regex oPassword =
new Regex(@"^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,15}$");
return oPassword.IsMatch(sPassword);
}
public static bool IsSocialSecurityNumber(string sValue)
{
// U.S. social security numbers, within the range of numbers that have been currently allocated
Regex oValue =
new Regex(@"^(?!000)([0-6]\d{2}7([0-6]\d7[012]))([ -]?)(?!00)\d\d\3(?!0000)\d{4}");
return oValue.IsMatch(sValue);
}
public static bool IsVISACreditCard(string sValue)
{
// Validate against a visa card number
Regex oValue =
new Regex(@"^([4]{1})([0-9]{12,15})$");
return oValue.IsMatch(sValue);
}
public static bool IsISBNumber(string sValue)
{
// ISBN validation expression
Regex oValue =
new Regex(@"^\d{9}[\dX]$");
return oValue.IsMatch(sValue);
}
public static bool IsDollarAmount(string sAmt)
{
// Dollar decimal amount with or without dollar sign
Regex oAmt =
new Regex(@"^\$?\d+(\.(\d{2}))?$");
return oAmt.IsMatch(sAmt);
}
///
/// Method to return string array of splitted values from string
///

/// string value [KabirSachinJohnMarkDavidkevinNash]
/// separator in the string value
///
public static string[] mSplitString(string value, string separator)
{
string[] values = new string[25];
if(!string.IsNullOrEmpty(value) && !string.IsNullOrEmpty(separator))
{
values = System.Text.RegularExpressions.Regex.Split(value, separator);
return values;
}
return null;
}
///
/// To Remove specfic string from Collection of string
///

/// KabirSachinJohnMarkDavidkevinNash
/// separator in the string value
///
public static string mRemoveStringFromCollection(string strNames, string sep, string specificStr)
{
List list = new List();
string strValue = String.Empty;
if (!string.IsNullOrEmpty(strNames))
{
list.AddRange(Regex.Split(strNames, sep));
foreach (string str in list)
{
if (!str.Contains(specificStr))
{
if (string.IsNullOrEmpty(strValue))
{
strValue = str;
}
else
{
strValue = strValue + sep + str;
}
}
}
return strValue;
}
return strNames;
}

}
}
Locations of visitors to this page