Friday, December 11, 2009

Regular Expressions

Regular expressions is the term used for a codified method of searching invented or defined by the American mathematician Stephen Kleene.

The syntax (language format) described is compliant with extended regular expressions (EREs) defined in IEEE POSIX 1003.2 (Section 2.8). EREs are now commonly supported by Apache, PHP4, Javascript 1.3+, MS Visual Studio, MS Frontpage, most visual editors, vi, emac, the GNU family of tools (including grep, awk and sed) as well as many others. Extended Regular Expressions (EREs) will support Basic Regular Expressions (BREs are essentially a subset of EREs). Most applications, utilities and laguages that implement RE's extend the capabilities defined. The appropriate documentation should always be consulted.

Some Definitions

  • Liter

A literal is any character we use in a search or matching expression, for example, to find ind in windows the ind is a literal string - each character plays a part in the search, it is literally the string we want to find.

  • Metacharacter

A metacharacter is one or more special characters that have a unique meaning
and are NOT used as literals in the search expression, for example, the character
^ (circumflex or caret) is a metacharacter.

  • Escape sequence
An escape sequence is a way of indicating that we want to use one of our metacharacters as a literal. In a regular expression an escape sequence involves placing the metacharacter \ (backslash) in front of the metacharacter that we want to use as a literal, for example, if we want to find ^ind in w^indow then we use the search string \^ind and if we want to find file://file/ in the string c:\\file then we would need to use the search string \\\\file (each \ we want to search for (a literal) is preceded by an escape sequence \).
  • Target string
This term describes the string that we will be searching, that is, the string in which we want to find our match or search pattern.
  • Search expression
This term describes the expression that we will be using to search our target string, that is, the pattern we use to find what we want.

Brackets, Ranges and Negation
Bracket expressions introduce our first metacharacters, in this case the square brackets which allow us to define list of things to test for rather than the single characters we have been checking up until now. These lists can be grouped into what are known as Character Classes typically comprising well know groups such as all numbers etc.
[ ]
Match anything inside the square brackets for one character position once and only once, for example, [12] means match the target to either 1 or 2 while [0123456789] means match to any character in the range 0 to 9.
-
The - (dash) inside square brackets is the 'range separator' and allows us to define a range, in our example above of [0123456789] we could rewrite it as [0-9]
.
You can define more than one range inside a list e.g. [0-9A-C] means check for 0 to 9 and A to C (but not a to c).
Note: To test for - inside brackets (as a literal) it must come first or last, that is, [-0-9] will test for - and 0 to 9.
^
The ^ (circumflex or caret) inside square brackets negates the expression (we will see an alternate use for the circumflex/caret outside square brackets later), for example, [^Ff] means anything except upper or lower case F and [^a-z] means everything except lower case a to z.
Note:Spaces, or in this case the lack of them, between ranges are very important.
Positioning (or Anchors)
We can control where in our target strings the matches are valid. The following
is a list of metacharacters that affect the position of the search:
^
The ^ (circumflex or caret) outside square brackets means look only at the beginning of the target string, for example, ^Win will not find Windows in string Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt) but ^Moz will find Mozilla.

$
The $ (dollar) means look only at the end of the target string, for example, fox$ will find a match in 'silver fox' since it appears at the end of the string but not in 'the fox jumped over the moon'.
.
The . (period) means any character(s) in this position, for example, ton. will find tons and tonneau but not wanton, wantons and ton because it has no following character.
NOTE:
Many systems and utilities, but not all, support special positioning macros, for example \< match at beginning of word, \> match at end of word, \b match at the begining OR end of word , \B except at the beginning or end of a word.

List of the common values.
Character Class Abbreviations
\d
Match any character in the range 0 - 9 (equivalent of POSIX [:digit:])

\D
Match any character NOT in the range 0 - 9 (equivalent of POSIX [^[:digit:]])

\s
Match any whitespace characters (space, tab etc.). (equivalent of POSIX [:space:]
EXCEPT VT is not recognized)

\S
Match any character NOT whitespace (space, tab). (equivalent of POSIX [^[:space:]])

\w
Match any character in the range 0 - 9, A - Z and a - z (equivalent of POSIX [:alnum:])

\W
Match any character NOT the range 0 - 9, A - Z and a - z (equivalent of POSIX [^[:alnum:]])

Positional Abbreviations
\b
Word boundary. Match any character(s) at the beginning (\bxx) and/or end (xx\b) of a word, thus \bton\b will find ton but not tons, but \bton will find tons.
\B
Not word boundary. Match any character(s) NOT at the beginning(\Bxx) and/or end (xx\B) of a word, thus \Bton\B will find wantons but not tons, but ton\B will find tons.

Iteration 'metacharacters'
The following is a set of iteration metacharacters (a.k.a. quantifiers) that can control the number of times a character or string is found in our searches.

?
The ? (question mark) matches the preceding character 0 or 1 times only, for example, colou?r will find both color and colour.

*
The * (asterisk or star) matches the preceding character 0 or more times, for example, tre* will find tree and tread and trough.

+
The + (plus) matches the previous character 1 or more times, for example, tre+ will find tree and tread but not trough.
{n}
Matches the preceding character n times exactly, for example, to find a local phone number we could use [0-9]{3}-[0-9]{4} which would find any number of the form 123-4567.
Note: The - (dash) in this case, because it is outside the square brackets, is a literal.Value is enclosed in braces (curly brackets).

{n,m}
Matches the preceding character at least n times but not more than m times, for example, 'ba{2,3}b' will find 'baab' and 'baaab' but NOT 'bab' or 'baaaab'. Values are enclosed in braces (curly brackets).
More 'metacharacters'
The following is a set of additional metacharacters that provide added power to our searches:
()
The ( (open parenthesis) and ) (close parenthesis) may be used to group (or bind) parts of our search expression together.

The (vertical bar or pipe) is called alternation in techspeak and means find the left hand OR right values, for example, gr(ae)y will find 'gray' or 'grey'.
<humblepie> In our examples, we blew this expression ^([L-Z]in), we incorrectly stated that this would negate the tests [L-Z], the '^' only performs this function inside square brackets, here it is outside the square brackets and is an anchor indicating 'start from first character'. Many thanks to Mirko Stojanovic for pointing it out and apologies to one and all.</humblepie>

For More http://www.zytrax.com/tech/web/regex.htm

Wednesday, December 9, 2009

Data Controls

Template


Header

Footer

Item

EditItem

AlternatingItem

Pager

EmptyData

Separator

SelectedItem

GridView

Yes

Yes

Yes

Yes

Yes

Yes

Yes

No

No

DataList

Yes

Yes

yes

Yes

Yes

No

No

Yes

Yes

FormView

Yes

Yes

Yes

Yes

No

Yes

Yes

No

No

DetailsView

Yes

Yes

No

No

No

Yes

Yes

No

No

Repeater

Yes

Yes

Yes

No

Yes

No

No

Yes

No


Feature


Repeater

DataList

GridView

Table Layout

No

No

Yes

Flow Layout

Yes

Yes

No

Column Layout

No

Yes

No

Style Properties

No

Yes

Yes

Templates

Yes

Yes

Columns/Optional

Select/ Edit/Delete

No

Yes

Yes

Sort

No

No

Yes

Paging

No

No

Yes



Capabilities


Read

Edit

Create

GridView

Yes

Yes

No

DataList

Yes

Yes

No

Repeater

Read Only

No

No

DetailsView

Yes

Yes

Yes

FormView

Yes

Yes

Yes

Repeater Vs DataList Controls

Both the Repeater and DataList controls helps us to display a set of data items at a time. For example, you can use these controls to display all the rows contained in a database table.
The Repeater control is entirely template driven. You can format the rendered output of the control in any way that you please. For example, you can use the Repeater control to display records in a bulleted list, a set of HTML tables, or even in a comma-delimited list.
The DataList control is also template driven. However, unlike the Repeater control, the default behavior of the DataList control is to render its contents into an HTML table. The DataList control renders each record from its data source into a separate HTML table cell.
The Repeater control provides you with the maximum amount of flexibility in rendering a set of database records. You can format the output of the Repeater control in any way that you please.
The DataList control, like the Repeater control, is template driven. Unlike the Repeater control, by default, the DataList renders an HTML table. Because the DataList uses a particular layout to render its content, you are provided with more formatting options when using the DataList control.

DetailsView Vs FormView Controls

The DetailsView and FormView controls, these controls enable us to work with a single data item at a time. Both controls enable you to display, edit, insert, and delete data items such as database records. Furthermore, both controls enable you to page forward and backward through a set of data items.
The difference between the two controls concerns the user interface that the controls render. The DetailsView control always renders each field in a separate HTML table row. The FormView control, on the other hand, uses a template that enables you to completely customize the user interface rendered by the control.
A DetailsView control renders an HTML table that displays the contents of a single database record. The DetailsView supports both declarative and programmatic databinding.
You can use the FormView control to do anything that you can do with the DetailsView control. Just as you can with the DetailsView control, you can use the FormView control to display, page, edit, insert, and delete database records. However, unlike the DetailsView control, the FormView control is entirely template driven.
The FormView control provides you with more control over the layout of a form. Furthermore, adding validation controls to a FormView is easier than adding validation controls to a DetailsView control.

DataList Control

The DataList control renders data as table and enables you to display data records in different layouts, such as ordering them in columns or rows. You can configure the DataList control to enable users to edit or delete a record in the table. The DataList control differs from the Repeater control in that the DataList control explicitly places items in an HTML table, where as the Repeater control does not.
The DataList control is, like the Repeater control, used to display a repeated list
of items that are bound to the control. However, the DataList control adds a table around the data items by default.
<asp:DataList ID="DataList1" runat="server">
<HeaderTemplate>
</HeaderTemplate>
<ItemTemplate>
</ItemTemplate>
<AlternatingItemTemplate>
</AlternatingItemTemplate>
<EditItemTemplate>
</EditItemTemplate>
<SelectedItemTemplate>
</SelectedItemTemplate>
<SeparatorTemplate>
</SeparatorTemplate>
<FooterTemplate>
</FooterTemplate>
</asp:DataList>

Repeater Control

The Repeater control renders a read-only list from a set of records returned from
a data source. Like the FormView control, the Repeater control does not specify
a built-in layout. Instead you create the layout for the Repeater control using templates.

The Repeater control is used to display a repeated list of items that are bound
to the control.

Repeater is used when you want to just read your data, Read Only but here you can customize everything, repeater provide full control for UI.
<asp:Repeater ID="Repeater1" runat="server">
<HeaderTemplate>
</HeaderTemplate>
<ItemTemplate>
</ItemTemplate>
<AlternatingItemTemplate>
</AlternatingItemTemplate>
<SeparatorTemplate>
</SeparatorTemplate>
<FooterTemplate>
</FooterTemplate>
</asp:Repeater>

FormView Control

The FormView control renders a single record at a time from a data source and provides the capability to page through multiple records, as well as to insert, update, and delete records, similar to the DetailsView control. However, the difference between the FormView and the DetailsView controls is that the DetailsView control uses a table-based layout where each field of the data record is displayed as a row in the control. In contrast, the FormView control does not specify a pre-defined layout for displaying a record. Instead, you create templates that contain controls to display individual fields from the record. The template contains the formatting, controls, and binding expressions used to lay out the form.
FormView is a data-bound user interface control that renders a single record at
a time from its associated data source, optionally providing paging buttons to navigate between records.

Read/Edit/Create FormView is more over same as detailsview and used similarly.
<asp:FormView ID="FormView1" runat="server">
<HeaderTemplate>
</HeaderTemplate>
<ItemTemplate>
</ItemTemplate>
<InsertItemTemplate>
</InsertItemTemplate>
<EditItemTemplate>
</EditItemTemplate>
<EmptyDataTemplate>
</EmptyDataTemplate>
<PagerTemplate>
</PagerTemplate>
<FooterTemplate>
</FooterTemplate>
</asp:FormView>

DetailsView Control

The DetailsView control renders a single record at a time as a table and provides
the capability to page through multiple records, as well as to insert, update, and
delete records. The DetailsView control is often used in master-detail scenarios
where the selected record in a master control such as a GridView control determines the record displayed by the DetailsView control.

DetailsView is a data-bound user interface control that renders a single record
at a time from its associated data source, optionally providing paging buttons to
navigate between records. It is similar to the Form View of an Access database,
and is typically used for updating and/or inserting new records. It is often used
in a master-details scenario where the selected record of the master control (GridView, for example) determines the DetailsView display record.

DetailView mostly used with GridView for Master Detail relationship, where master details are shown using GridView and when you click a particular row, you can show further details of individual row using DetailView either at the same page or at separate page.
Here you can read, edit and create (add a new row/record)
<asp:DetailsView ID="DetailsView1" runat="server">
<HeaderTemplate>
</HeaderTemplate>
<EmptyDataTemplate>
</EmptyDataTemplate>
<PagerTemplate>
</PagerTemplate>
<FooterTemplate>
</FooterTemplate>
</asp:DetailsView>

GridView / DataList Control

GridView Control
The GridView control displays data as a table and provides the capability to sort columns, page through data, and edit or delete a single record. the GridView control offers improvements such as the ability to define multiple primary key fields, improved user interface customization using bound fields and templates, and a new model for handling or canceling events
datagrid and gridview both have same functionality to display your data in the form of a table.
Datagrid is used in Windows Application whereas gridview is used in Web Applications.

The GridView control is the workhorse of the ASP.NET 2.0 Framework. It is one of
the most feature-rich and complicated of all the ASP.NET controls. The GridView
control enables you to display, select, sort, page, and edit data items such as
database records.
You also get the chance to tackle several advanced topics. For example, we can highlight certain rows in a GridView depending on the data the row represents.
  • No code required.
  • No code required for PageIndexChanged.
  • Needs little code for update operation.
  • GridView supports events fired before and after database updates
Datagrid..
  • Code requires to handle the SortCommand event and rebind grid required.
  • Code requires to handle the PageIndexChanged.
  • Need extensive code for update operation on data.
  • When compared to gridview less events supported.

GridView is new version and extension of earlier asp.net 1.1 Gridview in ASP.NET
2.0 and onwards versions.
GridView is used for control, editing data, your own custom template, sorting kind
of scenarios but you can not customize everything.

<asp:GridView ID="GridView1" runat="server">
<EmptyDataTemplate>
</EmptyDataTemplate>
<Columns>
<asp:BoundField />
<asp:ButtonField />
<asp:CheckBoxField />
<asp:CommandField />
<asp:HyperLinkField />
<asp:ImageField>
</asp:ImageField>
<asp:TemplateField>
<HeaderTemplate>
</HeaderTemplate>
<ItemTemplate>
</ItemTemplate>
<AlternatingItemTemplate>
</AlternatingItemTemplate>
<InsertItemTemplate>
</InsertItemTemplate>
<EditItemTemplate>
</EditItemTemplate>
<FooterTemplate>
</FooterTemplate>
</asp:TemplateField>
</Columns>
<PagerTemplate>
</PagerTemplate>
</asp:GridView>

Wednesday, December 2, 2009

Read Mail from Gmail/ Hotmail....

Aspx file

<table border="1" style="background-color: Lime;">

<tr><td>

User Name

</td><td>

<asp:TextBox ID="txtUserName" runat="server" >

</asp:TextBox>

</td>

</tr>

<tr>

<td>Password</td>

<td>

<asp:TextBox ID="txtPassword" TextMode="Password" runat="server"></asp:TextBox>

</td>

</tr>

<tr><td>Read</td><td>
<asp:Button ID="btnHotmail" BorderWidth="0" BorderStyle="Groove" runat="server" OnClick="btnHotmail_Click"
Text="Hotmail" />

<asp:Button ID="btnGmail" BorderWidth="0" BorderStyle="Groove" runat="server" OnClick="btnGmail_Click" Text="Gmail" />

</td></tr>

</table>

Code Behind File

using System.IO;

using System.Net.NetworkInformation;

using System.Net.Security;

using System.Net.Socke

public void ReadMail(string hostName, int port, string userName, string password)

{

try

{

// create an instance of TcpClient
TcpClient tcpclient = new TcpClient();

// HOST NAME POP SERVER and gmail uses port number 995 for POP
tcpclient.Connect(hostName, port);

// This is Secure Stream // opened the connection between client and POP Server

System.Net.Security.SslStream sslstream = new SslStream(tcpclient.GetStream());

// authenticate as client
sslstream.AuthenticateAsClient(hostName);

//bool flag = sslstream.IsAuthenticated;

// check flag
// Asssigned the writer to stream
System.IO.StreamWriter sw = new StreamWriter(sslstream);

// Assigned reader to stream

System.IO.StreamReader reader = new StreamReader(sslstream);

// refer POP rfc command, there very few around 6-9 command

sw.WriteLine("USER " + userName);

// sent to server

sw.Flush();

sw.WriteLine("PASS " + password);

sw.Flush();

// this will retrive your first email
sw.WriteLine("RETR 1");

sw.Flush();

// close the connection

sw.WriteLine("Quit ");

sw.Flush();

string str = string.Empty;

string strTemp = string.Empty;

while ((strTemp = reader.ReadLine()) != null)

{

// find the . character in line

if (strTemp == ".")

{

break;

}

if (strTemp.IndexOf("-ERR") != -1)

{

break;

}

str += strTemp;

}

Response.Write(str);

Response.Write("<BR>" +
"Congratulation.. ....!!! You read your first gmail email "
);

}

catch (Exception ex)

{

Response.Write(ex.Message);

}

}

Read From Gmail

Before using this code make sure you are able to access your gmail email using outlook if not then login to www.gmail.com click on settings => pop => check to access email outside gmail web client

ReadMail("pop.gmail.com", 995, txtUserName.Text.Trim(),
txtPassword.Text.Trim());

Read From Hotmail

This article will read your first hotmail email. I have explained the commands that we can use with POP3.
I'm using ASP.net with C#.net and TcpIPClient to read email.
I saw many developers are searching for the code to read an email programatically.

ReadMail("pop3.live.com", 995, txtUserName.Text.Trim(),
txtPassword.Text.Trim());

____________________________________________________
Note* there are very few commands required to communicate with pop3 server.
You can use below commands to perform the operations on your pop3 server.
For more details about below command please refer RFC
http://www.ietf.org/rfc/rfc1939.txt

e.g.
1. LIST
2.
RETR
3.
STAT
4.
USER
5.
PASS
6.
DELE
7. QUIT

You can use above command instead of RETR
sw.WriteLine("STAT 1");
sw.Flush();
I'm using System.Net.Security.SslStream becaus hotmail accepts secure socket.