Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Sunday, November 23, 2008

ref - out : at a glance

The ref


The ref keyword causes argument passed by reference. The effect is that any chnages is made to the parameter in the method will be reflected in that variable when control passes back to the calling method. To use a ref parameter, both the method definition and the calling method must explicitly use the ref keyword.

An argument passed to to a ref parameter must first be initialized. his differs it from out whose argument need not be explicitly initialize before being passed.

Both ref and out are treated differently at runtime, but treated the same at compilation. Therefore, methods can't be overloaded if one method takes a ref keyword and the other takes an out argument.

Exaple:

class refpara
{
static void refMath(ref String STR)
{
STR = "Hi!";
}
static void Main()
{
String str = "Hello!";
refMath(ref str);
}
}


The out



The out keyword also causes argument to be passed by reference. There no need to initialize the out variable as it requires in case of ref variable.

Exaple:

class refpara
{
static void refMath(out String STR)
{
STR = "Hi!";
}
static void Main()
{
String str = "Hello!";
refMath(out str);
}
}

Sunday, August 10, 2008

Classes and Structures

Lets take these in general words, these are template from which you define object to access their functionalities. The programmers of C++ and Java are well aware from these two names. Till now from above reading you new that Classes are reference type and structures are value type so they are stored on Heap and Stack respectively in memory.

Structures
A structure in C# is simply a composite data type [you are well aware from composite data type, refer to data types for more details], which consists number of members of other types. The structure define simply by using the struct keyword



struct enroll
{
public string name, fname, mname;
public string char sex;
Public int age;
public string address;
}




Important points towards structures

There are some points towards structures:
1. Structures are C# composite data types
2. By default like classes structures are public
3. Sealed and Abstract modifiers cant applicable on structures
4. Structures have no inheritance features
5. A variable of structure type contains all the data of structure
6. Structures cant allow a destructor
7. By default C# provides a constructor with no parameter, but explicitly you cant use and replace it.
8. Initializations of fields are not allowed.


Classes
It is cleared from above study that Classes are reference type. A class is a collection of its data members. Data members are those members of class which contains the data of class like fields, constants and events etc. Class is declared simply just followed by class keyword with optional modifiers; by default C# classes are public.



class myClass
{
public int xyz;
public string name;
public const int y=22;
}







In above, all members are public, when we declare members we can optionally supply modifiers, in C# all class members private by default.



/* This Example is a part of different
* examples shown in Book:
* C#2005 Beginners: A Step Ahead
* Written by: Gaurav Arora
* Reach at : gaurav.aroraose@yahoo.co.in*/
// File name : classstructue.cs
using System;
namespace CSharp.AStepAhead.classstructue
{
class enroll
{
string name, fname;
int age;
char sex;
void getInfo()
{
Console.WriteLine("Enter Name: ");
name = Console.ReadLine();
Console.WriteLine("Enter Father Name: ");
fname = Console.ReadLine();
Console.WriteLine("Enter age: ");
age = int.Parse(Console.ReadLine());
Console.WriteLine("Enter Sex [Male -m, Female - f]: ");
sex = char.Parse(Console.ReadLine());
}
void showInfo()
{
Console.Clear();
Console.WriteLine("You have provided following information(s): \n");
Console.WriteLine(" Name : {0}\n Father Name : {1}\n Age : {2}\n Sex : {3}", name, fname, age, sex);
Console.ReadLine();
}
static void Main()
{
//Create an object of class
enroll objEnroll = new enroll();
objEnroll.getInfo();
objEnroll.showInfo();
}
}
}



Monday, August 4, 2008

A Simple VideoPlayer Custom COntrol - Uses in application

In my previous post, I have presented a Video Player Custom control which plays all type of streaming media. Now, here I am presenting a simple way to apply the same custom control in web application.

File Name : VideoPLayerCustomControl.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="VideoPLayerCustomControl.aspx.cs"
Inherits="VideoPLayerCustomControl" %>

<%@ Register TagPrefix="whPlayer" TagName= "vaPlayer" Src="~/videoPlayer.ascx" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Video Player Using Custom Control</title>
</head>
<body>
<form id="form1" runat="server">
<div align="center">
<whPlayer:vaPlayer ID="videoPlayer" autoStart="true" runat="server" />
<br />
<asp:ValidationSummary id="valSumm" runat="server" />
<asp:Label ID="lblVideoName" Text="Enter Video Name" runat ="server" />
<asp:TextBox ID="txtVideoName" runat="server" EnableViewState="true" Text="D:\Videos\AVSEQ06.DAT" />
<asp:Button ID="btnPlayVide" runat="server" OnClick="btnPlayVide_Click" Text="Play Video" />
<asp:RequiredFieldValidator id="rfvtxtVideoName" ControlToValidate="txtVideoName" text="*" ErrorMessage="Please eneter Video to play" runat="server" />

</div>
</form>
</body>
</html>
File Name : VideoPLayerCustomControl.aspx.cs
/* This Example is a part of different
* examples shown in Book:
* C#2005 Beginners: A Step Ahead
* Written by: Gaurav Arora
* Reach at : g_arora@hotmail.com */
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;

public partial class VideoPLayerCustomControl : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["sourceUrl"] != null)
this.videoPlayer.sourceUrl = Convert.ToString(Request.QueryString["sourceUrl"]);

videoPlayer.autoStart = true;
videoPlayer.height = "300";
videoPlayer.width = "300";
}

protected void btnPlayVide_Click(object sender, EventArgs e)
{
if(IsValid)
Response.Redirect("videoplayercustomcontrol.aspx?sourceUrl=" + txtVideoName.Text);

}
}

Steps to run the application
1. Open VS2005
2. Select New Web application

3. Add new Page from existing pages and browse to attachment
4. Run the applcation by prssing F5

OR

3. If not want to add new page just copy and paste the content from above, code(s)
4. Make sure all contents would be copied and then press F5

and then Enjoy the video...

A VideoPlayer - Custom Control

Some day ago, I have faced a little problem to show streaming contents on my Web-Projects, I have gone through many R & d’s and then decided to write a custom control for the same, then I have written a custom control.

Here, the same, I want to share with you:
File Name : videoPlayer.ascx

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="videoPlayer.ascx.cs" Inherits="videoPlayer" %>
<asp:PlaceHolder ID="phError" runat="server" Visible="false">
<%asp:Label ID="lblError" runat="server" ForeColor="Red" Text="Error" />
</asp:PlaceHolder>
<asp:Table ID="tblPlayer" runat="server" BorderWidth="1">
<asp:TableRow>
<asp:TableCell>
<asp:Literal ID="ltVideo" runat="server" />
</asp:TableCell>
</asp:TableRow>
</asp:Table>

Now, lets start to write code-behind as follows:
File Name : videoPlayer.ascx.cs

/* This Example is a part of different
* examples shown in Book:
* C#2005 Beginners: A Step Ahead
* Written by: Gaurav Arora
* Reach at : g_arora@hotmail.com */
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;

public partial class videoPlayer : System.Web.UI.UserControl
{
#region Properties to customize the Video/Audio Control

///
/// true:FullScreen, false:CustomSize
///
public Boolean isFullSize
{
set
{
ViewState["isFullSize"] = value;
}
get
{
if (ViewState["isFullSize"] != null)
return Convert.ToBoolean(ViewState["isFullSize"]);
else
return true;
}
}
///
/// Full url-path of Video/Audio
///
public String sourceUrl
{

set
{
ViewState["sourceUrl"] = value;
}
get
{
if (ViewState["sourceUrl"] != null)
return Convert.ToString(ViewState["sourceUrl"]);
else
return "http://www.video.com/myVideo.mpeg"; //Default video

}

}
///
/// width of player
///
public String width
{
set
{
ViewState["width"] = value;
}
get
{
if (ViewState["width"] != null)
return Convert.ToString(ViewState["width"]);
else
return "640";
}
}
///
/// Height of player
///
public String height
{
set
{
ViewState["height"] = value;
}
get
{
if (ViewState["height"] != null)
return Convert.ToString(ViewState["height"]);
else
return "480";
}
}
///
/// Custom message when player initializes
///
public String standByMessage
{
set
{
ViewState["standByMessage"] = value;
}
get
{
if (ViewState["standByMessage"] != null)
return Convert.ToString(ViewState["standByMessage"]);
else
return "Please wait while the player inializes...";
}
}
///
/// States whether media automatic starts or not
///
public Boolean autoStart
{
set
{
ViewState["autoStart"] = value;
}
get
{
if (ViewState["autoStart"] != null)
return Convert.ToBoolean(ViewState["autoStart"]);
else
return true;
}
}
///
/// -100 is fully left, 100 is fully right.
///
public String balance
{
set
{
ViewState["balance"] = value;
}
get
{
try
{
if (ViewState["balance"] != null)
return Convert.ToString(ViewState["balance"]);
else
return "0";
}
catch
{
return "0";
}
}
}
///
/// Position in seconds when starting.
///
public Int32 currentPosition
{
set
{
ViewState["currentPosition"] = value;
}
get
{
if (ViewState["currentPosition"] != null)
return Convert.ToInt32(ViewState["currentPosition"]);
else
return 0;
}
}

///
/// Show play/stop/pause controls
///
public Boolean showcontrols
{
set
{
ViewState["showcontrols"] = value;
}
get
{
if (ViewState["showcontrols"] != null)
return Convert.ToBoolean(ViewState["showcontrols"]);
else
return true;
}
}
///
/// Allow right-click
///
public Boolean contextMenu
{
set
{
ViewState["contextMenu"] = value;
}
get
{
if (ViewState["contextMenu"] != null)
return Convert.ToBoolean(ViewState["contextMenu"]);
else
return false;
}
}
///
/// Toggle sound on/off
///
public Boolean mute
{
set
{
ViewState["mute"] = value;
}
get
{
if (ViewState["mute"] != null)
return Convert.ToBoolean(ViewState["mute"]);
else
return false;
}
}
///
/// Number of times the content will play
///
public Int32 playCount
{
set
{
ViewState["playCount"] = value;
}
get
{
if (ViewState["playCount"] != null)
return Convert.ToInt32(ViewState["playCount"]);
else
return 1;
}

}
///
/// 0.5=Slow, 1.0=Normal, 2.0=Fast
///
public Double rate
{
set
{
ViewState["rate"] = value;
}
get
{
if (ViewState["rate"] != null)
return Convert.ToDouble(ViewState["rate"]);
else
return 1.0;
}
}
///
/// full, mini, custom, none, invisible
///
public String uiMode
{
set
{
ViewState["uiMode"] = value;
}
get
{
if (ViewState["uiMode"] != null)
return Convert.ToString(ViewState["uiMode"]);
else
return "Full";
}
}
///
/// Show or hide the name of the file/url
///
public Boolean showDisplay
{
set
{
ViewState["showDisplay"] = value;
}
get
{
if (ViewState["showDisplay"] != null)
return Convert.ToBoolean(ViewState["showDisplay"]);
else
return false;
}
}

///
/// 0=lowest, 50= normal, 100=highest
///
public Int32 volume
{
set
{
ViewState["volume"] = value;
}
get
{
if (ViewState["volume"] != null)
return Convert.ToInt32(ViewState["volume"]);
else
return 50;
}
}

#endregion

protected void Page_Load(object sender, EventArgs e)
{

try
{
ltVideo.Text = this.VideoPlayer(this.sourceUrl, this.isFullSize);
}
catch (Exception ex)
{
lblError.Text = ex.ToString();
phError.Visible = true;
}
}

#region VideoPlayer
///
/// Return the whPlayer to Play Video/ Audio Content
///
/// Source of content
/// Size of Player
///
private string VideoPlayer(string strsourceUrl, bool boolFullSize)
{
string whPlayer = "";
strsourceUrl = strsourceUrl + "";
strsourceUrl = strsourceUrl.Trim();

if (strsourceUrl.Length < 0)
{
//play content
}
else
{
throw new System.ArgumentNullException("strsourceUrl");
}


if (boolFullSize)
{
//this.width = String.Empty;
//this.height = String.Empty;
this.width = "800";
this.height = "600";
}
else
{
//continue with supplied width/height
}

whPlayer = whPlayer + "";

return whPlayer;
}
#endregion
}

In Next article, I will tell you how to use the VideoPlayer Custom Control?

Sunday, July 27, 2008

How to shuffle results - SqlServer?

This is an interesting question asked by Mr. Ram Nath Rao.
The history is:

Mr. Nath wants to shuffle his record(s) every time when the page refreshes, the same has been tried with the use of rand() function by him. Unfortunately, the results were not as expected.

Now, lets elaborate some of interesting points towards this :

When anybody use rand() function what happened [check followings)]:

Select rand()as Random Number --creates random number

The result may be:



When you will repeat above statement, the new result is entirely different from the earlier one.

Now, try another similar query:

Select rand()as Random_Number,* from Employees

The result may be:



In above, result note-down first column Random_Number, this column has the similar value through-out the result.

In another words from above, we can sum-it up that the rand() function, generates a random number which is a new every time we press or execute the query.

Also, it doesn't change with rows when result-set retrieves more than one row(s). So, the problem of Mr. Ram Nath Rao doesn't resolve with the use of rand() function.

I recommended newid() to retrieve the solution of Mr. Ram's problem.

Check the following query:

Select newid()as RowId,* from Employees

Above generates following result(s):-



Note-down first column of above result(s), every row has a new value.

Now, lets try to ad-more stuff in above:

Select newid()as RowId,* from Employees order by newid()



Now, regenerate above result(s) one more time, you can get different resul(s). This is the solution of the problem.

The above is a short-description how we can get random data in SqlServer2000.

Its time to do all above at application-level, I have decided to use Vs2005:

Step(s) to use:

1. Start your Vs2005
2. Create a New Website project named its as 'Shuffle Result'.
3. Rename your default web-page to 'shuffleresults.aspx'
4. Write the following lines



5. Press F7 or choose code-view from Solution-Explorer
6. Add following sort-of-code in 'shuffleresults.aspx.cs'



7. Run the above application by pressing F5.
8. It will generate following result(s):



This is the normal output.

9. Click on 'Shuffle Results' button and check the output it might be s following :



The above is described "How one can shuffle the result-sets".

Sunday, July 20, 2008

How to review .net application?

This is not the end when any application has been developed. After development there are many steps which must have to pass by an application. The same process is know as Code-Review process.

Here are certain guidelines which are assembled by me for my work, I hope these will suits you. Your comments and further guidelines will recoupe our stuffs.



This is just a snapshot the guidelines due to limited resources I am unable to write here all document. You can collect the document by sending me a mail :
gUnderscorearoraAthotmailDotcom with subject: Guidelines-Code-Review.

Saturday, July 12, 2008

What are New Features in Vs 2008 and .Net Framework 3.5?

Vs 2008 and .Net Framework 3.5 [code name is Orcas] has many new features and improvements prior versions.

The following are some of the features:

1. VS 2008 Multi-Targeting Support
VS 2008 support multiple versions .net framework i.e 2.0, 3.0, 3.5. Where VS 2002 supports only .Net 1.0, VS 2003 supports 1.1, and VS 2005 supports 2.0 . That means you can open an existing project or create a new one with VS 2008, you can pick which version of the .NET Framework to work with - and the IDE will update its compilers and feature-set to match this. And that features, controls, projects, item-templates, and assembly references that not work with that version of the framework will be hidden. Unfotunately it does not support .net1.0 and .net 1.1. but we can run VS 2008 side by side with VS 2005 , VS 2003 and VS 2002 on the same machine.


2. JavaScript Intellisense
I really like this feature. When ever I am writing java script in previous versions , i think about intellisense of java script. Now i got this feature in VS 2008. Now i can enjoy the coding of javascript. This makes developer easy write of coding java script. This built in support of javascript intellisense avoids java script errors and makes developing the code faster.


3. JavaScript Debugging

Now, you can stop putting alerts in your code unnecessarly to check the values of the variable or flow of control. Instead of alert boxes , now you can keep break points to look the values of the variables at client script within your server-side .aspx and .master source files. Its like putting break points in server script.
Any JavaScript breakpoints you set will be saved auto matically in VS 2008 when you close the project/solution. When you open up the project again, the previous locations you set the breakpoints on will still have them enabled.

4. Support of AJAX

One of the main features of VS 2008 is ASP.NET AJAX Control Extenders. These controls are derived from the System.Web.UI.ExtenderControl base class, and which can be used to add additional functionality [usually AJAX or JavaScript support] to existing controls already declared on a page. They enable developers to nicely encapsulate UI behavior, and make it really easy to add richer functionality to an application.


5. Split of Design view and Source view Editing

In VS 2005 and previous versions , we have design view , source view .Besides this features it supports a new "split-view" mode when working on pages. This allows you to see both the HTML source and the Design View at the same-time, and easily have any changes you make in one view be updated in the other. We can set the split view as horizontal as well as vertical to use maximum screen.


6. CSS Manager

VS 2008 supports a new tool window inside the IDE called "Manage Styles". This shows all of the CSS stylesheets, and their corresponding rules, for the page you are currently editing. It can be used both when you are in design-view, as well as when you are in source view on a page.


7. Nested Master Pages

The great feature in asp.net 2.0 is Master page. By including master page we can avoid redundant code like header , footer and menus which contains in all pages. Now in VS 2008,we can create nested master pages.


8. List View Control

One of the new controls in ASP.NET 3.5 is the control. The ListView control supports the data editing, insertion, deleting, paging and sorting semantics of higher-level controls like the GridView. But - unlike the GridView - it provides you with complete control over the html markup generated.

Saturday, July 5, 2008

Regular Expressions - How to use?

Yesterday, my colleague Kumar Abhishek asked me to draft a Regular expression to validate url like : regularexp.indotnet.com, he was bit confused to draft the same as he wan't aware the power of regular expression. The following lines are for Kumar Abhishek


The following are special characters when working with Regular Expressions.
They will be discussed throughout the article.

. $ ^ { [ (  ) * + ? \

Matching any character with dot - The Period sign [.]


The full stop or period character (.) is known as dot. It is a
wildcard that will match any character except a new line (\n). For
example
if I wanted to match the 'g' character followed by any two characters.


Text: gau shu gnt cow
Regex: g..
Matches: gau shu gnt cow
gau
gnt

If the Singleline option is enabled, a dot matches any character
including the new line character.


Matching word characters - The Word sign [w]


Backslash and a lowercase 'w' (\w) is a character class that
will match any word character. The following Regular Expression matches 'a'
followed by two word characters.

Text: abc anaconda ant cow apple
Regex: a\w\w
Matches: abc anaconda ant cow apple
abc
ana
ant
app

Backslash and an uppercase 'W' (\W) will match any non-word
character.


Matching white-space - The Space sign [s]


White-space can be matched using \s (backslash and 's').
The following Regular Expression matches the letter 'a' followed by two word
characters then a white space character.

Text: "abc anaconda ant"
Regex: a\w\w\s
Matches:
"abc "

Note that ant was not matched as it is not followed by a white space
character.


White-space is defined as the space character, new line (\n),
form feed (\f), carriage return (\r), tab
(\t) and vertical tab (\v). Be careful using \s as it
can lead to unexpected behaviour by matching line breaks (\n and
\r). Sometimes it is better to explicitly specify the characters to
match instead of using \s. e.g. to match Tab and Space use
[\t\0x0020]


Matching digits - The Digit sign [s]


The digits zero to nine can be matched using \d (backslash and
lowercase 'd'). For example, the following Regular Expression matches any three
digits in a row.

Text: 123 12 843 8472
Regex: \d\d\d
Matches: 123 12 843 8472
123
843
847

Matching sets of single characters - The Square-Brackets sign [( )]


The square brackets are used to specify a set of single characters to match.
Any single character within the set will match. For example, the following
Regular Expression matches any three characters where the first character is
either 'd' or 'a'.

Text: abc def ant cow
Regex: [da]..
Matches: abc def ant cow
abc
def
ant

The caret (^) can be added to the
start of the set of characters to specify that none of the characters in the
character set should be matched.
The following Regular Expression matches any
three character where the first character is not 'd' and not 'a'.


Text: abc def ant cow
Regex: [^da]..
Matches:
"bc "
"ef "
"nt "
"cow"

Matching ranges of characters - The Hyphen sign [-]


Ranges of characters can be matched using the hyphen (-). the
following Regular Expression matches any three characters where the second
character is either 'a', 'b', 'c' or 'd'.

Text: abc pen nda uml
Regex: .[a-d].
Matches: abc pen nda uml
abc
nda

Ranges of characters can also be combined together. the following Regular
Expression matches any of the characters from 'a' to 'z' or any digit from '0'
to '9' followed by two word characters.


Text: abc no 0aa i8i
Regex: [a-z0-9]\w\w
Matches: abc no 0aa i8i
abc
0aa
i8i

The pattern could be written more simply as [a-z\d]


Specifying the number of times to match with Quantifiers- The Plus and Star sign [+ and *]


Quantifiers let you specify the number of times that an expression must
match. The most frequently used quantifiers are the asterisk character
(*) and the plus sign (+). Note that the asterisk
(*) is usually called the star when talking about Regular
Expressions.


Matching zero or more times with star (*)


The star tells the Regular Expression to match the character, group, or
character class that immediately precedes it zero or more times. This
means that the character, group, or character class is optional, it can be
matched but it does not have to match. The following Regular Expression matches
the character 'a' followed by zero or more word characters.

Text: Anna Jones and a friend owned an anaconda
Regex: a\w*
Options: IgnoreCase
Matches: Anna Jones and a friend owned an anaconda
Anna
and
a
an
anaconda

Matching one or more times with plus (+)


The plus sign tells the Regular Expression to match the character, group, or
character class that immediately precedes it one or more times. This
means that the character, group, or character class must be found at least once.
After it is found once it will be matched again if it follows the first match.
The following Regular Expression matches the character 'a' followed by at least
one word character.

Text: Anna Jones and a friend owned an anaconda
Regex: a\w+
Options: IgnoreCase
Matches: Anna Jones and a friend owned an anaconda
Anna
and
an
anaconda

Note that "a" was not matched as it is not followed by any word characters.


Matching zero or one times with question mark (?)


To specify an optional match use the question mark (?). The
question mark matches zero or one times. The following Regular Expression
matches the character 'a' followed by 'n' then optionally followed by another
'n'.

Text: Anna Jones and a friend owned an anaconda
Regex: an?
Options: IgnoreCase
Matches: Anna Jones and a friend owned an anaconda
An
a
an
a
an
an
a
a

Specifying the number of matches


The minimum number of matches required for a character, group, or character
class can be specified with the curly brackets ({n}). The
following Regular Expression matches the character 'a' followed by a minimum of
two 'n' characters. There must be two 'n' characters for a match to occur.

Text: Anna Jones and Anne owned an anaconda
Regex: an{2}
Options: IgnoreCase
Matches: Anna Jones and Anne owned an anaconda
Ann
Ann

A range of matches can be specified by curly brackets with two numbers inside
({n,m}). The first number (n) is the minimum
number of matches required, the second (m) is the maximum number of matches
permitted. This Regular Expression matches the character 'a' followed by a
minimum of two 'n' characters and a maximum of three 'n' characters.

Text: Anna and Anne lunched with an anaconda annnnnex
Regex: an{2,3}
Options: IgnoreCase
Matches: Anna and Anne lunched with an anaconda annnnnex
Ann
Ann
annn

The Regex stops matching after the maximum number of matches has been
found.


Matching the start and end of a string


To specify that a match must occur at the beginning of a string use the caret
character (^). For example, I want a Regular Expression pattern to
match the beginning of the string followed by the character 'a'.

Text: an anaconda ate Anna Jones
Regex: ^a
Matches: an anaconda ate Anna Jones
"a" at position 1

The pattern above only matches the a in "an".


Note that the caret (^) has different behaviour when used inside
the square brackets.


If the Multiline option is on, the caret (^) will match
the beginning of each line in a multiline string rather than only the start of
the string.


To specify that a match must occur at the end of a string use the dollar
character ($). If the Multiline option is on then the pattern will
match at the end of each line in a multiline string. This Regular Expression
pattern matches the word at the end of the line in a multiline string.

Text: "an anaconda
ate Anna
Jones"
Regex: \w+$
Options: Multiline, IgnoreCase
Matches:
Jones

Finally, here is the Q. & Ans. for Kumar Abhishek

Q. How to write a regular expression to validate following domain name in ASP.NET Ver.1.1
wellatbell.whdev.com
Ans: <asp:regularexpressionvalidator runat="server" controltovalidate="txtDomainName" errormessage="Please enter a Domain in the correct format." validationexpression="^([0-9a-zA-Z])*\.([0-9a-zA-Z])*\.([a-zA-Z]{3})$" cssclass="clsForm" id="revDomainName">****</asp:regularexpressionvalidator>



Hope, the above reading will fulfill your needs. All the best.

Thursday, May 29, 2008

How to retrieve column names using datareader? - Part III

The following is the snapshot shhowing the output:

How to retrieve column names using datareader? - Part II

<!--

* The code snippet tells how to retrieve fields

* using datareader for, this is a part of :

* Book: C#2005 Beginners: A Step Ahead

* Written by: Gaurav Arora [gaurav.aroraose@yahoo.co.in]

-->

<%@ Page Language="C#" %>

<%@ Import Namespace="System.Web" %>

<%@ Import Namespace="System.Data" %>

<%@ Import Namespace="System.Data.SqlClient" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<script runat="server">



SqlConnection myCon = new SqlConnection("Server=localhost;database=HRnPAYROLL;trusted_Connection=true");

SqlCommand myCmd = null;

SqlDataReader myDr = null;

SqlDataAdapter myDa = null;

DataSet myDs = null;

String strOutPut = string.Empty;

protected void Page_Load(object sender, EventArgs e)

{

Getfields_DataReader();

Getfields_DataReader_SchemaOnly();

Getfields_DataSet();

}

/// <summary>

/// Retrieves all filed/column names of DataReader using GetName method without SchemaOnly

/// </summary>

protected void Getfields_DataReader()

{

myCmd = new SqlCommand("Select * from Employees", myCon);

myCon.Open();

myDr = myCmd.ExecuteReader();

//Store total number of Columns

Int32 totCol = myDr.FieldCount; //Fiedl count returns the number of total columns

Response.Write("<div class=\"upperColumn\">");

Response.Write("<h1>Retrieves All Field Names from DataReader using GetName Without SchemaOnly</h1>");


strOutPut = "<table border=\"1\"><tr> <td>Column Name</td> <td>Data Type</td></tr>";


for (Int32 intCol = 0; intCol < totCol; intCol++)

{

strOutPut += "<tr><td>" + myDr.GetName(intCol) + "</td>";

strOutPut += "<td>" + myDr.GetFieldType(intCol) + "</td></tr>";


}

strOutPut += "</table>";

//Write the output

Response.Write("<br/>" + strOutPut + "</Div> <br class=\"clear\" />");

myCon.Close();


}

/// <summary>

/// Retrieves all filed/column names of DataReader using SchemaOnly

/// </summary>

protected void Getfields_DataReader_SchemaOnly()

{

myCmd = new SqlCommand("Select * from HR_MAST_DEPT", myCon);

myCon.Open();

myDr = myCmd.ExecuteReader(CommandBehavior.SchemaOnly);

//Store total number of Columns

Int32 totCol = myDr.FieldCount; //Fiedl count returns the number of total columns

Response.Write("<div class=\"content\"> <div class=\"bottomColumn\">");

Response.Write("<h1>Retrieves All Field Names from DataReader using SchemaOnly</h1>");


strOutPut = "<table border=\"1\"><tr> <td>Column Name</td> <td>Data Type</td></tr>";


for (Int32 intCol = 0; intCol < totCol; intCol++)

{

strOutPut += "<tr><td>" + myDr.GetName(intCol) + "</td>";

strOutPut += "<td>" + myDr.GetFieldType(intCol) + "</td></tr>";


}

strOutPut += "</table>";

//Write the output

Response.Write("<br/> " + strOutPut + "</Div> </Div><br class=\"clear\" />");

myCon.Close();


}


/// <summary>

/// Retrieves all filed/column names of DataSet using ColumnName

/// </summary>

protected void Getfields_DataSet()

{


myDa = new SqlDataAdapter("Select * from Employees", myCon);

myDs = new DataSet();

myDa.Fill(myDs);

Response.Write("<div class=\"content\"> <div class=\"rightColumn\">");

Response.Write("<h1>Retrieves All Field Names from DataSet ColumnName</h1>");


strOutPut = "<table border=\"1\"><tr> <td>Column Name</td> <td>Data Type</td></tr>";


for (Int32 intCol = 0; intCol < myDs.Tables[0].Columns.Count; intCol++)

{

strOutPut += "<tr><td>" + myDs.Tables[0].Columns[intCol].ColumnName + "</td>";

strOutPut += "<td>" + myDs.Tables[0].Columns[intCol].DataType + "</td></tr>";


}

strOutPut += "</table>";

//Write the output

Response.Write("<br/> " + strOutPut + "</Div> </Div>");

}


</script>


<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<style type="text/css">

.content

{

margin:auto;

width:600px;

background-color:white;

border:Solid 2px orange;

}


html

{

background-color:gray;

font:14px Georgia,Serif,Garamond;

}


h1

{

color:Green;

font-size:18px;

border-bottom:Solid 1px orange;

}

.lbl

{

color:green;

font-weight:bold;

}


.upperColumn

{



margin:auto;

width:500px;

border:Solid 2px orange;

background-color:white;

padding:10px;

}

.bottomColumn

{



margin:auto;

width:700px;

border:Solid 2px orange;

background-color:white;

padding:10px;

}

.leftColumn

{ float:left;

width:300px;

height:150px;

border-right:Solid 1px gray;

background-color:white;

padding:5px;

}

.rightColumn

{ float:left;

height:150px;

border-left:Solid 1px gray;

padding:5px;

}

.clear

{

clear:both;

}

</style>

<title>How to retrieve all field names of datareader</title>

</head>

<body>

<form id="form1" runat="server">

</form>

</body>

</html>

How to retrieve column names using datareader? - Part I

Sometimes, we people when doing a higher things had lost some basics from memories, the sam happened with me.

Yesterday [May 28, 2008] my supervisor asked me a bit question - "How to retrieve column names using datareader?" I was junked that time and noticed that I have lost something from my memories of basics.
Today, I have sit back with my PC and workout the problem and write following Code snippet for VS2005:

We need a table to attain the above task, following query will solve the problem:

/* This query is created a HRnPAYROLL DATABASE
* for use of different examples shown in
* Book: C#2005 Beginners: A Step Ahead
* Written by: Gaurav Arora */

--First Create HRnPAYROLL DATABASE
Create Database HRnPAYROLL
go

Use HRnPAYROLL

--Create Employees Table and fill data

Create Table Employees
(
ID Varchar(4) Primary Key,
FirstName Varchar(25) Default 'Gaurav',
LastName Varchar(25) Default 'Arora',
Age Varchar(4) Default '19'
)
go

--*****************************************************************************************************************
Insert Into Employees Values ('0001','Anil','Jain','37');
Insert Into Employees Values ('0002','Aman','Jain','35');
Insert Into Employees Values ('0003','Amanpreet','Singh','28');
Insert Into Employees Values ('0004','Anuradha','Bhatia','24');
Insert Into Employees Values ('0005','Archana','Garg','25');
Insert Into Employees Values ('0111','Babita','Gupta','33');
Insert Into Employees Values ('0112','Babban','Das','24');
Insert Into Employees Values ('0113','Babu','Ram','24');
Insert Into Employees Values ('0114','Babbu','Man','38');
Insert Into Employees Values ('0115','Balbir','Singh','24');
Insert Into Employees Values ('0201','Chaman','Lal','38');
Insert Into Employees Values ('0202','Charan','Das','37');
Insert Into Employees Values ('0203','Chander Bhan','Singh','49');
Insert Into Employees Values ('0204','Changej','Khan','24');
Insert Into Employees Values ('0205','Champak','Lal','18');
Insert Into Employees (ID,FirstName,Age) Values ( '0160',' AMIT KUMAR','21')
Insert Into Employees (ID,FirstName,Age) Values ( '0180',' ABHISHEK MISHRA','24')
Insert Into Employees (ID,FirstName,Age) Values ( '0181',' ARUN KUMAR','23')
Insert Into Employees (ID,FirstName,Age) Values ( '0184',' ASHUTOSH BAJPAYEE','21')
Insert Into Employees (ID,FirstName,Age) Values ( '0185',' ANIL KUMAR YADAV','21')
Insert Into Employees (ID,FirstName,Age) Values ( '0188',' ASHOK KUMAR PATHAK','25')
Insert Into Employees (ID,FirstName,Age) Values ( '0190',' ABHISHEK KUMAR SINGH','23')
Insert Into Employees (ID,FirstName,Age) Values ( '0194',' AMIT KUMAR THAKUR','22')
Insert Into Employees (ID,FirstName,Age) Values ( '0549',' BRIJESH CHANDRA','21')
Insert Into Employees (ID,FirstName,Age) Values ( '0558',' BRAJESH KUMAR','27')
Insert Into Employees (ID,FirstName,Age) Values ( '0560',' B.K. SINGH','31')
Insert Into Employees (ID,FirstName,Age) Values ( '0562',' BALBIR SINGH [MANGAT]','35')
Insert Into Employees (ID,FirstName,Age) Values ( '1244',' DHARMESH PANWAR','27')
Insert Into Employees (ID,FirstName,Age) Values ( '1296',' DEEPAK PRASAD','26')
Insert Into Employees (ID,FirstName,Age) Values ( '1320',' DEEPAK JAIN','30')
Insert Into Employees (ID,FirstName,Age) Values ( '2004',' FAKHRE MUBEEN','21')
Insert Into Employees (ID,FirstName,Age) Values ( '2466',' GAURAV ARORA','19')
Insert Into Employees (ID,FirstName,Age) Values ( '2480',' GURDEEP SINGH','34')
Insert Into Employees (ID,FirstName,Age) Values ( '2481',' GOPAL DATT SATI','27')
Insert Into Employees (ID,FirstName,Age) Values ( '3210',' KAHLON I.J. SINGH','26')
Insert Into Employees (ID,FirstName,Age) Values ( '3211',' INDRESH KUMAR PANDEY','35')
Insert Into Employees (ID,FirstName,Age) Values ( '3641',' JAI PRAKASH','27')
Insert Into Employees (ID,FirstName,Age) Values ( '3683',' JAYCHANDRA','27')
Insert Into Employees (ID,FirstName,Age) Values ( '3698',' J.K. SINGH','23')
Insert Into Employees (ID,FirstName,Age) Values ( '3700',' JEET NARAYAN SINGH','29')
Insert Into Employees (ID,FirstName,Age) Values ( '3701',' JIVENDRA KUMAR','29')
Insert Into Employees (ID,FirstName,Age) Values ( '4009',' KAPOOR SINGH','30')
Insert Into Employees (ID,FirstName,Age) Values ( '4057',' KISHAN LAMA','21')
Insert Into Employees (ID,FirstName,Age) Values ( '4110',' KRISHAN KUMAR MISHRA','33')
Insert Into Employees (ID,FirstName,Age) Values ( '4112',' K.B. CHOUBEY','33')
Insert Into Employees (ID,FirstName,Age) Values ( '4113',' KAISH UDDIN','35')
Insert Into Employees (ID,FirstName,Age) Values ( '4455',' LOKNATH BALBANTARAY','34')
Insert Into Employees (ID,FirstName,Age) Values ( '4801',' M.K. DEBROY','30')
Insert Into Employees (ID,FirstName,Age) Values ( '4884',' MADAN GIRI','21')
Insert Into Employees (ID,FirstName,Age) Values ( '4936',' MANJISH KUMAR','34')
Insert Into Employees (ID,FirstName,Age) Values ( '4946',' MADAN SINGH','24')
Insert Into Employees (ID,FirstName,Age) Values ( '4949',' MANOJ KUMAR TIWARI','21')
Insert Into Employees (ID,FirstName,Age) Values ( '4978',' MUKHTAR AHMED','18')
Insert Into Employees (ID,FirstName,Age) Values ( '4985',' MANOJ SAXENA','31')
Insert Into Employees (ID,FirstName,Age) Values ( '4987',' MANISH MISHRA','31')
Insert Into Employees (ID,FirstName,Age) Values ( '5263',' NEERAJ MAHAWAR','33')
Insert Into Employees (ID,FirstName,Age) Values ( '5271',' NIRAJ KUMAR SINHA','19')
Insert Into Employees (ID,FirstName,Age) Values ( '5272',' N.K. SINGH','21')
Insert Into Employees (ID,FirstName,Age) Values ( '5274',' NITIN GUPTA','32')
Insert Into Employees (ID,FirstName,Age) Values ( '5275',' NARESH KUMAR GUPTA','23')
Insert Into Employees (ID,FirstName,Age) Values ( '5612',' O.P. YADAV','32')
Insert Into Employees (ID,FirstName,Age) Values ( '6135',' PRAMOD SINGH RAWAT','30')
Insert Into Employees (ID,FirstName,Age) Values ( '6136',' PRAMOD KUMAR GAUTAM','22')
Insert Into Employees (ID,FirstName,Age) Values ( '6137',' PRAMOD KUMAR SINHA','31')
Insert Into Employees (ID,FirstName,Age) Values ( '6138',' PRASAD SASNUR','20')
Insert Into Employees (ID,FirstName,Age) Values ( '6700',' R. BHATTACHARJEE','21')
Insert Into Employees (ID,FirstName,Age) Values ( '6753',' RAMA SHANKAR','20')
Insert Into Employees (ID,FirstName,Age) Values ( '6765',' RAMESH CHANDRA','27')
Insert Into Employees (ID,FirstName,Age) Values ( '6776',' RAMU YADAV','20')
Insert Into Employees (ID,FirstName,Age) Values ( '6899',' RAVINDER LAMBA','29')
Insert Into Employees (ID,FirstName,Age) Values ( '6925',' RAVINDRA KUMAR RANA','24')
Insert Into Employees (ID,FirstName,Age) Values ( '6996',' R.P. YADAV','28')
Insert Into Employees (ID,FirstName,Age) Values ( '7010',' RAJESH PUNDIR','33')
Insert Into Employees (ID,FirstName,Age) Values ( '7011',' RAJIV CHAUDHARY','32')
Insert Into Employees (ID,FirstName,Age) Values ( '7012',' RAVINDRA YADAV','23')
Insert Into Employees (ID,FirstName,Age) Values ( '7013',' RAJESH SHARMA','32')
Insert Into Employees (ID,FirstName,Age) Values ( '7016',' RAVI SHANKAR','19')
Insert Into Employees (ID,FirstName,Age) Values ( '7017',' RAM BILAS CHOUDHARY','23')
Insert Into Employees (ID,FirstName,Age) Values ( '7022',' RAJ KISHORE RAI','24')
Insert Into Employees (ID,FirstName,Age) Values ( '7023',' R. RAMESH','35')
Insert Into Employees (ID,FirstName,Age) Values ( '7123',' SATISH KUMAR','32')
Insert Into Employees (ID,FirstName,Age) Values ( '7296',' SHANKAR LAL','29')
Insert Into Employees (ID,FirstName,Age) Values ( '7471',' SANJEEVAN M.K.','30')
Insert Into Employees (ID,FirstName,Age) Values ( '7480',' SANDEEP KR. SHRIVASTA','34')
Insert Into Employees (ID,FirstName,Age) Values ( '7484',' SUBHARAM BANERJEE','25')
Insert Into Employees (ID,FirstName,Age) Values ( '7490',' S.M. TRIPATHI','31')
Insert Into Employees (ID,FirstName,Age) Values ( '7501',' TEK BAHADUR CHATTRI','23')
Insert Into Employees (ID,FirstName,Age) Values ( '7513',' TULSI PRASAD','30')
Insert Into Employees (ID,FirstName,Age) Values ( '7919',' UMESH CHANDRA MISHRA','19')
Insert Into Employees (ID,FirstName,Age) Values ( '8480',' VIVEK TRIPATHI','31')
Insert Into Employees (ID,FirstName,Age) Values ( '8481',' VIJAY KUMAR','22')
Insert Into Employees (ID,FirstName,Age) Values ( '8485',' VIJAY KUMAR MISHRA','20')
Insert Into Employees (ID,FirstName,Age) Values ( '8486',' VINEET KUMAR SAXENA','35')
Insert Into Employees (ID,FirstName,LastName,Age) Values ( 'J001',' ANURAG', 'MISHRA','21')
Insert Into Employees (ID,FirstName,LastName,Age) Values ( 'J002',' ANURAG', ' DWIVEDI','24')
Insert Into Employees (ID,FirstName,LastName,Age) Values ( 'J006',' A.B.', ' KATIYAR','23')
Insert Into Employees (ID,FirstName,LastName,Age) Values ( 'J007',' AJAY', ' NAGAR','21')
Insert Into Employees (ID,FirstName,LastName,Age) Values ( 'J009',' AMIT KUMAR', ' SINGH','21')
Insert Into Employees (ID,FirstName,LastName,Age) Values ( 'J011',' AKHILESH KUMAR', ' VERMA','25')
Insert Into Employees (ID,FirstName,LastName,Age) Values ( 'J012',' ASHUTOSH', ' SRIVASTVA','23')
Insert Into Employees (ID,FirstName,LastName,Age) Values ( 'J013',' AKHILESH', ' BABU','22')
Insert Into Employees (ID,FirstName,LastName,Age) Values ( 'J018',' ASHOK KUMAR', ' PAL','21')
Insert Into Employees (ID,FirstName,LastName,Age) Values ( 'J019',' ANIL KUMAR', ' SINGH','27')
Insert Into Employees (ID,FirstName,LastName,Age) Values ( 'J023',' AMRISH', ' SHARMA','31')
Insert Into Employees (ID,FirstName,LastName,Age) Values ( 'J151',' CHANDRA PRATAP', ' SINGH','35')
Insert Into Employees (ID,FirstName,LastName,Age) Values ( 'J152',' C.P.', ' MISHRA','27')
Insert Into Employees (ID,FirstName,LastName,Age) Values ( 'J201',' DILIP', ' NAYAK','26')
Insert Into Employees (ID,FirstName,LastName,Age) Values ( 'J204',' DHEERAJ KUMAR', ' SACHAN','30')
Insert Into Employees (ID,FirstName,LastName,Age) Values ( 'J205',' DEVBRAT', ' SINGH','21')
Insert Into Employees (ID,FirstName,LastName,Age) Values ( 'J209',' DINESH', ' MISHRA','19')
Insert Into Employees (ID,FirstName,LastName,Age) Values ( 'J210',' DHARMENDRA KR.', ' PANDEY','34')
Insert Into Employees (ID,FirstName,LastName,Age) Values ( 'J316',' HEMANT', ' KUMAR','27')
Insert Into Employees (ID,FirstName,LastName,Age) Values ( 'J350',' JAGDISH', ' AWASTHI','26')
Insert Into Employees (ID,FirstName,LastName,Age) Values ( 'J366',' K.K.', ' KHULAR','35')
Insert Into Employees (ID,FirstName,LastName,Age) Values ( 'J371',' KAVIRAJ',' ','27')
Insert Into Employees (ID,FirstName,LastName,Age) Values ( 'J372',' KRISHNA KANT', ' SINGH','27')
Insert Into Employees (ID,FirstName,LastName,Age) Values ( 'J383',' LIBREN STENLY', ' LUGEN','23')
Insert Into Employees (ID,FirstName,LastName,Age) Values ( 'J384',' LING RAJ', ' SAHU','29')
Insert Into Employees (ID,FirstName,LastName,Age) Values ( 'J396',' MAHENDRA', ' PRAJAPATI','29')
Insert Into Employees (ID,FirstName,LastName,Age) Values ( 'J400',' MANJEET SINGH', ' REHSHI','30')
Insert Into Employees (ID,FirstName,LastName,Age) Values ( 'J403',' MAHENDRA', ' KHARAD','21')
Insert Into Employees (ID,FirstName,LastName,Age) Values ( 'J405',' MANPREET SINGH', ' JABBAL','33')
Insert Into Employees (ID,FirstName,LastName,Age) Values ( 'J411',' NEERAJ', ' TIWARI','33')
Insert Into Employees (ID,FirstName,LastName,Age) Values ( 'J416',' NARENDRA PRATAP', ' SINGH','35')
Insert Into Employees (ID,FirstName,LastName,Age) Values ( 'J417',' NARAYAN', ' SINGH','34')
Insert Into Employees (ID,FirstName,LastName,Age) Values ( 'J443',' PRAMOD KUMAR', ' SHARMA','30')
Insert Into Employees (ID,FirstName,LastName,Age) Values ( 'J444',' PRAFUL CHANDRA', ' RAI','21')
Insert Into Employees (ID,FirstName,LastName,Age) Values ( 'J445',' PRAKASH', ' SHARMA','34')
Insert Into Employees (ID,FirstName,LastName,Age) Values ( 'J447',' PRAVEEN KUMAR', ' DUBEY','24')
Insert Into Employees (ID,FirstName,LastName,Age) Values ( 'J448',' PRADEEP', ' KUMAR','21')
Insert Into Employees (ID,FirstName,LastName,Age) Values ( 'J450',' PRADEEP KR.', ' DWIVEDI','18')
Insert Into Employees (ID,FirstName,LastName,Age) Values ( 'J451',' PARTHA', ' CHOUDHARY','31')
Insert Into Employees (ID,FirstName,LastName,Age) Values ( 'J501',' RAM BABU', '','31')
Insert Into Employees (ID,FirstName,LastName,Age) Values ( 'J502',' RAJEEV', ' SHAHANI','33')
Insert Into Employees (ID,FirstName,LastName,Age) Values ( 'J508',' RAJEEV', ' LOCHAN','19')
Insert Into Employees (ID,FirstName,LastName,Age) Values ( 'J510',' RAJIV', ' KUMAR','21')
Insert Into Employees (ID,FirstName,LastName,Age) Values ( 'J551',' SANJAY', ' SINGH','32')
Insert Into Employees (ID,FirstName,LastName,Age) Values ( 'J554',' SUBODH', ' TIWARI','23')
Insert Into Employees (ID,FirstName,LastName,Age) Values ( 'J556',' SHIV SHANKAR', ' GOSWAMI','32')
Insert Into Employees (ID,FirstName,LastName,Age) Values ( 'J559',' SANJAY', ' TOMAR','30')
Insert Into Employees (ID,FirstName,LastName,Age) Values ( 'J562',' SURENDER', ' PAL SINGH','22')
Insert Into Employees (ID,FirstName,LastName,Age) Values ( 'J563',' SANDEEP', ' KUMAR','31')
Insert Into Employees (ID,FirstName,LastName,Age) Values ( 'J651',' T.', 'RAMESH','20')
Insert Into Employees (ID,FirstName,LastName,Age) Values ( 'J701',' UDAY RAJ', ' SINGH','20')

--*****************************************************************************************************************
-- Create HR_MAST_DEPT Table

CREATE TABLE HR_MAST_DEPT
(
[code] [char] (2) Primary Key ,
[Dpname] [varchar] (25) NOT NULL ,
[city] [varchar] (25),
[country] [varchar] (50),
[inhouse] [bit],

)
gO

-- Fill HR_MAST_DEPT Table

Insert Into HR_MAST_DEPT Values ( '10' , 'Information Technology' , 'Delhi' , 'India' , '1' )
Insert Into HR_MAST_DEPT Values ( '20' , 'Human Resources Dept' , 'Mohali' , 'India' , '1' )
Insert Into HR_MAST_DEPT Values ( '30' , 'Marketing' , 'Toronto' , 'Canada' , '0' )
Insert Into HR_MAST_DEPT Values ( '40' , 'Civil' , 'Calgiri' , 'Canada' , '0' )
Insert Into HR_MAST_DEPT Values ( '50' , 'Sales' , 'Gurgaon' , 'India' , '1' )
Insert Into HR_MAST_DEPT Values ( '60' , 'Commercial' , 'Delhi' , 'India' , '1' )
Insert Into HR_MAST_DEPT Values ( '70' , 'Admin' , 'Noida' , 'India' , '1' )
Insert Into HR_MAST_DEPT Values ( '80' , 'Testing' , 'Gurgaon' , 'India' , '1' )
Insert Into HR_MAST_DEPT Values ( '90' , 'Implementing' , 'Delhi' , 'India' , '1' )

--*****************************************************************************************************************

Saturday, May 10, 2008

Just-in-Time [JIT]

JIT compiler is a crucial component of the .NET framework. The JIT compiler converts IL to machine code, which is then executed. The JIT compiler does not compile the entire code at once because it could hamper the performance of the program. It compiles the code at runtime, at the time it is called. The code that is compiled gets stored until the execution comes to an end. This avoids recompilation of code.

Types of JIT
There following three types of JIT:
Pre-JIT
It compiles whole source code into native code in a single compilation cycle. This is done at the time of deployment of the application
Econo-JIT
It compiles only those methods that are called at runtime. However, these methods are removed when they are not required.
Normal-JIT
It also compiles only those methods which are called at runtime. These methods are compiled the first time they are called, and then they are stored in cache. When the same methods are called again, the compiled code from cache is used for execution

Common Language Runtime [CLR]

Let's rewind our mind to ancient era, when there is no existence of CLR concept, what happened when we invoke the language program or code. Basically, languages consist both compiler and runtime environment. Compiler converts or compiles code to executable files [known as PE (Portable file) files], which can be run by the users, in the other hand runtime environment provides O.S. [Operating System] services to executable code. Now at that time each language has its own runtime environment. Like Visual Basic contained MSVBVM60.DLL, Visual C++ contained MSVCRT40.DLL and for Java we need JRE [Java Runtime Environment] or JVM [Java Virtual machine].
But, with the invention of Common Language Runtime there is no need to gather individual runtime environment for individual languages, that's why .Net runtime is known as Common Language Runtime [CLR] Environment.

.NET framework

.NET framework is a Tool, which provides an environment for building, deploying and running web services and other application.

It also predicts from above figure that .NET framework [see fig11] consists of CLR and a single of unit of complete set of Class Libraries, provides the scarcity to develop Windows applications and Web Application with the help of .NET programming languages.

According to .NET documentation of Microsoft:
The .NET Framework is a new computing platform that simplifies application development in the highly distributed environment of the Internet. The .NET Framework is designed to fulfill the following objectives:

  1. To provide a consistent object-oriented programming environment whether object code is stored and executed locally, executed locally but Internet-distributed, or executed remotely.

  2. To provide a code-execution environment that minimizes software deployment and versioning conflicts.

  3. To provide a code-execution environment that guarantees safe execution of code, including code created by an unknown or semi-trusted third party.
    To provide a code-execution environment that eliminates the performance problems of scripted or interpreted environments.

  4. To make the developer experience consistent across widely varying types of applications, such as Windows-based applications and Web-based applications.

  5. To build all communication on industry standards to ensure that code based on the .NET Framework can integrate with any other code.

Tuesday, March 25, 2008

Working with Stored procedures

Stored procedure helps to make your work easy. With the help of these you just have to supply some parameters only.

The Code snippet using storedprocedures describes a way to use stored procedures.

Working with Transactions

Whenever you have to update more than one table or destinations then it must have to sure that the operation done successfully because some time it has been seen that one table updated but due to some error another(s) not. To overcome this problem you have Transactions.

In ADO.Net transactions are initiated by calling BeginTransaction() methods on the database connection object.

Transaction isolation levels


Isolation Level(s)

Description

ReadCommitted

Its default for SQL Server. It ensures that data written by one transaction will only be accessible in a second transaction after the first transaction commits.

ReadUnCommitted

It permits transaction to read data within the database, even data that have not yet been committed by another transaction.

RepeatableRead

It extends the ReadCommitted level, ensures that if the same statement issued within the transaction, regardless of other potential updates made to the database, the same data will always be returned.

Serializable

It is the most exclusive transaction level, which in effect serializes access to data within the database. With this level, phantom rows can never show up, so a SQ statement issued within a serializable transaction will always retrieve the same data.

Bellow is the code snippet to show transaction in action:

string myConStr = "server=(local); integrated security=SSPI;database=HRnPAYROLL";

using (SqlConnection myCon = new SqlConnection(myConStr))
{
//Open connection object
myCon.Open();
SqlTransaction nTran = myCon.BeginTransaction();
//some code for work
nTran.Commit();
}

Monday, March 24, 2008

Testing a Private Assembly

Lets start to create a client application for privateassembly, Open a notepad and write following code [till now you have not created any client application using visual studio, you will do the same very soon in ASP.Net section]. For this example lets create a client application using Console application from templates pane [windows applications are beyond the scope of the book].

  • In Solution explorer change the class name from Program to mathClassClient
  • Using private assembly.

  • Add CSharp.AStepAhead.privateAssembly namespace
  • Now, important step is to add assembly reference, right click on the project
    in solution explorer and click on the Add Reference
    [you can choose the
    same from Project menu]

  • Adding Assembly Reference

  • Create an object of mathClass Class
  • Build the project or press F5
  • Important Important:Version information of an assembly is stored in its MANIFEST
    : Concept of Versioning is applicable only to GAC [Global Assembly Cache], because
    private assemblies are lying in their individual folders.

  • Output of Client application :
  • Output:Client Application
    Important Important:
    1. Revise source of above project [privateAssembly project] to
    understand the code. In this project, you saw that there is nothing extraordinary
    operations, just accepting integer values and on the behalf of these values result
    will retaining by overriding ToString() method. Yes, you can override this virtual
    method as per your requirement, as done in this example.
    2. Now, in Client application, this is a Console Based application
    project, as you are going for Asp.Net so, Windows applications are beyond the
    scope of the book
    .

Creating a Private Assembly

In Visual Studio .NET there is always an assembly whether you choose a class library
project or an exe project. Now, let's start some practical work.

  • Start Visual Studio 2005

  • Choose a new C# project [File -> New Project]

  • Choosing new C#:project
  • From template pane choose Class Library Template

  • Set the Location : F:\myWrittings\CSharpBook\Source Codes\

  • Name : privateAssembly

  • Check full code of private
    assembly
    .

  • In Solution explorer change class name from Class1 to mathclass

  • Now right click on mathclass and click on view code

  • Change the name of namespace from privateAssembly to CSharp.AStepAhead.privateAssemby

  • After writing codes of the assembly, now you have to provide some information to
    your assembly as follows:

using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; // General Information about an assembly is
controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("privateAssembly")]
[assembly: AssemblyDescription("This is an Example of Book: C#-A Step Ahead
Series")]
[assembly: AssemblyConfiguration("Free I.T. Education Series - A Step Ahead")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("A Step Ahead Series")]
[assembly: AssemblyCopyright("Copyright © A Step Ahead 2007")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("d5389a36-3aa1-4e22-b3df-4cacd5e96531")]

  • For above, you have to click on AssemblyInfo.cs under properties from Solution Explorer
  • The above information tells about the assembly name, title its short description
    and company who had developed it.
  • For more detail check table assembly attributes.
  • Write codes to provide the working for client application.
  • Now build solution from Build -> Build Solution or Ctrl + Shift + B
  • If build succeeded, it means you have created an assembly
  • You can check the assembly using ILDASM

  • How to view an Assembly

    To view the assembly means to view the IL code, ILDASM converts the whole exe or
    dll into IL Code. To start the same:


    • Go to C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin and then double click
      on ildasm.exe

    • Open SDK command prompt and type ildasm


    • Invoking ILDASM


    • Now in ildasm open assembly File -> Open [or ctrl+O]



    • Opening ILDASM


    • Double click on the MANIFEST



    • Viewing Assembly MANIFEST


    • If you want to view mathclass, just double click on it



    • Viewing Class


    • For further information about the methods just do the same as you did in above case


    • Viewing Method





    What is MANIFEST


    This is a very important part of an assembly. It describes the full information
    of an assembly, so, in general words it contains metadata of an assembly. Manifest
    is a container of metadata of an assembly, which contains the followings:



    • Name, version info, culture info etc.

    • Identity of security

    • Scope of assembly

    • Resolve references to resources and classes.