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