Thursday, October 21, 2010

Inheritance

As we all know, inheritance is just the hierarchical relationship between various classes.
Class from which another class is inheriting some methods is base class and the other one is known as derived class.

For ex:
Class AA
{ }

Class BB : AA
{ }

Here, AA is your base class and B is your derived class.

Now a very basic question:
When we create an object of derived class, which constructor gets called?
1. Of Base Class
2. Of Derived Class
3. Both
4. None

Let's try to figure it with this example:

class AA
{
public AA()
{
Console.WriteLine("In AA");
}
}

class BB : AA
{
public BB()
{
Console.WriteLine("In BB");
}
}

class CC : BB
{
public CC()
{
Console.WriteLine("In CC");
}
}

Here, class CC is inheriting class BB and class BB is inheriting class AA.

class Program
{
static void Main(string[] args)
{
CC c = new CC();
}
}

I just created an object of CC in another class.
Now which constructor will be called?

Here is the output :


In case of inheritance, derived class always calls base class constructor first and then its own constructor.
Here, object of CC called the constructor of BB and similarly BB calls its base class constructor i.e., AA.
so, the sequence of execution is:
AA constructor -> BB constructor -> CC constructor

Read More..

Const Keyword

Const is a keyword which can be use to declare fields. We can initialize Const variable only at the time of declaration and cant modify it at runtime.
We cant make a Const field as static.
Const fields are compile-time constants.

For ex:
I have a class which contains two const variables.
class TestConst
{
public const int a = 10;
public const int b = 7;
}

I have another class, where i have created an object of TestConst class.
class Program
{
static void Main(string[] args)
{
Console.WriteLine(TestConst.a);
Console.WriteLine(TestConst.b);
Console.ReadLine();
}
}

We cant access a const variable through object of class. We can always access a const variable with class name only.
Like : ClassName.ConstVariableName
Read More..

ReadOnly Modifier

ReadOnly is a modifier which can be use to declare fields. We can initialize readonly variable either at the time of declaration or through constructor.

ReadOnly fields can be used for runtime constants as we can declare value through constructors.

For ex:
I have a class which contains two readonly variables.
class TestReadOnly
{
public readonly int a = 10;
public readonly int b;

public TestReadOnly()
{
b = 15;
}

public TestReadOnly(int newB)
{
b = newB;
}
}

I have another class, where i have created an object of TestReadOnly class.
class Program
{
static void Main(string[] args)
{
TestReadOnly test = new TestReadOnly();
Console.WriteLine(test.a);
Console.WriteLine(test.b);
test = new TestReadOnly(20);
Console.WriteLine(test.b);
Console.ReadLine();
}
}

Whenever, I want to reassign the value to a readonly variable, I have to call the parametrized constructor of the class and pass the new value.
Read More..

Monday, October 11, 2010

BENEFITS OF XMLDATADOCUMENT OVER XMLDOCUMENT

Recently I came across a requirement, where I need to fetch the data from GridView and convert it to XML.
I had a predefined format of XML, in which I need to save the data :
<root>
<rec>
<amount />
<remark />
</rec>
<rec>
<amount />
<remark />
</rec>
</root>
Also, I have a checkbox in the first column of GridView. I have to fetch records for which checkbox is checked.

I can use either XMLDocument or XMLDataDocument for the same.

1. Using XMLDocument:XmlDocument xmlDoc = new XmlDocument();
XmlElement root = xmlDoc.CreateElement("root"); xmlDoc.AppendChild(root);
foreach (GridViewRow Row in grdTest.Rows)
{
CheckBox chkTopUpRequest = (CheckBox)Row.FindControl("chkRequest");
if (null != chkTopUpRequest && chkTopUpRequest.Checked)
{
XmlElement rec = xmlDoc.CreateElement("rec");
root.AppendChild(rec);
XmlElement topupid = xmlDoc.CreateElement("topupid");
topupid.InnerText = grdTopUpRequest.DataKeys[Row.RowIndex].Value.ToString();
rec.AppendChild(topupid);
XmlElement amount = xmlDoc.CreateElement("amount");
TextBox txtAmount = (TextBox)Row.FindControl("txtAmount");
amount.InnerText = txtAmount.Text.Trim();
rec.AppendChild(amount);
XmlElement remarks = xmlDoc.CreateElement("remarks");
TextBox txtRemarks = (TextBox)Row.FindControl("txtRemarks");
remarks.InnerText = txtRemarks.Text.Trim();
rec.AppendChild(remarks);
}
}
2. Using XMLDataDocument :

DataSet dataSet = new DataSet("root");
DataTable dataTable = new DataTable("rec");
dataTable.Columns.AddRange(new DataColumn[]
{
new DataColumn("topupid"),
new DataColumn("amount"),
new DataColumn("remarks")
});

foreach (GridViewRow Row in grdTest.Rows)
{
CheckBox chkTopUpRequest = (CheckBox)Row.FindControl("chkRequest");
if (null != chkTopUpRequest && chkTopUpRequest.Checked)
{
TextBox txtAmount = (TextBox)Row.FindControl("txtAmount");
TextBox txtRemarks = (TextBox)Row.FindControl("txtRemarks");
dataTable.Rows.Add(grdTopUpRequest.DataKeys[Row.RowIndex].Value.ToString(),
txtAmount.Text.Trim(),
txtRemarks.Text.Trim());
}
}
dataSet.Tables.Add(dataTable);
XmlDataDocument xmlDataDoc = new XmlDataDocument(dataSet);


XMLDocument is an in-memory (cache) tree representation of an XML document and enables the navigation and editing of this document.

The XmlDataDocument class extends XmlDocument and allows structured data to be stored, retrieved, and manipulated through a relational DataSet. This class allows components to mix XML and relational views of the underlying data.

Read More..

Friday, October 8, 2010

HANDLING KEYPRESS EVENT OF TEXTBOX INSIDE GRIDVIEW

I have a GridView, in which my first column is Template Field which contains textbox.

<asp:gridview id="grdTest" runat="server" autogeneratecolumns="false" datakeynames="TestID">
<columns>
<asp:templatefield HeaderText="Amount">
<itemtemplate>
<asp:TextBox ID="txtAmount" runat="server" Text='' />
</itemtemplate>
<asp:boundfield datafield="Name" headertext="Name" />
</asp:TemplateField>
</columns>
</asp:GridView>

Now, I want that user can only enter integer value in txtAmount textbox. I want to handle this client side only. So, I used jquery and handled KeyPress event of textbox. By doing so, user can only enter digits. If user will press any non-numeric key it will not get entered.

<script type="text/javascript">
$(document).ready(function () {
$("#<%=grdTest.ClientID %> INPUT[id$='txtAmount']").keypress(
function IsNumericHandler(e) {
var unicode = e.charCode ? e.charCode : e.keyCode

//if the key isn't the backspace key (which we should allow)
if (unicode != 8) {
//if not a number
if (unicode <> 57)
//disable key press
return false;
}
});
});
</script>

Read More..

Thursday, October 7, 2010

SELECT ALL \ DESELECT FUNCTIONALITY FOR CHECKBOX INSIDE GRIDVIEW

I have a GridView, in which my first column is Template Field which contains checkbox.

<asp:gridview id="grdTest" runat="server" autogeneratecolumns="false" datakeynames="TestID">
<columns>
<asp:templatefield>
<headertemplate>
<asp:checkbox id="ChkAll" runat="server" />
</headertemplate>
<itemtemplate>
<asp:checkbox id="chkRequest" runat="server" />
</itemtemplate>
<asp:boundfield datafield="Name" headertext="Name" />
</asp:TemplateField>
</columns>
</asp:GridView>

Now, I want on click of ChkAll checkbox (which is in header of grid) all the checkboxes in the first row gets selected. Also, when I deselect any checkbox in first row, ChkAll checkbox gets deselected.

I did this using jquery :

<script type="text/javascript">
$(document).ready(function () {
//To Select/Deselect all checkboxes on click of ChkAll checkbox.
var chkBox = $("input[id$='ChkAll']");
chkBox.click(
function () {
$("#<%=grdTest.ClientID %> INPUT[type='checkbox']")
.attr('checked', chkBox.is(':checked'));
});

// To deselect CheckAll when a GridView CheckBox is unchecked.
$("#<%=grdTest.ClientID %> INPUT[type='checkbox']").click(
function (e) {
if (!$(this)[0].checked) {
chkBox.attr("checked", false);
}
});
});
</script>
Read More..

Tuesday, October 5, 2010

CREATING XML FROM GRIDVIEW AND SAVING IT AS STRING USING XMLDOCUMENT

Today, I came across a requirement in which i have a GridView which have some databound columns and one checkbox cloumn. On a button click, I need to pick all the rows in which checkbox is checked.
I need to convert the data of all the rows in XML format and then at last save it in database. But, before saving it, I again need to convert it to string format.

//These two namespaces are required to create XML Document and String Writer.
using System.Xml;
using System.IO;

protected string CreateXMLFromGrid()
{
// Created new XmlDocument to store Xml.
XmlDocument xmlDoc = new XmlDocument();
//Created the root element and added it to xmlDoc.
XmlElement root = xmlDoc.CreateElement("root");
xmlDoc.AppendChild(root);

foreach (GridViewRow Row in grdTopUpRequest.Rows)
{
CheckBox chkTopUpRequest = (CheckBox)Row.FindControl("chkRequest");
if (null != chkTopUpRequest && chkTopUpRequest.Checked)
{
XmlElement rec = xmlDoc.CreateElement("rec");
root.AppendChild(rec);

XmlElement topupid = xmlDoc.CreateElement("topupid");
topupid.InnerText = grdTopUpRequest.DataKeys[Row.RowIndex].Value.ToString();
rec.AppendChild(topupid);

XmlElement amount = xmlDoc.CreateElement("amount");
TextBox txtAmount = (TextBox)Row.FindControl("txtAmount");
amount.InnerText = txtAmount.Text.Trim();
rec.AppendChild(amount);

XmlElement remarks = xmlDoc.CreateElement("remarks");
TextBox txtRemarks = (TextBox)Row.FindControl("txtRemarks");
amount.InnerText = txtRemarks.Text.Trim();
rec.AppendChild(remarks);
}

// Creating an Object of StringWriter and assigining it to XmlTextWriter, whixh will
// copy the xml from xmlDoc to StringWriter.
StringWriter strWriter = new StringWriter();
XmlTextWriter xmlTxtWriter = new XmlTextWriter(strWriter);
xmlDoc.WriteTo(xmlTxtWriter);
return strWriter.ToString();
}
}

Read More..

DIFFERENCE BETWEEN FINDALL() AND WHERE()

First of all how both these works :
Suppose we have a class Person :

public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}

Now, create an object of person class :
Person person = new Person();

Take a List of person class :
List lstPerson = new List();

Now, assign values to this class and add it to list :
person.FirstName = "FirstName1";
person.LastName = "LastName1";
lstPerson.Add(person);

person.FirstName = "FirstName2";
person.LastName = "LastName2";
lstPerson.Add(person);

Now, I want to find all the records where FirstName = "FirstName1".
To do this, I have two options : FindAll() and Where()

FindAll() :
List result = lstPerson.FindAll(delegate(Person per)
{
return per.FirstName == "Firstname1";
});

Where() :
List result = lstPerson.Where((Person per) => per.FirstName == "FirstName1").ToList();


Both will return the same result. So, the question is which one should be used in which situation?
There are some difference between both, now you have to decide which one suits your requirement:

1. FindAll() is a function on the List type, it's not a LINQ extension method like Where. The LINQ extension methods work on any type that implements IEnumerable, whereas FindAll can only be used on List instances (or instances of classes that inherit from it, of course). If our collection is IEnumerable type, then we can't use FindAll() as it's a function of List.

2. The FindAll method of the List class actually constructs a new list object, and adds results to it. The Where extension method for IEnumerable will simply iterate over an existing list and yield an enumeration of the matching results without creating or adding anything (other than the enumerator itself.)

3. Where is much faster than FindAll. No matter how big the list is, Where takes exactly the same amount of time because Where() just creates a query, It doesn't actually do anything, unlike FindAll which does create a list.

Read More..

Monday, October 4, 2010

PRIME NUMBER

public bool IsPrime(int x)
{
if (x == 1)
{
return true;
}
else
{
for (int i = x - 1; i > 1; i--)
{
if (x % i == 0)
{
return false;
}
}
return true;
}
}
Read More..

RECURSIVE PROGRAM TO FIND THE FACTORIAL

public int Factorial(int x)
{
if (x == 1)
{
return x;
}
else
{
return x * Factorial(x - 1);
}
}
Read More..

Saturday, October 2, 2010

CUSTOM CONTROLS IN ASP.NET - GRIDVIEW

In Asp.net, we generally bind GridView with a data source. That data source can be anything like – Data Table, Data View, Class Object, etc. If data source contains some value then it simply binds the grid and displays the records according to grid formatting.
What happens when data source is empty? – GridView will not get displayed.
If suppose, we want to display header and footer of grid in each and every case then what should we do?
One way is to manipulate the data source and add a blank row in it and bind it with grid. It will display the header and footer along with a blank row in grid. This is dirty coding.
Another way is custom controls. Before moving to custom controls first understand the workflow of Grid View.
Steps to create a GridView custom control and use it in aspx page:
1. Take a class and declare a namespace.
2. Inherit your class with GridView (System.Web.UI.WebControls.GridView) class:
using System;
using System.Collections;
using System.Data;
using System.Web.UI.WebControls;

namespace AlwaysShowHeaderFooter {
public class GridViewAlwaysShow : GridView {
}
}
3. Add a delegate above the class:
public delegate IEnumerable MustAddARowHandler(IEnumerable data);

4. Add an event inside the class:
public event MustAddARowHandler MustAddARow;

5. Create a Method to raise this event:
protected IEnumerable OnMustAddARow(IEnumerable data) {
if (MustAddARow == null) {
throw new NullReferenceException("The datasource has no rows. You must handle the \"MustAddARow\" Event.");
}
return MustAddARow(data);
}

6. Now come to main aspx page where you want to display the grid. Register your custom control namespace here:
<%@ Register TagPrefix="Custom" Namespace="AlwaysShowHeaderFooter" %>

7. Add your custom grid on page and call OnMustAddARow function:
OnMustAddARow="grdCustom_MustAddARow"

8. Now define the grdEmail_MustAddARow() in aspx.cs file:
//Flag used to identify if the datasource is empty.
bool _isEmpty = false;

///
/// Handles the MustAddARow event of grdEmail
///

/// The data.
///
protected IEnumerable grdEmail_MustAddARow(IEnumerable data)
{
ListDictionary ldEmails = (ListDictionary)data;
ldEmails.Add("", "");
_isEmpty = true;
return ldEmails;
}
Here we have set a flag _isEmpty = true to check if data source is empty.
I have bind the grid with ListDictionary, you can take any data source.

9. Come back to your custom control class and override the OnDataBound() method to check if data source is empty. As we have added a dummy(blank) row in grdEmail_MustAddARow(), it will display a blank row in grid at runtime which should not come. So we will hide it.
protected override void OnDataBound(EventArgs e)
{

//if in DesignMode, don't do anything special. Just call base and return.
if (DesignMode)
{
base.OnDataBound(e);
return;
}

//hide the dummy row.
if (_isEmpty)
{
Rows[0].Visible = false;
}
base.OnDataBound(e);
}

10. GridView have a method protected internal override void PerformDataBinding(IEnumerable data) which gets called through Databind() method of GridView.

11. Now override the PerformDataBinding method to call OnMustAddARow method if data source is blank. This method gets called from databind() method of GridView.
protected override void PerformDataBinding(IEnumerable data)
{

//If in DesignMode, don't do anything special. Just call base and return.
if (DesignMode)
{
base.PerformDataBinding(data);
return;
}

//Count the data items.(I wish I knew a better way to do this.)
int objectItemCount = 0;
foreach (object o in data)
{
objectItemCount++;
}

//If there is a count, don't do anything special. Just call base and return.
if (objectItemCount > 0)
{
base.PerformDataBinding(data);
return;
}

//Set these values so the GridView knows what's up.
SelectArguments.TotalRowCount++;
_isEmpty = true;

//If it's a DataView, it will work without having to handle the MustAddARow event.
if (data.GetType() == typeof(DataView))
{
//Add a row and use that new view.
DataView dv = (DataView)data;
dv.Table.Rows.InsertAt(dv.Table.NewRow(), 0);
base.PerformDataBinding(dv.Table.DefaultView);
return;
}
else
{
//If you are using some custom object, you need to handle this event.
base.PerformDataBinding(OnMustAddARow(data));
return;
}
}

That’s it!! Your custom control is ready to run...:)
Read More..

WORKFLOW OF GRIDVIEW

Have you ever thought how grid view handles all the events like RowDataBound, RowCommand, RowDeleting, RowUpdating, etc...? If you look in System.Web.UI.WebControls.GridView class, you will find lots of properties, events and methods.

Let’s take RowDataBound as an example to understand the GridView workflow.
1. We have an event RowDataBound which gets fired OnRowDataBound method :
// Summary: Occurs when a data row is bound to data in a
System.Web.UI.WebControls.GridView control.
public event GridViewRowEventHandler RowDataBound;

2. We have a delegate to handle RowDataBound event :
using System;
namespace System.Web.UI.WebControls
{
// Summary: Represents the method that handles the
// System.Web.UI.WebControls.GridView.RowCreated and S
// System.Web.UI.WebControls.GridView.RowDataBound events of a
// System.Web.UI.WebControls.GridView control.
// Parameters:
// sender: The source of the event.
//e: A System.Web.UI.WebControls.GridViewRowEventArgs object that contains the event data.
public delegate void GridViewRowEventHandler(object sender, GridViewRowEventArgs e);
}

3. We have a method OnRowDataBound() which raises the RowDataBound event :
// Summary: Raises the System.Web.UI.WebControls.GridView.RowDataBound event.
// Parameters:
// e: A System.Web.UI.WebControls.GridViewRowEventArgs that contains event data.
protected virtual void OnRowDataBound(GridViewRowEventArgs e);

4. Create grdTest_RowDataBound function in aspx.cs and write the code which you want to execute for each row when data binding takes and call it in OnRowDataBound()
Here I am generating the Serial No., which will be displayed in grid.

private int intSerialNo = 1;

/// Handles the RowDataBound event of the grdEmail control.
/// The source of the event.
/// The instance containing the event data.
protected void grdEmail_RowDataBound(object sender, GridViewRowEventArgs e)
{
if ((e.Row.RowType == DataControlRowType.DataRow) || (e.Row.RowType == DataControlRowType.Footer))
{
Label serialNumber = (Label)e.Row.FindControl("lblSno");
serialNumber.Text = intSerialNo.ToString() + ".";
intSerialNo = intSerialNo + 1;
}
}

This is how GridView works!!
Read More..

Wednesday, September 29, 2010

Basics Of WCF

Main components of WCF are :
1. EndPonits
2. Binding
3. Contract

A service is a construct that exposes one or more endpoints, each of which exposes one or more service operations.
The endpoint of a service specifies an address where the service can be found, a binding that contains the information that a client must communicate with the service, and a contract that defines the functionality provided by the service to its clients.

Windows Communication Foundation (WCF) enables applications to communicate whether they are on the same computer, across the Internet, or on different application platforms.

The Basic Tasks

The basic tasks to perform are, in order:

1. Define the service contract. A service contract specifies the signature of a service, the data it exchanges, and other contractually required data.

2. Implement the contract. To implement a service contract, create the class that implements the contract and specify custom behaviors that the runtime should have.

3. Configure the service by specifying endpoint information and other behavior information.

4. Host the service in an application.

5. Build a client application.
Read More..

Friday, June 4, 2010

FIND() AND FINDALL() FUNCTIONS IN LINQ

We have a table Customer which contains details of a customer like name, address, phone, etc.

we have a list of customers -
List lstCust = new List();

we want to find a particular record from this list based on some criteria.
say where name = 'abc';

In C# :

List lstCustResult = lstCust .FindAll(
delegate(Customers cust)
{
return cust.name == "abc";
});

This will return all the records having name ="abc".

suppose we want to fetch a particular value based on some criteria, in that case we will use Find instead of FindAll.

string name = lstCust .Find(
delegate(Customers cust)
{
return cust.id== 1;
}).name;

Also, if suppose we have a list of strings and want to find a particular record in that list.
For That we need to do something like this :

List lstNumbers = new List();
lstNumbers.Add("One");
lstNumbers.Add("Two");
lstNumbers.Add("Three");
lstNumbers.Add("Four");
lstNumbers.Add("One");
List result= lst.FindAll(delegate(string name)
{
name = "One";
return lstNumbers.Equals(name);
});
Read More..

Tuesday, January 26, 2010

VALIDATION IN ASP.NET USING REGULAR EXPRESSION

ASP.NET provides a suite of validation controls, which make validating inputs on web forms extremely easy compared to the same task using legacy (or classic if you prefer) ASP. One of the more powerful validators is the RegularExpressionValidator which, as you might guess, allows you to validate inputs by providing a regular expression which must match the input. The regular expression pattern is specified by setting the ValidationExpression property of the control. An example validator for a ZIP code field is shown below:

ControlToValidate="ZipCodeTextBox" ErrorMessage="Invalid ZIP code

format; format should be either 12345 or 12345-6789."

ValidationExpression="(\d{5}(-\d{4})?" />

A few things to note about the RegularExpressionValidator:

  • It will never be activated by an empty string in the control it is validating. Only the RequiredFieldValidator catches empty strings
  • You do not need to specify beginning of string and end of string matching characters (^ and $)—they are assumed. If you add them, it won't hurt (or change) anything—it's simply unnecessary.
  • As with all validation controls, the validation is done client-side as well as server side. If your regular expression is not ECMAScript compliant, it will fail on the client. To avoid this, either ensure your expression is ECMAScript compliant, or set the control to perform its validation only on the server.

Regular Expression API

Outside of the ASP.NET validation controls, most of the time when you're using regular expressions in .NET, you'll use the classes found in the System.Text.RegularExpressions namespace. In particular, the main classes you'll want to become familiar with are Regex, Match, and MatchCollection.

Incidentally, there is some dispute as to whether the shortened version of regular expression, regex, should be pronounced /reg-eks/ or /rej-eks/. Personally I prefer the latter, but there are experts in both pronunciation camps, so pick whichever sounds better to you.

The Regex class has a rich set of methods and properties, which can be rather daunting if you haven't used it before. A summary of the most frequently used methods is included here:

Method

Description

Escape / Unescape

Escapes metacharacters in a string for use as literals in an expression.

IsMatch

Returns true if the regex finds a match in the input string.

Match

Returns a Match object if a match is found in the input string.

Matches

Returns a MatchCollection object containing any and all matches found in the input string.

Replace

Replaces matches in the input string with a given replacement string.

Split

Returns an array of strings by splitting up the input string into array elements separated by regex matches.

In addition to many methods, there are also a number of options that can be specified, usually in the constructor of the Regex object. These options are part of a bitmask, and thus can be OR'd together (yes, you can have both Multiline and Singleline turned on at the same time).

Option

Description

Compiled

Use this option when you will be doing many match operations in a loop. This saves the step of parsing the expression on each iteration.

Multiline

Has nothing to do with how many lines are in the input string. Rather, this simply modifies the behavior of ^ and $ so that they match BOL and EOL instead of the beginning and end of the entire input string.

IgnoreCase

Causes the pattern to ignore case sensitivity when matching the search string.

IgnorePatternWhitespace

Allows pattern to have as much white space as desired, and also enables the use of in-pattern comments, using the (?# comment #) syntax.

SingleLine

Has nothing to do with how many lines are in the input string. Rather, will cause the . (period) metacharacter to match any character, instead of any character except \n, which is the default.

Some common things you may use regular expressions for include validating, matching, and replacing. In many cases, these can be accomplished using static methods of the Regex class, without any need to instantiate the Regex class itself. To perform validation, all you must do is create or find the right expression and apply it to your input string using the IsMatch() method of the Regex class. For example, the following function demonstrates how to use a regular expression to validate a ZIP code:

private void ValidateZipButton_Click(object sender, System.EventArgs e)

{

String ZipRegex = @"^\d{5}$";

if(Regex.IsMatch(ZipTextBox.Text, ZipRegex))

{

ResultLabel.Text = "ZIP is valid!";

}

else

{

ResultLabel.Text = "ZIP is invalid!";

}

}

Similarly, the static Replace() method can be used to replace matches with a particular string, as this snippet demonstrates:

String newText = Regex.Replace(inputString, pattern, replacementText);

Finally, you can iterate through a collection of matches in an input string using code like this:

private void MatchButton_Click(object sender, System.EventArgs e)

{

MatchCollection matches = Regex.Matches(SearchStringTextBox.Text,

MatchExpressionTextBox.Text);

MatchCountLabel.Text = matches.Count.ToString();

MatchesLabel.Text = "";

foreach(Match match in matches)

{

MatchesLabel.Text += "Found " + match.ToString() + " at

position " + match.Index + ".
";

}

}

Where you'll typically need to instantiate an instance of the Regex class is when you need to specify anything outside the default behavior. In particular, setting options. For example, to create an instance of Regex that ignores case and pattern white space, and then retrieve the set of matches for that expression, you would use code like the following:

Regex re = new Regex(pattern,

RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);

MatchCollection mc = re.Matches(inputString);

Complete working versions of these samples are included in the download for this article, as simple ASP.NET pages.

Advanced Topics

Two regular expression features that really make me have to think are named groups and lookaround processing. Since you'll only need these on rare occasions, I'll only briefly describe these topics here.

With named groups, you can name individual matching groups and then refer to these groups within the expression programmatically. This can be especially powerful when combined with the Replace method as a way of reformatting an input string by re-arranging the order and placement of the elements within the input string. For example, suppose you were given a date in string format of the form MM/DD/YYYY and you wanted it in the form DD-MM-YYYY. You could use write an expression to capture the first format, iterate through its Matches collection, parse each string, and use string manipulation to build the replacement string. This would require a fair amount of code and a fair amount of processing. Using named groups, you could accomplish the same things like so:

String MDYToDMY(String input)

{

return Regex.Replace(intput, @"\b(?\d{1,2})/(?\d{1,2}/(?\d{4})\b", "${day}-

${month}-${year}");

}

You can also refer to groups by number as well as by name. In any event such references are collectively referred to as backreferences. Another common use of backreferences is within matching expressions themselves, such as this expression for finding repeated letters: [a-z]\1. This will match 'aa', 'bb', 'cc' and is not the same as [a-z]{2} or [a-z][a-z] which are equivalent and would allow 'ab' or 'ac' or any other two-letter combination. Backreferences allow an expression to remember things about parts of the input string it has already parsed and matched.

"Lookaround processing" refers to positive and negative lookahead and lookbehind capabilities supported by many regular expression engines. Not all regular expression engines support all variations of lookaround processing. These constructs do not consume characters even though they may match them. Some patterns are impossible to describe without lookaround processing, especially ones in which the existence of one part of the pattern depends on the existence of a separate part. The syntax for each flavor of lookaround is described below.

Syntax

Description

(?=…)

Positive Lookahead

(?!...)

Negative Lookahead

(?<=…)

Positive Lookbehind

(?

Negative Lookbehind

One example of where lookaround processing is necessary is password validation. Consider a password restriction where the password must be between 4 and 8 characters long, and must contain at least one digit. You could do this by just testing \d for a match and using string operations to test the length, but to do the whole thing in a regular expression requires lookahead. Specifically positive lookahead, as this expression demonstrates: ^(?=.*\d).{4,8}$

Conclusion

Regular expressions provide a very powerful way to describe patterns in text, making them an excellent resource for string validation and manipulation. The .NET Framework provides first-rate support for regular expressions in its System.Text.RegularExpressions namespace and specifically the Regex class found there. Using the API is simple; coming up with the right regular expression is often the tough part. Luckily, regular expressions are highly reusable, and there are many resources online where you can find expressions designed by others or get help with ones you are struggling to create.

Read More..