http://in.geocities.com/rsramsam/aspdotnet1.htm

                     

      ASP.Net  using  C#....

       (A  Quick tour)                                                                            -R.S.RAMASWAMY

(rsramsam@yahoo.co.in)

 

( published in  Feb-2004 issue of

     DEVELOPERIQ  magazine.

www.developeriq.com)

--------------------

  It can be claimed without being far off the mark, that ASP.net is the prize-offering  in the DotNet platform. ASP.Net programs can bewritten in either C# or in VB.Net. However, it is better to use C#.  Professional programming  mostly  requires C/C++/Java and C# is very much similar to these languages.Thus, it will be easier to switch over to other languages if necessary. If we want to write our program, using J# also, it will entail minimum change in style of coding..Moreover, C# is the language being actively promoted by Microsoft for certain advanced level work. 

 

 

 If we want to work in ASP.net , but in Linux platform using MONO, then C#  is a ' must' at present, though in future, it may be possible to create ASP.net programs in other languages in MONO.So, it will be better to switch over to C# from VB world.

 

VB.net however is only very slightly different from C# code.VB.net may seem to be the easier choice as it is the default language for 'ASP.net in Microsoft platform' and is not case-sensitive( how swiftly, things are changing! Who would have predicted that we may have to qualify  ASP.net with reference to the platform?) . But, being case-indifferent is not the best way to thrive in professional software field!.

 

Another point,which should be stressed is that though there are classes in' Windows.Forms' and 'Web.Forms', bearing the same name,their behaviour is different. ( For example, Datagrid).However, a lot of  C# code will work equally well in desktop as well as in ASP.net!     

 

     ASP.net makes VB programmers , equally productive in Web-Applications as well as desktop apps.Similarly,  ASP.net ,gives the great ease of webforms and webservice to j2ee hands and  removes all hurdles. For all appearances, ASP.net programming is just like VB programming except that instead of getting the gui elements by drag and drop, we have to write some rudimentary html-like code. True, even this difference vanishes if we are using VisualStudio.net but we will be using DotNet Framework SDK only, for our lessons because it is LEGALLY free for professional development and our method will be useful even in Linux world.  And , as we are studying ASP.net in C#,

we must write the code with case-awareness.

-------------------------------------------

The major topics in ASP.net are listed below.

 

 1) ASP.net Web-Form controls

 2) Database operations, Data-bound controls 

 3) Graphics & Dynamic graphics creation

 4) XML operations

 5) ASP.net Validation & special controls

 6) Separation of logic & presentation

 7) XML-WebService

 8) Mobile Applications.

 9) Session Management

10) File-Upload , email etc.

     ------------------------

    These are the topics that are essential to get started with  ASP.net.   If we know these  ,we would have covered about 75% and we can always learn the remaining topics , after this.

 

If we have some prior knowledge of Java,VB and ASP, and if we actually learn by doing,we can learn ASP.net  very easily.It is that very programmer-friendly environment, but so much more fun,powerful and modern!

---------------------------------------------

    However, some readers may find it very difficult to instal DotNet SDK and IIS-5 properly and run their first asp.net program successfully. This may well be the most difficult part.For Windows programmers,first, we should remember that Asp.net runs only in Windows-2000. Secondly, it requires InternetInformationServer-5. This is not automatically installed.But it is available separately in Windows-2000 CD. We also need  InternetExplorer 5.5 or above(6.0 preferable). Microsoft Data Access Components 2.7 (MDAC2.7)

 also has to be installed. We must checkup whether the server is working by creating a simple page as:

'D:\inetpub\wwwroot\welcome.htm'.

---------------------

<html> <body>welcome</body></html>

-------------------

 & viewing it in browser. as 'http://localhost/welcome.htm'.

 

   After this, we must checkup a simple 'demo1.aspx' as given below. If we get correct result, we are on our way.   

--------------------------------------------

(TOPIC-1).......  ASP.net WebForm  Controls

    ===========================

     Let us straight away begin with a simple ASP.net example using WebForm controls.

  

We create demo1.aspx file in 'lessons'folder

,as (d:\inetpub\wwwroot\lessons\demo1.aspx)

-----------------------------------------------  

 

<%@    language="C#"   debug="true" %>

<script         runat=server  >

 

void job1(Object o, EventArgs   e)

{

String   s = text1.Text;

text2.Text=s;

}

</script>

 

<html><body><form         runat=server>

 

<asp:textbox  id=text1    runat=server  />

<asp:button   text="click" 

   onclick=job1  runat=server />

<asp:textbox   id=text2    runat=server   />

 

</form></body></html>

-----------------------------------------------

In C#,all Class names,functions and properties begin with Capital letter. Instead of camel-

back notation as in Java, we use capitalletter

 for that purpose also.(see how EventArgs is

 typed in the script section).These rules are

 the same as in MFC and so only Java

programmers , accustomed as they are to

function names beginning with 'lower case' and camelback notation will have some initial difficulty.

-----------------------------------------------

In reading  ASP.net code, we always begin with

the html section. It looks like the usual html

 form, except that asp:textbox and asp:button

have been used. Secondly, each of these lines

ends with 'runat=server'  attribute.The html

section is NOT case-sensitive.(but the script section is definitely case-sensitive...in C#).Carefully note that we have not

specifically mentioned GET or POST.

The default is POST. (Posting to itself!)

 

When we start the browser and type the URL as:

 'http://localhost/lessons/demo1.aspx',

and hit 'enter', we get a textbox(text1),a 

button and another textbox(text2).Let us type something in text1 and click the button.  

What we typed  in text1 now appears in text2!

( Due to compilation time, allow for some

 delay).

(Is this ASP.net or VB or JAVA?).That easy!

 

   Actually, what is being done behind the

scene is very much complex! The 'apparently

html'  code is compiled in the server and the resultant html is sent to the browser. If we

try to see the source in the browser, we see standard html for textboxes and button.We also

 see some strange characters dubbed as 'viewstate'!.and 'hidden' . When any button is clicked in ASP.net, it is equivalent to

submitting the form to the server! The code

 re-creates the form's controls and fills up

the data as required.

The data typed in text1 is retained as if we

are in VB!Anyone with familiarity in ASP will

realise,that  to create the same effect in

plain ASP requires  imagination and dynamic

form creation.

-----------------------

 Now that we have seen a simple example,let us

see the syntax for creating a few other gui elements.     ----------------------------------------------

 

<asp:dropdownlist  id=combo1  runat=server />

 

<asp:listbox   id=list1       runat=server />

 

<asp:listbox   id=list2

      selectionmode=multiple  runat=server />

 

<asp:checkboxlist

           id=checklist1      runat=server />

 

 <asp:radiobuttonlist

           id=radiolist1      runat=server />

-----------------------------------------------

 We can populate these controls by the uniform method of    first creating a vector, adding elements to that vector      and binding the respective control to the vector.

(Actually, the class-name is ArrayList but we

name the       variable as vector so that Java coders will find it     easy to follow.)

     

      For example,

           ArrayList   vector1;

                 vector1 = new ArrayList();

                     vector1.Add("Madras");

                     vector1.Add("Bombay");

                     vector1.Add("Delhi");

           combo1.DataSource=vector1;

           combo1.DataBind();

      --------------------------------------

    Considering another example,

           ArrayList      vector2;

                    vector2=new ArrayList();

                      vector2.Add("COBOL");

                      vector2.Add("C++");

                      vector2.Add("Java");

                      vector2.Add("MFC");

                      vector2.Add("C#");

            checklist1.DataSource=vector2;

            checklist1.DataBind();

    ------------------------------------------

Exactly, same method as the above,is followed

for populating    simple-list & multi-list and radiobutton-list.As this is done  in scripting  section, the html part is absolutely free from clutter!

 -----------------------------------------------  

 How do we extract data from these controls?

Simple! In combo,simple-list and radiolist, we have to get just one string. So,

    --------------------------------------------

     String     s1=combo1.SelectedItem.Text;

 

     String     s2=list1.SelectedItem.Text;

 

     String     s3=radio1.SelectedItem.Text;

     --------------------------------------------

    In multi-list and checklist, we have to extract more than     one item. So, the syntax

is special.

 ------------------------------------  

       For multi-list,

           String  s = "";

   foreach(ListItem   item  in list2.Items)

       {

         if(item.Selected)

            {

             String   a=item.Text;

             list3.Items.Add(s);

            }

      

                -----------------------------------------------

      'ListItem' is a class name.

      'Items' is a property of listbox.

      'Selected' is a property.

      'Text' also is a property. 

      'Add'  is a method.

--------------------------------------------     

   For check-list,

     String   s = "";

  foreach(ListItem  item in checklist1.Items)

    {

      if(item.Selected)

         {

         String  a=item.Text;

       List3.Items.Add(s);

 

         }

So, where is the difference?  It occurs in the source of 'Items'.

-----------------------------------------------

 How do we create the equivalent of TextArea?

 As is VB, it is just a textbox with multiline property.

  

<asp:textbox   id=area1  textmode=multiline

    rows=6   columns=20    runat=server  />

-----------------------------------------------  

 

 Let us now consider a second example

(demo2.aspx). The purpose is to illustrate

creation of  combo,multi-list and simple-list controls  and the ususl operations in them.

 In this demo,a combo offers options for

various Engg branches. When we choose the

required branch, a list of  best students of

that branch is displayed in multi-list (list1)

We can select a few  in a single step and

add them to simple-list(list2). If we want to delete any name from list2, we can.

 

We can repeat the process for each branch and

 arrive at the final selection list.In essence, this is nothing but the famous 'Shopping Cart' problem of the web.The only difference is that

we have not populated the controls from a

database . But once we understand this simple example, a real world example is not all that difficult and is being given after covering

database.  

 

 We want the combo to be populated when the

form first appears but not afterwards.

 (similar to form_load in vb).But, each time

a button is clicked in ASP.net, the form is

posted back to the server!So, we must ensure

 that the combo is not loaded repeatedly.

This is checked up by  the conditional :

if(!IsPostBack)

-----------------------------------------------

  // d:\inetpub\wwwroot\lessons\demo2.aspx

============================================       

 

 

<%@   language="C#"    debug="True"    %>

<script    runat=server>

  void Page_Load()

  {

   if(  !IsPostBack)

   {

    ArrayList         vector1;

      vector1 =       new ArrayList();

             vector1.Add("Electrical");

             vector1.Add("Mechanical");           

        combo1.DataSource    = vector1;

        combo1.DataBind();

   }

  }

//---------------------------------------

   void job1(Object o, EventArgs e) 

    {

 String   s  =  combo1.SelectedItem.Text;

      ArrayList      vector1;

       

      

         if(s =="Electrical")

           {

             vector1=new ArrayList();

        

             vector1.Add("Thomas");

             vector1.Add("Robert");           

             vector1.Add("Sam");

           }

 

          if(s == "Mechanical")

            {

             vector1=new ArrayList();

            

              vector1.Add("James");

              vector1.Add("Jones");

              vector1.Add("Tom");

             }

          list1.DataSource = vector1;

         list1.DataBind();

         

    }

//--------------------------------------

  void job2(Object o, EventArgs e) 

      {

foreach (ListItem  item    in list1.Items)

     {

        if (item.Selected)

               {

                  String a = item.text;

                 list2.Items.Add(a);

               }

            }     

       }     

 //-------------------------------------- 

      void job3(Object o, EventArgs e)

      {        

    list2.Items.Remove(list2.SelectedItem);

      }

//----------------------------------------

</script>

 

<html>  <body>

<form     runat=server>

 

<asp:dropdownlist id="combo1" runat=server />

<asp:listbox   id=list1

   selectionmode=multiple     runat=server />

<asp:listbox   id=list2       runat=server />

<asp:button   text="select branch"

              onclick=job1    runat=server />

<asp:button   text="add"

              onclick=job2    runat=server />

<asp:button   text="remove"

              onclick=job3    runat=server />

 

</form>

</body>

</html>

 

===============================================

Though, we have not covered all the controls,

these are enough for the present.We now move on to Database opearations.

==============================================

 

(SECTION-2) DATABASE OPERATIONS

 ------------------------------    

    ADO.net  offers two sets of packages for Database operations.

 

         a) OleDb

         b) SqlClient

         ----

As we know,Microsoft offers an indstrial grade

DB product    known as SQLSERVER.   In DOTNET, Microsoft have provided a special low-level

 driver, especially for accessing SQLSERVER.      This speeds up the operations.   For other

databases like Oracle ,Access etc,they provide     another set known as OleDb.

-----------------------------------------------    

     Dot.net offers two methods of Database operations.

 

  SqlClient

  =========

 

          a) SqlDataReader

          b) SqlDataAdapter & DataSet

          -----

    OleDb

    -----------

         a) OleDbReader

         b) OleDbDataAdapter & dataset  -----------------------------------------------

 The Reader type is cursor based and fast&

does not bring the entire table into the

 memory.

 DataAdapater and DataSet method brings the

 entire database into memory.   This is known

 as 'In-memory database'. After this, the

connection to   the database is cutoff. This

enables other  clients to access the database.   After, viewing/manipulating the records, the

data can be stored   back in database , if

needed. This is the advantage of Dataset

approach. But, if the table is very large, it

 may slow down because of   too much memory consumption.(For those familiar with XML

parsing, these are similar to the merits of

SAX & DOM spectively).

 

  However, for XML opeartions , DataSet is

 very  easy and powerful.  So, for the usual operations like 'select','insert into' ,     'delete' and 'update' , we can   use the  

Reader method.For XML opeartions,we can use DataSet method..  ***********************************************

The following code-examples give illustration.

 

 1) Sample code: SqlSever:  Reader approach

  -----------------------------------------

<%@    page   language="c#"     %>

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

   <%

 

String s1= "Server=localhost;uid=RSR;pwd=sa;database=db";

 

 SqlConnection  con=  new SqlConnection(s1);              

      con.Open();

 

    String   sql="select * from  table1";

 

 SqlCommand    command=

           new SqlCommand( sql,    con);

 

     SqlDataReader    reader=

                 command.ExecuteReader();

 

     while(reader.Read())

     {

       Response.Write(reader[0].ToString());

       Response.Write("<br>");

     }

 

     reader.Close();

     con.Close();

     %>

 

  -----------------------------------------------

  2) Sample Code: SqlServer DataSet  approach

   ---------------------------------------------

 

 

<%@    page   language="c#"     %>

 

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

<%@ import namespace="System.Data" %>

<script     runat=server>

void Page_load()

{

String s1= "Server=localhost;uid=RSR;pwd=sa;database=db";

String s2="select * from table1";

 

SqlDataAdapter  adapter =

            new SqlDataAdapter(s2,s1);

   DataSet      ds = new DataSet() ;

 

        adapter.Fill(ds, "table1");

 

        grid1.DataSource=ds;

        grid1.DataBind();

 

}

 

</script>

 

<html><body><form         runat=server>

 

<asp:datagrid  id="grid1"  runat=server   />

 

</form></body></html>            

-----------------------------------------------

 3) Sample : Access database  Reader approach

 -----------------------------------------------

 

<%@ Page language="C#" debug="true" %>

<%@ Import NameSpace="System.Data.OleDb" %>

<script    runat=server>

 

  public void job1(Object o, EventArgs e)

  {  

//string s1 should be typed in a single line.

//leave gap between 'data' & 'source'.                

String s1=

"Provider=Microsoft.JET.OLEDB.4.0;

         "data source =d:\\hostel.mdb";                 

 

  

   OleDbConnection      con =

             new OleDbConnection(s1);;

   con.Open();

 String    sql  = text1.Text; 

 

  OleDbCommand   command =

               new OleDbCommand(sql,con);

  OleDbDataReader    reader =

                   command.ExecuteReader();

                               

  grid1.DataSource=reader;

  grid1.DataBind();

 

     reader.Close();

     con.Close();

}

 

</script>

 

<html><body><form runat=server>

 

<asp:DataGrid    id=grid1     runat=server />

<asp:TextBox id=text1  size=40 runat=server />

<asp:Button    text="click" 

               onclick=job1   runat=server />

 

</form></body></html>

-----------------------------------------------

4) Sample Code:  Access :   DataSet approach

------------------------------------------------

<%@    page   language="c#"     %>

 

<%@ Import NameSpace="System.Data.OleDb" %>

<%@ import namespace="System.Data" %>

<script     runat=server>

void Page_load()

{

 

// string s1 should be typed in a single line.

//leave gap between 'data' & 'source'.              

String s1=

 "Provider=Microsoft.JET.OLEDB.4.0;

               data source = d:\\hostel.mdb";

String  s2="select * from table1";

 

OleDbDataAdapter    adapter =

                 new OleDbDataAdapter(s2,s1);

   DataSet               ds = new DataSet() ;

 

        adapter.Fill(ds, "table1");

 

        grid1.DataSource=ds;

        grid1.DataBind();

 

}

 

</script>

 

<html>  <body>  <form         runat=server>

 

<asp:datagrid   id="grid1"  runat=server    />

 

</form>  </body>  </html>

***********************************************

We will now consider how a simple program can

be developed for web-based db-opeartions.

 

We can begin with an opening page 'opener.htm'

which will give links to various operations.

     

      a) addnew.aspx     

      b) delete.aspx

      c) update

      c) find.aspx    

  -----------------------

  These files form a comprehensive set.

We will assume that our database is created

using SQLSERVER, and is named 'db'.The table

name is table1 having just two fields.

namely 'name' and 'number'.

----

We can begin by creating a folder dbdemo :

d:\inetpub\wwwroot\dbdemo

-------

   Create opener.htm in this folder.

// opener.htm

==============

<html><body>

<a     href="addnew.aspx">addnew</a>    <br>

<a     href="delete.aspx">delete</a>    <br>

<a     href="find.aspx">find    </a>    <br>

<a     href="modify.aspx">modify</a>    <br>

 

</body></html>

------------------------------------------------

After this, we can create the various aspx

 files in the same folder.

----------------------------------------------

//   addnew.aspx

================

 

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

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

<script runat=server>

public void job1(Object o,EventArgs e)

 {    

   

         String  a=text1.Text;     // name

         String  b =text2.Text;    // number

String  s1=

"Server=localhost;uid=RS;pwd=sa;database=db";      

SqlConnection  con = new SqlConnection(s1);

                con.Open();

 String       sql =

"insert into table1 values ('"+a+"','"+b+"')";

 

SqlCommand    command =

           new SqlCommand(sql  ,  con);

      

        command.ExecuteNonQuery();

        con.Close();

  label1.Text = "new record has been added";

}

</script>

 

<html>

<body>

<form runat=server>

 

<asp:textbox id="text1"   runat="server"/><br>

<asp:textbox id ="text2" runat="server" /><br>

<asp:button text="addnew"

       Onclick="job1"    runat="server"/>

<asp:label id="label1"   runat="server" />

 

<asp:hyperlink id ="link1" text="verify"  

  navigateurl="find.aspx"  runat ="server" />

 

<asp:hyperlink     id="link2"   text="opener"

 navigateurl="opener.htm"   runat=server   />

 

</form></body></html>

 

The files for 'delete', 'update' , etc are

similar.

For 'delete.aspx', we provide just a text1

and button.(job1).

---

  String          s=text1.Text;  

                                                                String     sql=

 "delete from table1  where   name='"+s+"' ";

 

command.executeNonQuery();

============================================

For update, we can provide text1,text2 & text3

(where text3 is the criterion by name).

   String        s1=text1.Text;

   String        s2=text2.Text;

   String        s3=text3.Text;

String  sql =

"update table1 set name='"+s1+"',

    number='"+s2+"' where

    name='"+s3+"'    ";

command.executeNonQuery();

=========================================

The complete code for 'find.aspx' is follows:

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

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

<script runat=server>

  public void job1(Object o,EventArgs e)

   {

String  s1=

"Server=localhost;uid=RSR;pwd=sa;database=db"

SqlConnection  con = new SqlConnection(s1);

      String         a=text1.Text;

           

String      sql =

 "select * from table1 where name='"+a+"'";

       

 

 SqlCommand     command =

         new SqlCommand(sql,con);

 

 SqlDataReader   reader=

            command.ExecuteReader();

 

        ArrayList  vector1;

        vector1 = new ArrayList();

 

        while (reader.Read())

        {

     vector1.Add(reader["name"].ToString());

         }

        reader.Close();

 

        int n;

 

        n=vector1.Count;

 

 if (n==0){Response.Write("no such record");}

 

 else

   {             

   grid1.DataSource=command.ExecuteReader();

   grid1.DataBind();

   }

 

   con.Close();

 

}

</script>

 

<html><body><form runat="server">

 

<asp:textbox id="text1"  runat="server"/>

<asp:button text="find"

        Onclick="job1"   runat="server"/>

<asp:DataGrid id="grid1" runat="server"/>

 

</form></body></html>

=================================================

Now that we have seen the basics of database

operations , let us develop a simple shopping

cart for 'bookshop' .

We will create a database in Access and name

it as 'bookshop'. It has two tables. 'table1'

 has just one column.

The name of this column is 'subject'.

 The other table, is named 'table2' and has

two columns, namely , 'subject' and 'title'.

Let us fillup table1 with all the subjects and

in table2, we fillup with subjects and titles.

Finally , we move this database to D: DRIVE.

(because the default c:\my documents' is clumsy.)

-------------------------------------------------

  File name : 'shopcart.aspx'

  ==========================

   (d:\inetpub\wwwroot\lessons\shopcart.aspx')

--------------------------------------------- 

 

<%@ Page language="C#" debug="true" %>

<%@ Import NameSpace="System.Data.OleDb" %>

<script    runat=server>

                                

  public void Page_Load()

  {

      if(  !IsPostBack) {

// String s1 should be typed in a single line.

// provide space between 'data' & 'source'!

 

 String   s1=

   "Provider=Microsoft.JET.OLEDB.4.0;

            data source=d:\\bookshop.mdb";

  

   OleDbConnection  con =

        new OleDbConnection(s1);

   con.Open();

 

 OleDbCommand  command =

 new OleDbCommand("select * from table1",con);

 

 OleDbDataReader  reader =

                 command.ExecuteReader();

                               

  combo1.DataSource=reader;

  combo1.DataTextField ="subject";

  combo1.DataBind();

 

     reader.Close();

     con.Close();

    }

}

 

void job1(Object o,EventArgs e)

{

  

  String s = combo1.SelectedItem.Text;

 

   String s1=

"Provider=Microsoft.JET.OLEDB.4.0;

            ata source=d:\\bookshop.mdb";

 

 OleDbConnection  con =

                new OleDbConnection(s1);

   con.Open();

String  sql=

 "select title from table2 where

                  subject = '"+s+"' " ;

 

  OleDbCommand  command =

             new OleDbCommand(sql,con);

    

  OleDbDataReader  reader =

                   command.ExecuteReader();

                               

  list1.DataSource=reader;

  list1.DataTextField="title";

  list1.DataBind();

 

     reader.Close();

     con.Close();

 

   }

 

   public void job2(Object o,EventArgs e)

   {

 

     foreach (ListItem item in list1.Items)

     {

       if (item.Selected)

       {

          String a = item.Text;

          list2.Items.Add(a);

       }

     }

}

 

public void job3(Object o,EventArgs e)

 {

   list2.Items.Remove(list2.SelectedItem);

   }

 

public void job4(Object o,EventArgs e)

 {

   list2.Items.Clear();

   }

 

</script>

 

<html><body>

 

<form           runat=server>

 

<asp:dropdownlist  id=combo1  runat=server  />

<asp:button   text="show" 

             onclick=job1   runat=server    />

<asp:listbox id=list1 

     selectionmode=multiple  runat=server   />

<asp:button   text="add" 

            onclick=job2     runat=server   />

<asp:listbox  id=list2       runat=server   />

<asp:button   text="remove"  

             onclick=job3   runat=server    />

<asp:button   text="remove all" 

             onclick=job4   runat=server    />

</form>

</body>

</html>

 

**********************************************

 

     The  concluding part of this tutorial is continued in

     second part.

 

                        HOME  PAGE

1