Friday, February 29, 2008

ASP.Net DataList HyperLink Template

Having seen the basics of DataList in http://shalvinpd.blogspot.com/2008/02/aspnet-datalist.html, lets take up a bit more complex DataList application.


We are going to implement a multiform one to many application similar to what you see in Ecommerce application. In the first page there might be a list of categories. All Categories will be appearing as hyperlinks. On clicking a Category you will taken to the the child page say SubCategory.





So we have to produce hyperlink templates. I am not going into the details of database connectivity and the like (You can refer http://shalvinpd.blogspot.com/2008/02/aspnet-datalist.html for basics of DataList) instead I am straight a way jumping into DataList ItemTemplate.




//Default.aspx








Here we are specifying an html anchor tag as passing the CatId as Query String to the next page.
In the second page we can extract the QueryString value pass it into the select statements where clause and display the result.


<Columns>
    <asp:TemplateField>
                <ItemTemplate>
                       
                    <a href = '<%#  String.Format("Cat.aspx?CatId={0}", Eval("CategoryId")) %>'>
                        <%# Eval("CategoryName") %>
                    </a>
                </ItemTemplate>
            </asp:TemplateField>
</Columns>


GridView is also having the equivalent functionality.



create procedure spGetSubCats(@pCatId int)
as
select * from SubCategory where CatId = @pCatId
go




//SubCata.aspx.cs


using System.Data.SqlClient;
public partial class SubCat : System.Web.UI.Page
{
SqlConnection cnn;
SqlDataAdapter da;
DataSet ds = new DataSet();
protected void Page_Load(object sender, EventArgs e)
{
cnn = new SqlConnection(ConfigurationManager.AppSettings.Get("Cnn"));
cnn.Open();
da = new SqlDataAdapter("spGetSubCats " + Convert.ToInt32(Request.QueryString["CatId"]), cnn);
da.Fill(ds, "SubCat");
dlstSubCat.DataSource = ds.Tables["SubCat"];
DataBind();
}
}

//SubCat.aspx









Happy Programming
shalvinpd.blogspot.com

Thursday, February 28, 2008

Asp.Net 2.0 Master Page and TreeView

Lets continue out discussion on Master Page. In this blow we will take up TreeView also which can be used for having a consistent navigation option.

It is possible to work with TreeView by going to properties window but in this blog we are going to take up working with Site Map.

Start a new asp.net project. Delete the Default.aspx page.

Add a Site map by going to Web Site Menu option.

Web.sitemap is an xml file.












Add a Master Page.

This time I am making the master page a bit complex as shown in the exhibit.













Click on the smart tag of tree view and go to choose data source and select new data source as show in the figure.













Select Sitemap and click ok.

Now add Default.aspx, Categories.aspx and Products.aspx also make sure you check Select Master Page as discussed in the previous blog http://shalvinpd.blogspot.com/2008/02/aspnet-master-page-for-consistant-look.html

Now you have a consistence look and feel and well as navigation option for your site.

Happy Programming
shalvin@gmail.com

ASP.Net Master Page for Consistant look and feel for websites

In this blog we will take up the Master page.
Start a new Asp.Net 2.0 project.
Go to solution explorer and delete Default.aspx. Go to Web Site menu select Master Page.
Master page resembles an ordinary asp.net web page except that it contains a content place holder.

Go to the design view.





















































In the case of my master page I am going to give a consitent header and footer. So keeping the content place holder intact I added the header and footer.





Now add a new Asp.Net page. There will be an option called select maste page. Check that option and click Add.









































The Select Master Page dialog will appear as shown in the exibit.




















Select the master page and Click OK.

You will get the page as shown in the exibit. You can type the page specific data inside the content place holder.






Like wise you can add rest of the Asp.Net pages and select the master page for consistent look and feel.


Related Blogs

Asp.Net 2.0 Master Page and TreeView
Themes in Asp .Net
shalvinpd.blogspot.com

Tuesday, February 26, 2008

Regular Expression and .Net Regex.IsMatch()

Regular Expression is a set of characters that can be compared to a string to determine whether a string meets a specified format required.

Let's analyse the Regular expression characters

() Group or subexpression
? Zero of one occurence of previous character or subexpression
Eg : Eg: a? : Zero or one occurence of a

* Zero or more one occurence of previous character or subexpression
Eg : a* : Zero or more occurence of a. That is it can evaluate to no value, a, aa, aaa, etc.

+ One or more occurence of previous character or subexpression
Eg : a+ one ore more occurence of a (shalvin)+ one or more occurence of shalvin

| Either of the character of subexpression.

[123] Matches any one of the enclosing characters.
[a-c] Any character in the specified range

\d Matches a digit
\w Matches any word character

Regular Expressions in .Net Windows Forms

Having seen the basics of Regular Expression let see how to use it for input validation in Windows Forms Application.

using System.Text.RegularExpressions;
private void txtAQues_Validating(object sender, CancelEventArgs e)
{
if (!Regex.IsMatch(txtAQues.Text, "^a?$"))
errorProvider1.SetError(txtAQues, "Only zero or one occurence of a is allowed");
else
errorProvider1.SetError(txtAQues , "");
}

private void txtShalvinQues_Validating(object sender, CancelEventArgs e)
{
if (!Regex.IsMatch(txtShalvinQues.Text, "^(Shalvin)?$"))
errorProvider1.SetError(txtShalvinQues, "Only zero of one occurence of Shalvin is allowed");
else
errorProvider1.SetError(txtShalvinQues , "");
}


Regular Expression Examples

Checking for valid email id.
[A-Z0-9._]+@[A-Z0-9.-+\.[A-Z]{2,4}

Monday, February 25, 2008

Asp.Net DataList Part I

DataList is a templated control. You specify how to display the items, alternating items, Header, Footer etc. using , etc.

First let's see how to a simple DataList Example:
Instead of hard coding the connection string information I am using the section of web.config to specify the connection string information.

//web.config




















using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
SqlConnection cnn;
SqlDataAdapter da;
DataSet ds = new DataSet();
protected void Page_Load(object sender, EventArgs e)
{
cnn = new SqlConnection(ConfigurationManager.AppSettings.Get("Cnn"));
da = new SqlDataAdapter("select * from Categories", cnn);
da.Fill(ds, "Cat");
DataList1.DataSource = ds.Tables["Cat"];
DataBind();
}
}

























































Creating a custom table with DataList































Output

















DataList HyperLink Template - Asp.Net DataList - II

Happy Programming
shalvin@gmail.com

Saturday, February 23, 2008

ADO in VB.Net

The beauty of Microsoft technology lies in interoperability. Instead of considering COM, .Net Windows Forms and WPF as seperate technologies I consider it as technologies of same family with excellent interoperatbility.
This blog takes up the issue of working with COM Ado. in .Net.


First of all set a refence to COM Ado by going to Project, Add Reference.







Option Strict Off
Friend Class Form1
Inherits System.Windows.Forms.Form
Dim cnn As ADODB.Connection
Dim rs As ADODB.Recordset
Private Sub cmdNext_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdNext.Click
rs.MoveNext()
FillData()
End Sub

Private Sub cmdPrvious_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdPrvious.Click
rs.MovePrevious()
FillData()
End Sub

Private Sub Form1_Load(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles MyBase.Load
cnn = New ADODB.Connection
cnn.Open("Integrated Security=sspi;Initial Catalog=Northwind;Provider=sqloledb.1")
rs = New ADODB.Recordset
rs.Open("select * from Categories", cnn, ADODB.CursorTypeEnum.adOpenDynamic, ADODB.LockTypeEnum.adLockOptimistic)
FillData()
End Sub

Private Sub FillData()
txtCategoryName.Text = rs.Fields("CategoryName").Value
txtDescription.Text = rs.Fields("Description").Value
End Sub
End Class

Related article

Using COM Controls in .Net

Thursday, February 21, 2008

.Net Intermediate Language

.Net Intermediate Language or IL is simple, object oriented, stack based assembly language of .Net.
All .Net languages gets converted to IL on compilation.

IL is case sensitive and and follows the same case pattern that of C#, ie. initial capital Eg. System.Console.WriteLine where S C W and L and capitalized respectively.

This blog assumes that you are familiar with C# if not please refer my blog Exploring C# Language : The Console Way.

IL statements can be broadly classified into two IL directives and IL instructions. Any statement that starts with . is an IL directive examples are .assembly, .module, etc. and others are IL instructions.

Namespaces ares specified inside square brackets.

Hello World

.assembly '1Hello'{}

.method void Main()
{
.entrypoint
ldstr "Hello World" call void [mscorlib] System.Console::WriteLine(string)
ret
}



For creating an assembly out of the IL we can use ilasm (Intermediate Language assembler).















Memory Variable Console::ReadLine and String::Concat methods


In IL all local variables are defined inside .locals directive. One nice thing about IL generated by .Net compilers are the variable names are mangled. Here it creates a string memory variable.

.assembly '2MemVar'{}

.method void Main()
{
.entrypoint

.locals init (string V_0)
ldstr "Enter your name : " call void [mscorlib]System.Console::WriteLine (string)
call string [mscorlib]System.Console::ReadLine()
stloc.0
ldstr "Hello "
ldloc.0
call string [mscorlib]System.String::Concat (string, string)
call void [mscorlib]System.Console::WriteLine(string)
ret
}


Integer Memory Variable and add

.assembly '4Add'{}

.method public hidebysig static void Main() cil managed
{
.entrypoint

.locals init (int32 V_0, int32 V_1, int32 V_2)

ldstr "Enter first integer :"
call void [mscorlib]System.Console::WriteLine(string)

call string [mscorlib]System.Console::ReadLine()
call int32

[mscorlib]System.Int32::Parse(string)
stloc.0
ldstr "Enter second integer :"
call void [mscorlib]System.Console::WriteLine(string)

call string [mscorlib]System.Console::ReadLine()
call int32 [mscorlib]System.Int32::Parse(string)
stloc.1
ldloc.0
ldloc.1
add
stloc.2
ldloca.s V_2
call instance string [mscorlib]System.Int32::ToString()
call void [mscorlib]System.Console::WriteLine(string)
ret
}



Form
.assembly extern System.Windows.Forms
{
.publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) .ver 2:0:0:0 }
.assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) .ver 2:0:0:0
}
.assembly '4Form' { }
.module '4Form.exe'
.class private auto ansi beforefieldinit frmHello extends [System.Windows.Forms] System.Windows.Forms.Form
{
.method public hidebysig static void Main() cil managed
{
.entrypoint newobj instance void frmHello::.ctor() call void [System.Windows.Forms] System.Windows.Forms.Application::Run(class [System.Windows.Forms]System.Windows.Forms.Form)
ret
}
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed
{
ldarg.0 call instance void [System.Windows.Forms] System.Windows.Forms.Form::.ctor()
ret
}
}

Button and Form Text Property
.assembly extern System.Windows.Forms {
.publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) .ver 2:0:0:0 }
.assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) .ver 2:0:0:0 } .assembly '5Button' { }
.module '5Button.exe'
.class private auto ansi beforefieldinit frmHello extends [System.Windows.Forms]System.Windows.Forms.Form
{
.field private class [System.Windows.Forms]System.Windows.Forms.Button btnHello
.method public hidebysig static void Main() cil managed
{
.entrypoint newobj instance void frmHello::.ctor()
call void [System.Windows.Forms]System.Windows.Forms.Application::Run(class [System.Windows.Forms]System.Windows.Forms.Form)
ret
}
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed
{
ldarg.0 call instance void [System.Windows.Forms]System.Windows.Forms.Form::.ctor() ldarg.0
ldstr "Shalvin"
callvirt instance void [System.Windows.Forms]System.Windows.Forms.Control::set_Text(string)
ldarg.0 newobj instance void [System.Windows.Forms]System.Windows.Forms.Button::.ctor() stfld class [System.Windows.Forms]System.Windows.Forms.Button frmHello::btnHello
ldarg.0 ldfld class [System.Windows.Forms]System.Windows.Forms.Button frmHello::btnHello ldstr "Hello"callvirt instance void [System.Windows.Forms]System.Windows.Forms.Control::set_Text(string)
ldarg.0
call instance class [System.Windows.Forms]System.Windows.Forms.Control/ControlCollection [System.Windows.Forms]System.Windows.Forms.Control::get_Controls() ldarg.0 ldfld class [System.Windows.Forms]System.Windows.Forms.Button frmHello::btnHello callvirt instance void [System.Windows.Forms]System.Windows.Forms.Control/ControlCollection::Add(class [System.Windows.Forms]System.Windows.Forms.Control)
ret
}
}

Event Handling
.assembly extern System.Windows.Forms
{ .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) .ver 2:0:0:0 }
.assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) .ver 2:0:0:0 } .assembly extern System.Drawing {
.publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ).ver 2:0:0:0 }.assembly '6Click' { } .module '6Click.exe' .class private auto ansi beforefieldinit frmHello extends [System.Windows.Forms]System.Windows.Forms.Form {
.field private class [System.Windows.Forms]System.Windows.Forms.Button btnHello .method public hidebysig static void Main() cil managed
{
.entrypoint newobj instance void frmHello::.ctor() call void [System.Windows.Forms]System.Windows.Forms.Application::Run(class [System.Windows.Forms]System.Windows.Forms.Form)
ret
}
.method public hidebysig specialname rtspecialname instance void
.ctor() cil managed
{
ldarg.0 call instance void [System.Windows.Forms]System.Windows.Forms.Form::.ctor() ldarg.0ldstr "Shalvin" callvirt instance void [System.Windows.Forms]System.Windows.Forms.Control::set_Text(string)
ldarg.0 newobj instance void [System.Windows.Forms]System.Windows.Forms.Button::.ctor() stfld class [System.Windows.Forms]System.Windows.Forms.Button frmHello::btnHello ldarg.0 ldfld class [System.Windows.Forms]System.Windows.Forms.Button frmHello::btnHello ldc.i4.s 50 ldc.i4.s 50 newobj instance void [System.Drawing]System.Drawing.Point::.ctor(int32, int32) callvirt instance void [System.Windows.Forms]System.Windows.Forms.Control::set_Location(valuetype [System.Drawing]System.Drawing.Point)
ldarg.0 ldfld class [System.Windows.Forms]System.Windows.Forms.Button frmHello::btnHelloldarg.0
ldftn instance void frmHello::btnHello_Click(object, class [mscorlib]System.EventArgs) newobj instance void [mscorlib]System.EventHandler::.ctor(object, native int)callvirt instance void [System.Windows.Forms]System.Windows.Forms.Control::add_Click(class [mscorlib]System.EventHandler)
ldarg.0
ldfld class [System.Windows.Forms]System.Windows.Forms.Button frmHello::btnHello
"Hello"
callvirt instance void [System.Windows.Forms]System.Windows.Forms.Control::set_Text(string)
ldarg.0
call instance class [System.Windows.Forms]System.Windows.Forms.Control/ControlCollection [System.Windows.Forms]System.Windows.Forms.Control::get_Controls()
ldarg.0
ldfld class [System.Windows.Forms]System.Windows.Forms.Button frmHello::btnHello callvirt instance void [System.Windows.Forms]System.Windows.Forms.Control/ControlCollection::Add(class [System.Windows.Forms]System.Windows.Forms.Control)
ret
}
.method private hidebysig instance void btnHello_Click(object sender, class [mscorlib]System.EventArgs e) cil managed
{
ldstr "Hello" call valuetype [System.Windows.Forms]System.Windows.Forms.DialogResult [System.Windows.Forms]System.Windows.Forms.MessageBox::Show(string) popret
}
}

Related Blogs
Creating and Consuming Class Library in C#, Object Initializer
C# WPF Creating a Class with Constructors

Placing ComboBox in Windows Forms DataGrid Cell

A common task found in invoicing application is placing a combobox in a particular colum of a DataGrid. Let's see how to do that in VB.Net.

Imports System.Data.SqlClient

Public Class Form1
Dim cn As SqlConnection
Dim cmd As SqlCommand
Dim da As SqlDataAdapter
Dim dr As SqlDataReader
Dim ds As New DataSet

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
cn = New SqlConnection("integrated security=sspi;initial catalog=Northwind")
cn.Open()
da = New SqlDataAdapter("select ProductName,CategoryId,UnitPrice from Products", cn)
da.Fill(ds, "Prod")
DataGrid1.SetDataBinding(ds, "Prod")
Fillcombo()
DataGrid1_CurrentCellChanged(DataGrid1, e)
End Sub

Private Sub Fillcombo()
cmd = New SqlCommand("select * from categories", cn)
dr = cmd.ExecuteReader()
While dr.Read()
ComboBox1.Items.Add(dr("CategoryName"))
End While
End Sub

Private Sub DataGrid1_CurrentCellChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DataGrid1.CurrentCellChanged
Dim x, y, h, w As Integer
Dim rect As Rectangle
rect = DataGrid1.GetCurrentCellBounds
x = rect.X + DataGrid1.Left
y = rect.Y + DataGrid1.Top
w = rect.Width
h = rect.Height
ComboBox1.SetBounds(x, y, w, h)
ComboBox1.Visible = True
End Sub
End Class

Using COM Controls in .Net




Many firms have invested millions of dollars in COM. So you can't expect them to throw away COM one day and adopt .net afresh.



It is possible for .Net to inter operate with COM and use COM dlls and controls in .Net.






We are going to see how to use one of my favorite COM Control - TreeView in .Net



Create a new tab in Visual Studio 2008 .Net toolbox and give good name like COM.



Right click the tab and select Choose Item which will take you to 'Choose Toolbox items' dialog. You can see three tabs viz. .Net Framework Components, COM Components and WPF Components. Select COM Components tab and check Microsoft TreeView Control 6.0, and that will add the COM treeView to the toolbox.








First let us review the VB.Net code.
Imports MSComctlLib.TreeRelationshipConstants

Public Class Form1

Dim Nodx As MSComctlLib.Node

Private Sub Form1_Load(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
MyBase.Load

Nodx = AxTreeView1.Nodes.Add(, , "India",
"India")

Nodx = AxTreeView1.Nodes.Add("India",
MSComctlLib.TreeRelationshipConstants.tvwChild,
"Kerala", "Kerala")

Nodx = AxTreeView1.Nodes.Add("Kerala",
tvwChild, "Kochi", "Kochi")

Nodx = AxTreeView1.Nodes.Add("India", tvwChild,
"Karnataka", "Karnataka")
Nodx.EnsureVisible()
End Sub

Private Sub btnAdd_Click(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
btnAdd.Click

Nodx =
AxTreeView1.Nodes.Add(AxTreeView1.SelectedItem,
tvwChild, txtNewNode.Text, txtNewNode.Text)
txtNewNode.Text = ""
txtNewNode.Focus()


End Sub
End Class

The VB.Net code is straight forward.

That is not the case with C#.
C# is highly strict in comparison to VB.Net.
So lets review the issues:
C# doesn't support optional parameters. In COM the value is passed by reference and there is no method overloading in COM.

C# Code

using MSComctlLib;

Node NodX;

private void Form1_Load(object sender, EventArgs e)
{
Object m = Type.Missing;
Object i = "India";
NodX = axTreeView1.Nodes.Add(ref m, ref m, ref i, ref i, ref m, ref m);

Object k = "Kerala"; Object rel = TreeRelationshipConstants.tvwChild;
NodX = axTreeView1.Nodes.Add(ref i, ref rel, ref k, ref k, ref m, ref m);

Object ka = "Karnataka";
NodX = axTreeView1.Nodes.Add(ref i, ref rel, ref ka, ref ka, ref m, ref m);
Object ko = "Kochi";
NodX = axTreeView1.Nodes.Add(ref k, ref rel, ref ko, ref ko, ref m, ref m);
NodX.EnsureVisible();
}









Wednesday, February 20, 2008

Asp.Net : Implementing Date Selection without CalendarExtender Ajax Control

Thought implementing Date Selection options with CalendarExtender Ajax Control is a breeze, many ASP.Net Programmers are still working with Asp.net 1.x.
With a bit of nostalgic tint let me blog on the code I used to write to implement the same functionality in Asp.Net 1.x.

I start out with placing three combo boxes for Day, Month and Year and fill the controls with valuues. Then catenated values of three comboxes will be committed to table.

Here is the code:

using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
SqlConnection cnn;
SqlCommand cmd;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FillDayCombo();
FillMonthCombo();
FillYearCombo();
DataBind();
}
cnn = new SqlConnection("Integrated Security=sspi;Initial Catalog=Shalvin;Data Source=.\\sqlexpress");
cnn.Open();
}

protected void FillDayCombo()
{
for (int i = 1; i < 31; i++)
ddlDay.Items.Add(i.ToString());
}
protected void FillMonthCombo()
{
string[] strMonths = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "July", "Aug", "Sep", "Oct", "Nov", "Dec" };
ddlMonth.DataSource = strMonths;
}
protected void FillYearCombo()
{
for (int i = 1990; i < 2020; i++)
ddlYear.Items.Add(i.ToString());
}

protected void Button1_Click(object sender, EventArgs e)
{
string strDate = ddlDay.Text.ToString() + "-" + ddlMonth.Text.ToString() + "-" + ddlYear.Text.ToString();
Response.Write(strDate);
cmd = new SqlCommand("Insert into DateTest values ('" + strDate + "')", cnn);
cmd.ExecuteNonQuery();
Response.Write("Record Saved");
}
}


MultiTier

Now let's implement the same solution in Multi tier scenario.
I am creating a class called DBConnect.

public class DbConnect
{
public ArrayList GetDays()
{
ArrayList alDays = new ArrayList();
for (int i = 1; i < 31; i++)
alDays.Add(i.ToString());
return alDays;
}
public string[] GetMonths()
{
string[] strMonths = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "July", "Aug", "Sep", "Oct", "Nov", "Dec" };
return strMonths;
}
public ArrayList GetYears()
{
ArrayList alYears = new ArrayList();
for (int i = 1990; i < 2020; i++)
alYears.Add (i.ToString());
return alYears;
}

Coming back to the form I am instantiating the DbConnect class and callilng its methods.
DbConnect dbc = new DbConnect();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ddlDay.DataSource = dbc.GetDays();
ddlMonth.DataSource = dbc.GetMonths();
ddlYear.DataSource = dbc.GetYears();
DataBind();
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
string str = ddlDay.Text + "-" + ddlMonth.Text + "-" + ddlYear.Text;
Response.Write(str);
}


Happy Programming
Shalvin@gmail.com

Friday, February 8, 2008

ASP.Net Profile

Profile is a ASP.Net 2.0 State Management option.

The greatest drawback with other state management options like Query String, Session Variable, Cookie and ViewState is lack of intellisense, which is the cause for hard to track bugs.
For example if you define a QueryString called Name in Default.aspx and refer to the same as Nam in Welcome.aspx, you won't get an error message instead a new QueryString variable called Nam will be created so obviously unpredicted result.

Profile supports intellisense.

Profile is strongly typed and you can specify default value.


Start out be creating Profile propertis in web.config












Make sure you run the application before using the profile properties.

You will get intellisense of Profile properties.

//Default.aspx
protected void btnSubmit_Click(object sender, EventArgs e)
{
Profile.Name = txtName.Text;
Profile.Blog = txtBlog.Text;
Profile.Rate = 400 + 100;
Response.Redirect("Welcome.aspx");
}


Here note that we are not assigning value to Specialization Profile property and we can apply arithmetic operations on Rate Profile property since its type is Int32.

We are accessing the value in Welcome.aspx

//Welcome.aspx
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(String.Format("{0} 's blog is {1} specializing in {2} hourly rate is {3} INR", Profile.Name, Profile.Blog, Profile.Specialization, Profile.Rate ));
}

Group of Personalization Properties

lt;profile>

<properties>
<group name ="Person">
<add name ="Name"/>
<add name ="Location"/>
</group>
</properties>
</profile>

//Default.aspx
protected void btnSubmit_Click(object sender, EventArgs e)
{
Profile.Person.Name = "Shalvin";
Profile.Person.Location = "Kochi";
Response.Redirect("Welcome.aspx");

}

//Welcome.aspx
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(String.Format("I am {0} my location is {1}", Profile.Person.Name, Profile.Person.Location));
}


Using Sql Server Instance Database

>aspnet_reqsql -E -S .\shalvin -d ShalvinProfile -A p



<connectionStrings>
<add name="ShalvinProfileConnectionString"
connectionString="Data Source=.\shalvin;Initial Catalog=ShalvinProfile;Integrated Security=True"
providerName="System.Data.SqlClient"/>
</connectionStrings>

<system.web>

<profile>
<providers>
<clear/>
<add name="AspNetSqlProfileProvider"
type="System.Web.Profile.SqlProfileProvider"
connectionStringName="ShalvinProfileConnectionString"/>
</providers>
<properties>
<add name="Name"/>
</properties>
</profile>
</system.web>







Related Blog

Query String Asp .Net : Working with multiple values

Session Asp .Net : Storing DataSet

System.IO Namespace

Knowledge of working with streams is very essential. Make sure you master these skills before venturing into Cryptography, Compression, Serialization, etc.

File and Directory classes of System.IO namespace contains static method for working with Files and Directories.

Creating a text file and writing to it

The following example demonstrates the easiest way to create a file and writing into it using StreamWriter class.

using System.IO;
StreamWriter sw;

private void btnCreateText_Click(object sender, EventArgs e)
{
sw = File.CreateText(@"f:\ShalvinPD.txt");
sw.WriteLine("Shalvin P D");
sw.WriteLine("Web site : shalvin.com");
sw.Close();
}


Creating an Html Page on Fly

Certain job sites creates as web page for you based on the information you provided about yourself. Let's see how to do it in .Net.

StreamWriter sw;
private void btnCreateHtm_Click(object sender, EventArgs e)
{
sw = File.CreateText(@"f:\1Hello.htm");
sw.WriteLine("");
sw.WriteLine("");
sw.WriteLine("Shalvin P D");
sw.WriteLine("
");
sw.WriteLine("Web Site : shalvin.com");
sw.WriteLine("");
sw.WriteLine("");
sw.Close();
System.Diagnostics.Process.Start("iexplore", @"f:\1Hello.htm");
}

Listing All Drives
Listing all drives is as simple as creating an array of DriveInfo class, calling the DriveInfo.GetDrives methos and Iteraing throught the DriveInfo collection.

StreamWriter sw;
private void Form1_Load(object sender, EventArgs e)
{ DriveInfo[] diDrives = DriveInfo.GetDrives();
foreach (DriveInfo diDrive in diDrives)
listBox1.Items.Add(diDrive);
}

Retriving the Drive Type, Free Space and Total Size of Drives

StreamWriter sw;
private void Form1_Load(object sender, EventArgs e)
{try
{
DriveInfo[] diDrives = DriveInfo.GetDrives();
foreach (DriveInfo diDrive in diDrives)
{
listBox1.Items.Add(diDrive);
listBox1.Items.Add(String.Format("Drive Type : {0}", diDrive.DriveType)); listBox1.Items.Add(String.Format("Free Space : {0}", diDrive.AvailableFreeSpace)); listBox1.Items.Add(String.Format("Total Size : {0}", diDrive.TotalSize));
listBox1.Items.Add(" ");
}
}
catch (Exception ex) { }
}

Adding Line Numbers to a File


StreamReader sr = new StreamReader("c:\\Code.txt");
StreamWriter sw = new StreamWriter("c:\\S1.txt");
private void button1_Click(object sender, EventArgs e)
{
int i = 1;
while (! sr.EndOfStream)
{
string s = sr.ReadLine();
sw.WriteLine(i.ToString() + " " + s);
i++;
}
sw.Close();
System.Diagnostics.Process.Start("notepad", "c:\\S1.txt");
}



Related Blogs
.Net Serialization (Code Snippets)

Email : shalvin@gmail.com