|
http://in.geocities.com/rsramsam/aspdotnet1.htm |
ASP.Net using C#....
(A Quick tour) -R.S.RAMASWAMY
( 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("
vector1.Add("
vector1.Add("
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"%>