Cmp212 ASP Net Reference Book
Cmp212 ASP Net Reference Book
NET 1
Introduction To .NET
In this lecture you will understand:
Today's software scenario
What Is .NET & why use it
Roadmap for learning
2 Introduction To .NET Building Portals Through ASP.NET
What Is It?
.NET is a framework consisting of common language runtime and a set of .NET base classes which
allow us to build distributed, secure, scaleable, robust, easily deployable and maintainable
applications in a language independent, object-oriented, web enabled, managed way using rich level
of integration amongst present technologies. Most of the books contain such a complicated definition
of .NET. Somebody who begins his tryst with .NET will find this definition too heavy.
Software Scenario
Many applications are build today are Desktop applications. Some are Web applications. We also
have Embedded applications. We have Distributed applications, Operating Systems, Compilers and
Device Drivers. So anybody who is trying to do any kind of computing in today’s software world
would be doing one of these different things. Desktop application can be an application like Internet
Explorer, Antiviral Software like AVG, simple editor like Notepad, simple admission system where
students come in and register for a particular course. These applications are typically build using VB
and VC++ in the past and they are now build using .NET technologies. Web applications like NDTV
website, MSN website. Earlier these websites were build using technologies like ASP or JSP. In
today’s software scenario these web applications can be easily build using .NET technologies.
ASP.NET is one of the subset of the .NET technologies created solely for building web applications
and web services. Initially Embedded systems were build using C or Java programming. But
increasingly there is migration towards using .NET for building even the Embedded systems. An
Embedded system is a system where a program is running but the device on which it is running is not
a computer. Mobile phone, washing machine and microwave are examples of Embedded system. The
programs which run in Embedded systems can also be build using .NET technologies. A banking
system, airline reservation system and railway reservation system are good examples of distributed
computing. Earlier this distributed computing was done using C language to begin with and
subsequently using a technology created by Microsoft known as Component Object Model ( COM ).
These technologies are completely overtaken by .NET. In a distributed application scenario we have
banking system and there are different branches. Those branches carry out business. They transact
business. So machines which are present in different banks have to communicate with centralized
server for the transactions to happen. In such distributed computing also .NET technologies have a
big role to play. Operating system, compilers and device drivers are build using C and C++. .NET is
all about building applications efficiently.
Why .NET?
• It is easy to develop applications in .NET because
o We can actually check as you type like spell-check or grammar check which we make
use in Word, PowerPoint or Excel.
o It offers a technology created by Microsoft called as Intellisense.
o We do not have to remember the function parameters, their type and their order. This
becomes available to us on the fly as we start typing.
o It provides very good examples/samples.
o We get exhaustive MSDN help.
• Microsoft has taken lot of pains to ensure that development of any application becomes very
rapid. Means turn around time for any project should not be very long. Everything should be
made available to developer which helps into reduce the time of development.
o Media player takes 10 minutes.
Building Portals Through ASP.NET Introduction To .NET 3
.NET Technologies
There are three basic categories in which we tried to build .NET applications. They are Desktop
applications, Mobile applications and ASP.NET applications.
Desktop Track
We expect desktop applications to have some sort of Internet connectivity. AVG antiviral software is
an example of it. Everyday we put on the machine, the AVG application checks whether we are
connected to the Internet and if we are, it indeed goes there and downloads the latest signatures. This
way our antiviral software remains up-to-date. Any new viruses that have posed, they are taken into
account by downloading suitable virus signatures every time we put on the machine and connect to
the Internet. Desktop applications also allow to create pluggable interfaces. Google toolbar is an
example of it. This Google toolbar is attached to the Internet Explorer. Yahoo also provides a toolbar
which gets embedded in the Internet Explorer. Means Internet Explorer is a desktop application but
people do want to provide plug-ins which will integrate with Internet Explorer. Desktop applications
are becoming functionally much richer. For example, we expect that any proper desktop application
would have any kind of help available. We also expect that search to become available within the
application. Likewise updation of the existing desktop software is popularly being done today.
Mobile Track
In the mobile track, we have to be careful about the screen sizes. While building a standard
application which runs on a PC, we can easily assume that the screen can be either 800 x 600
resolution screen or 1024 x 768 resolution screen whereas with mobiles, we get much smaller
screens. The geometry of different mobile devices are different. Some are laid out horizontally, some
are laid out vertically. Even if laid out vertically, size of each mobile phone’s display is also different.
User interfaces are different. Some mobile phones make use of a pointer, a stick using which we can
click on the screen which is touch sensitive such that we can use it as if we are marking numbers with
a pen or tapping the calculator using fingers. What kinds of user-interfaces are there is depends upon
the model of the mobile phone. When we are using mobile phones, connectivity is intermittent. When
we are using mobile phones, connectivity is intermittent. We cannot assume that our phone is
connected to Internet all times. We also even cannot assume that our phone is connected to carrier
networks at all times. We have to account for all these possibilities whenever we are trying to build
applications for the mobile phones. Synchronization of address book is an example of mobile phone.
ASP.NET Track
In the ASP.NET track, we might create different applications which act like portals. Portals are very
comprehensive. For example, from Yahoo’s portal we will get so much useful information from
different spheres right from what is the weather in different parts of the world, what kind of programs
are being organized in the city which we are visiting, alarm systems, calendaring system, emailing.
All this put together is a portal. In different websites, different themes are being followed. In the early
days of web programming, different pages even though they had a similar look and feel, there wasn’t
4 Introduction To .NET Building Portals Through ASP.NET
a mechanism available where we declare a theme and use it in all the pages. With .NET that has
become possible. This leads to faster development time. We also get different modules today. For
example, if we want that there should be an emailing system available in our website then we just
have to plug that module in our website. If we want that the calendaring system should be available
or a shopping cart should be available, we have to plug that in our website. Those kinds of
applications we might be required to create for a web application. .NET makes it easier for us.
Location
A desktop application typically runs on a machine and it is invoked from exactly the same machine
on which it is running. We typically execute a desktop application by double clicking its icon. We
can also execute the desktop application from the command line. Command line is accessed through
Start | Run menu item and try to execute command line shell by typing cmd in the dialog that we get
when we do Start | Run. Then we get a command window that’s the shell, text based shell. There we
can execute the applications at the command line. For example, we can execute Internet Explorer by
typing iexplorer.exe at the command prompt. We can start Microsoft Word by typing winword.
Means for every single application, we may not want to do a double click, we can even execute those
applications from command line. In a typical web application, application is anyway running on the
web server. Whenever a web application is deployed on a web server, the moment we boot that
machine i.e. the server machine, the application gets launched. Means whenever we are trying to
access a website, its not that we are trying to start the website. Website is already running there on the
web server. Unless we double-click the word icon, the word is not in the memory. We have to launch
it into the memory whereas a web application is already running into the memory but we have to
access it through a web browser. If we want to visit Google, we just type out www.google.com in the
browser. We invoke an application by sending a request through a web browser. Application is
already running in memory of the web server. Means web model is basically a distributed model. The
machine where the application is running is different than the machine from which we are trying to
interact with that. Whereas typically in a desktop application, the machine where the application is
running and where the interaction is happening is commonly the same machine. Most desktop
applications would be activated from the same machine on which they are deployed whereas in a web
application even the simplest of simple web application, application runs on a different machine; it’s
invoked from a different machine. So physical location of somebody who is trying to interact with the
application and the machine on which it is actually running, they are two different machines.
Invocation
A desktop application is invoked by double-clicking its icon or from the command-line whereas the
web application is already running on the web server. We just have to send a request to the web
server saying that let us carry out interaction with this already running application on the web server.
For example, we may start Internet Explorer and then type out some website address here may be
quest.ksetindia.com where we have hosted our store. So it is easily accessible to us. We have to send
the request to this particular site. The quest.ksetindia.com really gets mapped onto the IPAddress of
the machine where this particular site is hosted. quest.ksetindia.com gets converted to a 32-bit
address wherein it identifies the machine where this particular site is hosted. From that particular
machine, we are sending a request to some default page. The default page is returned to us. That
default page is rendered or displayed within the browser.
Building Portals Through ASP.NET Web Model Fundamentals 7
Number Of Users
In desktop applications, typically there is one user at a time. Most desktop applications would have
one user at a time unless we have created a desktop application to run in a network environment. For
example, there might be an admission system wherein there are three desks at which admission
information is being received and fees are being collected. So that’s a networked application. Its not
Internet enabled application. It’s still a desktop application but all these PCs are connected in a
network and may be they are communicating with a centralized server where all the data about the
students is getting stored as it is being received at three different nodes or three different machines.
Web applications are typically going to be used by thousands of users may be simultaneously. As a
result of which the web server where this application is deployed has to be a powerful server
necessarily. So any web application that we build, we always carry out a stress test on that application
because by the nature of a web application, we expect that several hundred users would be connected
to the site simultaneously. Is that scenario is being addressed in the website or not, that we need to
figure out. Hence the basic parameters of testing itself changes when we talk about a web application
as compared to a desktop application because by its very nature the number of users are just too many
for a web application. Clients from different machines can physically interact with this application
that is running on the centralized web server.
Connectivity
In case of a desktop application, the connectivity is needed rarely. For example, AVG antiviral
connects to the Internet when we start the AVG application or when we put on the machine, the AVG
software automatically starts and then it figures out whether Internet connection is alive at that
moment and if possible, if it is alive then it connects to the Internet and tries to retrieve the latest
virus signatures and downloads them automatically. If we want that those signatures should get
downloaded periodically then we need limited connectivity. In case of any web application, it is
understood that we are at all times connected to the Internet. Unless there is Internet connectivity,
there is no web application running. Application might continue to run but unless we are connected to
that application through Internet, that application really means nothing to us. Connectivitywise
expectations of desktop platform and web platform are completely different.
Programming Model
In a typical Windows based desktop application, there is a Event Driven programming model means
in a window if we have some text boxes, some buttons, some list boxes, some combo boxes, some
tree controls then as and when we interact with these controls an event is raised. Then there are
functions present in the application which react to these occurrence of different events. For example,
if we click on a mouse button then some method within the application would be called. We have to
arrange for this, when we build desktop applications. But basically it’s an Event driven model. As
events occurred, suitable functions get called. Web application model is basically a request-response
model means application is already running, we have send a HTTP request saying that give us a
particular page. It returns a response and that response gets rendered within the browser. There has to
be some rule according to which these requests are made. Those set of rules is known as a protocol.
The commonly used protocol for interacting with a web application is HTTP protocol. According to
this protocol, only we have to send a request and according to this protocol, only the response comes
back to us. So writer of every web application has to ensure that whenever he sends a response for the
request made by the user that response is uniform. Then only our browser would be able to
understand it properly and display that response to us within the window of the browser. So the way
it is imperative, it is necessary that the request has to be done in a uniform and consistent manner,
same way it is the responsibility of the web developer to send the response to its client also in a
uniform manner and to ensure this uniformity, we have protocols like HTTP through which we make
a request and through which we make a response.
8 Web Model Fundamentals Building Portals Through ASP.NET
State Model
In case of a desktop application, it’s a stateful model. For example, if we have two buttons present on
a desktop application. When we click on one button, some event happens. As a result of which, some
function gets called and then some calculation is done within that function which is kept somewhere
in memory. Then we click on the other button, some other event will occur, some other function
would be called but this function can have an access to the answer that we got when we clicked on
the 1st button. Means whatever is the state that is something that is available for subsequent actions.
Whatever calculations that we did when we click the 1st button, result of that calculation can be made
easily available to another event handler which gets called when the 2nd button is clicked. In case of
web application this is not so at all. HTTP protocol which is used for making a request and sending
back a response to the user, it’s a stateless protocol. Stateless protocol means what happens during
the 1st request is never remembered. So those results that occurred when the 1st request was made are
not available when the 2nd request is made. So that is the way the HTTP protocol has been created. So
the web model is a stateless model. The 1st request and the 2nd request are quite unrelated. 2nd request
does not know that some 1st request has already been made by the user. This leads to problems and
those problems were addressed by technologies like ASP.NET by storing the state of the 1st request
for the user. HTTP does not support that but ASP.NET model allows to build that kind of statefulness
into the application. Statefulness is built into the application not by HTTP but by ASP.NET which
lets us remember what is it that the user has done during the previous request.
Complexity
Desktop applications are simple whereas web applications are complex. The devices through which
we access a website are different. For example, if we want to access the website present on server, the
application remains on the same server but the devices on the client side change completely. We can
access a website through the desktop, we can also access it through laptop, we can access it through a
PDA or even a mobile phone. Geometry of these devices are very different and that has an impact on
building the web application. We have to build the application keeping in mind that a user is going to
connect through any of these four different methods and he should still be happy to see what he gets
on a screen. So we have to render the response in such a manner or we have to send the response in
such a manner that based on what kind of device the user had made a request from, it still gets
properly displayed on his device. In desktop applications it is going to deployed on a machine which
is going to have at the most 2-3 different resolutions. Different users may use different browsers to
send request to our application. Means what kind of request is going to come is same but the
capabilities of these different browsers would be different. Settings that we do within the browser
might also be different.
Web Evolution
Four different types of applications in this evolution phase could be a collection of static inter-linked
pages. Means in the early days of web people created 10-15 pages for their website, manage to put
them on the web and from one page we could quickly navigate to the other page. Links were
provided in each page and through those links we are able to navigate from one page to another. They
began with the home page and within home page they provided different links through which we
could really move onto the other pages present in the website. Different flight scheduling information
which is present on different websites of Airlines is an example of this. This phase lasted for quite
some time. After that came an era wherein people realized that why are only static contents on the
website? Why can’t we put dynamic contents on the website? If we take the same example of an
airline then in addition to the flight schedule people also started posting on their website the statuses
of different flights. This is a big step forward because this is when people started moving from
putting static content on the website to putting dynamic content on the website. Then it become more
demanding and so demanding that they said that why don’t we create full-fledged applications which
are hosted on the web and today that’s the reality. We don’t really have to go to the airline office to
book the tickets. We can book them online. All that we get a etiquette and that etiquette if we show
on the counter we will issue a boarding pass. Even there are provisions with certain airlines wherein
we don’t even have to go to the counter to get the boarding pass. We can print the boarding pass right
before 2 days of the flight. We can even choose a proper sitting which is appropriate to us. The
moment we choose a suitable sitting, it immediately block for us. Means this is a full-fledged
application. There is another set of applications that people are creating and exposing them as
webservices. This services model is very appealing. For example, if we want to know the current
conversion rate from US Dollar to Japanese Yen or Japanese Yen to Indian Rupees there are
webservices available on the net. We have to make function calls within the service and we make
these function calls from within our web application. Up-to-date information about the current
conversion rate from one currency to another is available to us. This web service exposes lot of other
things as well. Web service does not have a user interface. Services are available in the form of
functions and we simply have to make call to those functions. The difference between the full-fledged
web applications and the webservice is webservices never have any UI. So if we want to do any web
programming we should look at two possibilities; one is the web applications and 2nd is the
webservices.
application which will dynamically update the contents. Unless and until we have that in place, it
would just a too much time for we to be able to generate a HTML response. So, one thing is content
is going to be dynamic. 2nd thing is these dynamic contents will have to be generated
programmatically and 3rd problem is that HTML response if we start hand-crafting ourselves, it is
going to take time. Realize that over the years as the web evolved, HTML has also evolved. So
whatever are the capabilities of HTML lets say 5 years ago, today the capabilities are very different.
HTML has evolved and made it possible to integrate videos with the web pages in a seamless
manner. Means technology is in place to achieve all this but then if we start learning all the HTML
involved in doing this, in that case focus is going to get lost. HTML allows to present the information
in a proper manner. We should be able to programmatically generate HTML because the moment that
we make this content generation of HTML programmatic obviously we can change it dynamically.
We are going to use programs to generate HTML. That programming ability will allow the content
dynamic and we will rely on wizards to be able to generate most of the boiler plate HTML,
readymade or routine HTML.
Actual Code
We would put a for loop here running from i = 0 to i < 10 i.e. 10 times and each time through this
loop, we are going to display the latest value of i. To do so we would make a call to the method
Write( ) present in a Response object. So when we say Response.Write( ), Response is an object and
Write( ) is a method inside that object. For that to execute we need a namespace which is included at
the top i.e. System.Web. All the using statements shown in the slide are inserted by the wizard. We
had written <br /> in Response.Write( ) at the end. This is equivalent to a '\n'. The moment we put
this here automatically the number that gets printed through Response.Write( ) would start coming in
different lines. After that we would try to build the website by doing CTRL + F5.
Output
When we do CTRL + F5, we get the output shown in the slide. 10 different values of i being
displayed. In the browser’s address, we can see http://localhost:1296/WebSite1/Default.aspx. Here
1296 is known as a port number. When you execute this program, this port number may not be same
as shown here. The request for Default.aspx page is made and the moment we do so, the Page_Load(
) method is called and within that we had a for loop which wrote the response, which created the
HTML and that HTML was sent to the browser and browser rendered it by displaying different
values of i starting at 0 and ending up at 9.
HTML
In this lecture you will understand:
Genesis of HTML
Contents of HTML document
How to add HTML page
How to manage tables
How to generate dynamic content
Building Portals Through ASP.NET HTML 15
Genesis of HTML
There are at least three things common to all websites. One of them is the location. Every single
website will have some or the other Uniform Resource Locator. For yahoo, it is www.yahoo.com. For
Google, its www.google.com. Each website will have some or the other Uniform Resource Locator
means a unique way through which we would be able to reach that particular website. It’s known as
the URL. Each one of them would be using some or the other transfer protocol. The one which is
predominant is HTTP. When we send a request or even if we get back the response which is rendered
finally in the browser, there will have to be some or the other rules that will have to be followed.
Every response will have to be a HTTP response means the response that has been created as per the
rules that have been laid out in the HTTP protocol. Likewise, when we make a request for a particular
page on a website, this request also has to go in a standard form and that special way of making a
request is the HTTP request. Means using the protocol or the principles that have been laid out in the
HTTP protocol which for that matter stands for HyperText Transfer Protocol, we have to make the
request. So the request-response model of the websites works on this HTTP protocol. Third is the
publishing. All the content that is published is always in the form of HyperText and the language
which is used for publishing the content is the HTML language. That is common amongst all
websites. Information in today’s world is quite complex. Hence we have to have some ways or means
to identify this information or put this information using the markup language like HTML through
which we would want to publish this information. HTML can publish online documents; documents
which are complicated documents, documents which can contain not only headings and text but also
tables or lists or photographs. All these should be retrievable at the click of a button. We can design
forms for searching some information on the web or we can do online reservations through a HTML
page. We can put a spreadsheet in a HTML page, displays video within a HTML page or play some
sound clips.
Make Changes
When we do so, a new HTML page would get created for us. Now we want to make changes in that
HTML page. In each HTML page along with the tag there are attributes. For example, in the <html>
tag shown in the slide there is <html xmlns="http://www.w3.org/1999/xhtml"> means the attributes
are always organized in the form of name, value pairs. xmlns is the name and the value is identified
by putting that value within "". There can be multiple name, value pairs for a single tag. Means
multiple attributes can also be applied to a particular tag. Here each page has an attribute and it’s
organized in name, value pairs; so its syntax is name = "value". We can think of adding an attribute to
the body by saying <body bgcolor = "green" >. bgcolor is the background color. If we apply this
attribute to the body tag then whatever is within the body tag when displayed in the browser would
appear green in color. We can change the title from Untitled Page to My first HTML Page. Within
the body tag we can add a single line This is simple text.
Compile
After having done this, we would do CTRL + F5 to compile the website.
Result
The result is shown in the slide. We can see that the changes that we have suggested in the previous
slide have been made within the dialog that is shown in the slide. Title has now changed to My first
HTML Page and in the body we have text saying This is simple text. So This is simple text is
displayed within the web page. Request is made for the page Hello.htm and the address is
http://localhost:1489/Website1/Hello.htm. So once the request goes for Hello.htm, its contents would
be interpreted by the browser and suitably rendered within the window of the browser.
Using Tables
Tables come inside the <body> tag. Beyond This is simple Text. we are trying to add a table and that
has to be inserted within the <table> tag. Inside the table we have to identify the row for that table.
We are trying to identify the topmost row. In the <tr> tag, there is a Table Header containing Name
and Telephone Number. Means in the very first row of the table, we are going to get the Name and
Telephone Number. Below this Name and Telephone Number columns, we are trying to add some
names and telephone numbers. For that in the next row the Table Data for the very 1st cell is Name of
the person is Sanjay Jain and data for the next cell i.e. Telephone Number in the same row is +91
98450 23491. So one row contains the header, another row contains the table data. Both are marked
Building Portals Through ASP.NET HTML 17
using the <tr> tag. We may add one more Name and Telephone Number. So we add Vinod Wakhare
with telephone number +91 94221 12491. If we now try to make a request for this particular HTML
page then the result obtained is shown in the next slide.
Result
We can clearly see that Name and Telephone Number are clearly identified as headers. So they are in
bold. Then Sanjay Jain and Vinod Wakhare are the two rows of the table containing name and against
each name suitable telephone number has also been shown.
Check Output…
When we do CTRL + F5, we get in the output as shown in the slide, Name and Telephone Number as
header. We get Sanjay Jain and +91 98450 23491 as the name and telephone number i.e. table data in
the cells. We can appreciate that this is a dynamic content. But there is still some problem associated
with this. 1st problem is that we have completely hard-coded this information within the program. 2nd
is that there is no provision to work with the list of names and telephone numbers. We cannot modify
them, delete them, cannot sort them, add, list them.
18 Building Dynamic Websites Building Portals Through ASP.NET
Slide 8
20 Building Dynamic Websites Building Portals Through ASP.NET
The moment we select Add New Item, a new dialog would appear. In this dialog many items that we
can add to a website are listed out. Out of these, we select Class. Then give the name for the file as
Contact.cs. Then click on Add. So a new class would now get added. Before that addition happens, it
will ask that Do you really wish to add this new class to the website and it will also suggest you
where this class is going to get added. The name of the folder is App_Code. Inside this a new file is
going to get created. So say that we want to create this in App_Code directory.
Result – Contact.cs
When we click on Yes, we will see that a Contact.cs file will go into the App_Code directory as
shown in the Solution Explorer. The Contact class created is shown in the slide. Now we need to add
some code to it.
Slide 11
Now we would create properties like name, telno and mobile. Inside each property we have a get and
set clause. In the name property, get will allow to return the current value of m_name whereas set will
accept a value and set it up in m_name. Similarly in the telno property, get will allow to return the
current value of m_telno whereas set will accept a value and set it up in m_telno. Same is for mobile
property. get will allow to return the current value of m_mobile whereas set will accept a value and
set it up in m_mobile. So, each of these three properties has a get clause and a set clause.
Separated Values. It is very easy to read / write files in C# and can be opened in any text editor like
notepad.
Slide 16
Now we will write the LoadFromFile( ) function. This function receives a StreamReader reference
indicating from where we are proposing to carry out reading. We will use that StreamReader to make
a call to a ReadLine( ) function. Whatever string that it returns, we will collect that in a variable line.
We need to check whether line is null or not using if ( line != null ). ReadLine( ) would read only one
line. If there are no more lines to read from a file then ReadLine( ) would return null. If line is != null
means something remains to be read from the file which is associated with the StreamReader sr. Once
we have read a line then we can split it across the commas. To do so, we will call a function line.Split
( ',' ). There are three fields per line. They would be split up into three parts. Those three parts are
strings. Those strings are collected in list array which is an array of strings. Then we can split the line
that we have read across the different commas that are there in the line. list[ 0 ], list[ 1 ] and list[ 2 ]
after having split would contain name, telno and mobile. We would collect them in individual
variables name, telno and mobile. Then return true saying that we have been able to successfully
extract the name, telephone number and mobile number from a line that has been read from a file. If
we are unable to carry out the reading means if we reach the end of file in that case return false.
22 Managing Contacts Building Portals Through ASP.NET
Managing Contacts
In this lecture you will understand:
How to manage contacts
Design of classes to do so
ArrayList collection
Building Portals Through ASP.NET Managing Contacts 23
Managing contacts
When we decide to manage multiple contacts, we have to have the ability to store multiple contacts in
a file. Last time we used a comma separated value file means a simple text file rather than a database
or an xml file. Instead of getting into those complications, we said the CSV format is a straight
format which is popularly used today. So we would try to store our address book in a text file using
CSV. While managing contacts we would be required to add new contacts to that text file or we may
be required to delete an existing contact from the text file. We can also search a contact within the
contact book. We should also be able to save all the contacts into a file. We should also be able to
load all the contacts from a file. We should be able to handle unlimited number of contacts. We
should be able to maintain as many contacts as we want within the contact book.
Design
We have already seen the Contact class containing protected strings like name, telephone number and
mobile number. We also had created a 0-argument constructor, 2-argument constructor and properties
within the Contact class. Properties within the Contact class can either get or set the name, telephone
number or mobile number. From the Contact class, we had derived a FileContact class inside which
we had a 0-argument constructor and WriteToFile( ) function and LoadFromFile( ) function.
WriteToFile( ) function write contacts into the file and then we are also able to load those contacts
back from the file. This was done for one contact. Now its time to manage multiple contacts
simultaneously. To manage those multiple contacts we need to create a list of contacts and to do so
we will create a class called ContactList. In this ContactList class, to handle several contacts
simultaneously we need to create an ability to handle multiple contacts and for that we propose to
create an ArrayList. In the ArrayList, we would have references to several FileContact objects and
each FileContact object is going to contain a name, telephone number and mobile number. Within the
ContactList class we are also going to have a 0-argument constructor, a Search( ) function, a
LoadFromFile( ) function and a SaveToFile( ) function. ArrayList is a collection that .NET makes
available readymade to us. So rather than hand-crafting our own array to maintain several FileContact
objects, we would try to make use of standard ArrayList collection to do so.
Slide 6
In the SaveToFile( ) function, we would try to check out whether the file is existing or not. If it is
existing then we propose to delete it. When we say File.Exists( ), Exists( ) must be a static method
inside the File class. Similarly Delete( ) must be a static method inside the File class. Then we would
try to create a new StreamWriter object and to do so we will use m_path in which we have already
stored the path of the file in which our contact information is present. File class is defined in the
namespace System.IO. Once a StreamWriter object is created, we must start writing contact
information using the StreamWriter into the file whose path had already been stored in the
StreamWriter object. Number of contacts can be found using the Count property of the ArrayList
class. So when we do m_list.Count, we would come to know how many FileContact objects are
present in the ArrayList. Then we run a for loop and inside the for loop, we would first try to obtain
the FileContact object. ArrayList is a generic class which can hold on array of any objects. So when
we say m_list[ i ], we get the ith object present in the ArrayList. But since ArrayList is framework
class, when it returns the reference through m_list[ i ], it will return the reference of the FileContact
object. We need to specifically cast it before we collect it in a reference called con of the type
FileContact. Then we would say con.WriteToFile ( sw ). Once control comes outside the for loop
means we are done with writing of all the contacts into the file using StreamWriter then we can close
it by saying sw.Close( ). Then we would create a property List and it returns the ArrayList collection.
Inside this property we have a get clause which returns m_list. It is needed when we want to add a
new contact or delete an existing contact or make changes in the existing contact or display list of all
the contacts.
Search( )
We should carry out the search using the name. Moreover to be able to search, we should not be
required to give the entire name, even if part of the name is given then also we should be able to carry
out the search. What is to be searched is made available to the Search( ) function in the form of a
string called needle. Now we can run through the ArrayList collection. We can find out the number of
contact information present in the ArrayList using m_list.Count. Inside the loop, obtain the
FileContact information using m_list[ i ] and cast it into Contact and collect the reference of that
object in con. Then make use of two functions; one is Contains( ) and another is ToLower( ).
Whatever string is given to ToLower( ), it converts it into a lower case alphabet. Contains( ) helps to
check any part of the name. Once we have obtained from the ArrayList, the Contact reference then
we can check if ( con.name.ToLower( ).Contains ( needle.ToLower( ) ) ) and if that name is present
in the current contact then we say return con. Otherwise we would return null.
have ContactList.cs containing ContactList class definition which has the ability to maintain multiple
contacts again in the same directory.
26 Telephone Contacts User Interface Building Portals Through ASP.NET
User Interface
When we decide to build the user interface we have to understand what operations are we expecting
the user to perform while working with this website. We wish to carry out operations like display,
add, delete and modify on our contact list. Out of all these, we would first concentrate on the Display.
Whatever contacts we have, we should be able to display all of them on the screen. To do so, we will
have some contacts with us. For that we will first create some text file in which we would have some
minimum contacts and there onwards we would start displaying them. We would then add a new
contact to that particular file, so on. Whatever information we display on the webpage, it should be
possible for the user to read easily. Moreover the information that is present, we should be able to
carry out updation of that whenever a new contact is added or an existing contact is removed or an
existing contact is changed.
Design
The backend classes are Contact, FileContact and ContactList. We have created the Contact class
having protected strings like name, telephone number and mobile number. We also have constructors
and properties within the Contact class. From the Contact class, we have derived the FileContact
class which has the ability to add persistence to this contact information. We were be able to write the
contacts into a file or load them back from a file. Then we had created a ContactList class which
could maintain multiple contacts simultaneously in memory using an Array List collection. Inside the
ContactList class, we had 0-argument constructor, the Search( ) function, LoadFromFile( ) and
SaveToFile( ) functions. The LoadFromFile( ) function inturn call the LoadFromFile( ) of the
FileContact class. Likewise SaveToFile( ) function of the ContactList class inturn had called
WriteToFile( ) function of the FileContact class. Now to be able to display the information present in
the contact book right now, we need to add a page called ContactsManage.aspx. So the user interface
attempts to display all the contacts present in the contact book would begin with a creation of a new
webpage which is known as a Web Form. Whenever we create this Web Form, two files get created;
one is an aspx file containing html and the page directives and a code behind file which in this case is
a C# file. So the file created is ContactsManage.aspx.cs. So displaying of information, we would
manage through this Web Form.
Steps Involved
First we need to create and populate a data file called ContactsList.txt. Then we would add a new web
page in the form of a Web Form and we will call it as ContactsManage. Then we will have to insert a
table inside this web form and we need to do so by hand by editing the aspx file. Then we will try to
populate this table with the contents that we read from the text file i.e. ContactsList.txt file.
Population of the html table we propose to do through a program. Finally we are going to test what
we have done by building the website and then making a request for a page i.e. the
ContactsManage.aspx page such that we are able to figure out whether all that we had done is it
working or not. If it is working then we should be able to see list of contacts displayed on a web page.
Result
When we do so, now we would find that in the App_Data folder, the ContactsList.txt is ready with
the three contacts information. As shown in the slide, the result is going to look like once this
ContactsList.txt is ready.
Result I (aspx)
The moment we do so two files get created; one is ContactsManage.aspx file and another is
ContactsManage.aspx.cs file. This Result I shows the ContactsManage.aspx file. This
ContactsManage.aspx file is added outside the App_Data and App_Code folders. It is clearly seen in
the Solution Explorer.
Result II (Code-behind)
One more file i.e. the code behind file is get created. In the code behind file we have the using clauses
at the beginning and a new class has been created called ContactsManage and it has been derived
from the System.Web.UI.Page. Every single page that we have is always going to get derived from
the Page class. Whenever we create a website, it always creates a Default page. That Default page is
also derived from the Page class. So we have added a new Web Form that also stands derived from
the Page class. ContactsManage is the code behind class for the webpage that we have just now added
called ContactsManage. The idea behind having this code behind file is to be able to deal with
different events that occur in a webpage. To be able to handle those events we are proposing to create
a separate web page called ContactsManage derived from the generic Page class.
Page_Load( )
In the Page_Load( ) function, we say ListTable.Rows.Add ( AddHeader( ) ). Header is the 1st row.
We want the contact information as shown in the slide on our webpage. The header is Name,
Telephone and Mobile. The headings are obtained by the AddHeader( ) function. AddHeader( )
function will return us the information which we will then add by calling the Add( ) function. To be
able to call the Add( ) function, we will first say ListTable.Rows. Rows is a property in HTMLTable
class. So ListTable is going to be an object of HTMLTable class. Then we call LoadFromTextFile( ).
This function helps us in reading the text file line by line and as we read each line, we will add its
information into the table.
AddHeader( )
The return type of AddHeader( ) is HtmlTableRow. So finally when we add a new row, it will be
through the Add( ) function of the HtmlTableRow. Inside the AddHeader( ) function, we will first
create an object of HtmlTableRow class. Once this is done, we will also create an object of
HtmlTableCell and then setup the value inside this cell by using c.InnerHtml = "Name". Then we
would try to add it to the HtmlTableRow by saying r.Cells.Add ( c ). Cells is the property of
HtmlTableCell class. The way we have added the name, we can also add the telephone number. For
that we need to first create another of HtmlTableCell and then populate it with the string Telephone
and then we can add it to the HtmlTableRow. Exactly the same way, we may add one more column
containing the string Mobile. So now the header is ready. This header is returned by saying return r.
This will get added to the ListTable.
LoadFromTextFile( )
First we create the ContactList object which is one of the backend classes. Then we call a function
LoadFromFile( ) of the ContactList class. The file which we want to load, we have to clarify it. We
have created ContactsList.txt file in which we have stored information about three contacts. The path
of this ContactsList.txt is made available to the LoadFromFile( ) function. To be able to get the path
of ContactsList.txt, we have to call the MapPath( ) method. Server is the property of the Page class.
Using that property we access the MapPath( ) function. This function retrieves the absolute path of
the ContactsList.txt on the web server. We are saying "~/App_Data/ContactsList.txt" where ~
indicates the root of the website. We created the Contacts website in C:\ASP.NET\Contacts. But we
actually physically deploy this file on the web server; this may not be the path. Whatever is the path
that is assigned for our website, from there onwards we know that inside that particular path there is
going to be App_Data and inside App_Data there is ContactsList.txt. But since we do not know what
is the exact physical path, we just mentioned ~ which indicates root of the website. In this case ~
means C:\ASP.NET\Contacts. So we will pass the path of ContactsList.txt to LoadFromFile( )
function. Then it would be able to load that file successfully. Then we want to go through this file one
after the other contact. Hence we run a loop for that. List is a property that we had exposed. This List
property is used to return ArrayList in which all the contact information is present. When
LoadFromFile( ) stands called, all the contacts that are there in file have been populated inside the
ArrayList. So when we do clist.List we get an access to the ArrayList collection. Using the ArrayList
collection, we use the Count property to come to know as how many contacts right now are present in
the ArrayList. We will run the loop those many times. Each time through this loop, we should add a
new row in the HTML table. To do so, we propose to create a function AddContactRow( ). We pass (
Contact ) clist.List [ i ] to this AddContactRow( ) function.
AddContactRow( )
30 Telephone Contacts User Interface Building Portals Through ASP.NET
In the AddContactRow( ), we are going to receive the Contact information in con. We want to add it
to the HTML table. Create a HtmlTableRow object and a HtmlTableCell object. Now we can
populate the information inside this cell. We say con.name to actually get to the name. Now we try to
add the name of the person to the HtmlTableCell and that cell we are going to add to the
HtmlTableRow. Whatever we do for name, exactly same thing we do for the telephone number and
on the similar lines we will do same thing for the mobile number. Once all has been done, we should
now try to add the row to the HTML table. We can do so by saying ListTable.Rows.Add ( r ).
Step V – Test
For testing, in the Solution Explorer, right click on ContactsManage.aspx. The moment we do so, a
menu shown in the slide would appear and from that select Set As Start Page menu item. Now we can
do Build and run by doing CTRL + F5.
Fruits of Labour!
As soon as we do so, the output that is obtained is shown in the slide. Such a website would appear.
Name, Telephone and Mobile are the headers that we had created. Then the table has been populated
with 3 rows data as shown in the slide.
Building Portals Through ASP.NET Contacts – Professional Style 31
Example
Look at the table that we have shown in the slide. This table contains text like this is line 1, this is
line 2 and this is line 3. This text is displayed in three different lines. In each of these rows, we are
indicating that background color of the text is going to be according to the color number FFCC00.
This is a hexadecimal number. Out of these 6 digits in the hexadecimal number, 1st two digits stand
for the red color, next two digits i.e. CC stands for the green component and 00 is the blue. So red,
green and blue are mixed up to get the final effect of that color. So we are specifying some
Building Portals Through ASP.NET Contacts – Professional Style 33
background color in which this text has to be displayed. Then we are also mentioning that the text be
displayed in Arial font of size 2. Then we are saying that this text should be displayed in red color. So
we also have a foreground color. Then we have this is line 1 displayed in bold face. Some similar
attributes are also being associated with line 2, so also for line 3. Even though it’s a workable HTML
piece, it will show the table according to the desired fonts, desired background color, desired
foreground color, so on. This is not the best way of organizing it because we are trying to mix the
content with the presentation. If we look at that table, we cannot identify what is being displayed
because the text this is line 1, this is line 2 and this is line 3 somehow got lost into that. That
happened because we try to mix the presentation with the content. That we should never let happen.
So we need to separate that. When we separate the content then see the table as shown in the slide
that we follow. It’s very clear that the text that we displayed is this is line 1, this is line 2, this is line 3
and then what style is being used for this text is defined in a subtext class in a CSS file. So the
moment we are able to separate the .htm with .css in that case it’s much easier to present. At the same
time pay attention to the content and pay attention to the details of the style. Because when we are
looking at the cascaded stylesheet, we are concentrating only on the style. When we are looking at the
.htm then we are concentrating only on the content. That way both become more manageable.
Our Requirements
We want the table header to be displayed in different color as compared to the body of the contacts.
Means Name, Telephone number and Mobile number are our headings. They should appear in
different color and the data for that should be in different color. Font of these three titles to appear in
bold. So we want the output as shown in the slide. Page font should be easy to read. To do so, we are
proposing to make use of a Font family called Tahoma, Arial and Verdana. Alignment of the text
should be done in a justified manner.
Steps Involved
First we will create a Style Sheet with name Contacts.css. Then within the .css file, we will have to
define the styles and we are proposing to use two styles head and body. body is used for page and
head is used for header i.e. name, telephone number and mobile. Then we try to apply the styles that
we define in the .css file to the content that we have on this webpage. Then we try to use style
attributes defined in a css file in a programmatic fashion. Finally we would try to compile and test
whether what we intended to achieve has indeed been achieved or not.
Result
When we do so, the Contacts.css file will get created as shown in the slide. A body tag or a body
style stands inserted within the cascaded stylesheet. The menu has also changed. One more option
Styles is also available as shown in the slide. Using this Styles menu, we can add more styles other
than the body style which we have right now. Then we have Contacts.css inserted within our project
as shown in the Solution Explorer.
Result
When we do so, the head style would get inserted in the form of .head as shown in the slide. Inside
this .head style, we need to add background color, foreground color, etc.
Result
When we do so, in the aspx file we can see that besides title there is also a link tag get introduced.
The link tag has certain attributes. For example, one attribute is href. Another is rel and third id type.
These get added in header of our aspx file. <link> tag would be inserted any time, this html that we
have right now is going to be connected with some other external source. In this case the external
source is css file called Contacts.css. Appropriately href value has to be changed. Then we are
indicating the relationship. We are saying that relation is stylesheet and inside the stylesheet we have
text/css which indicates the type of the content. This is also commonly known as MIME type. The
moment we drag and drop the css file on the ContactsManage.aspx, in its header section this link tag
would get introduced and inside it there are attributes like href, rel and type each having a suitable
value.
When we compile and execute this application, the list of contacts that are displayed are more
impressive than what we were able to manage last time around. The moment we were separated
HTML content from the style or layout, it has definitely become more manageable. Not only that we
can easily or effectively apply different styles to different parts of text that are being displayed on this
webpage.
36 Cascaded Style Sheets Building Portals Through ASP.NET
Types of CSS
CSS can be applied in three different ways. One of them through an external style sheet which we
had done in Contacts website. We can also apply the CSS internally. For this we have to make an
entry in the <head> section of the html document. The third method of applying the CSS is Inline tag
method.
External CSS
External CSS we have used for Contacts website. The location of the style rules are done in .css file.
We had created Contacts.css file for this purpose and then through the <link> tag we had applied the
style saying that whatever styles are defined in the .css file they be used for rendering this particular
html document. For example, we can say in the <head> section a <link> tag saying href =
"mystyle.css" where mystyle is the name of the file. Relationship i.e. rel = "stylesheet" indicates that
it stands for a style sheet and MIME type is indicated as type = "text/css". Once this is done then all
the html content in this particular page would be rendered as per the style rules that have been defined
in mystyle.css.
Internal CSS
In the Internal CSS, the style location is still the aspx file or a html file. Application of this is done in
the <head> section and the way to do so is to say within the <head> section <style type = "text/css">.
Then for a horizontal rule hr, we can say that its color is navy i.e. hr { color: navy }. In its body, we
want that the left margin would be 20 pixels i.e. body { margin-left: 20px }. So we define the style
right within the <head> section rather than saying within the <head> section that we are proposing to
make use of an External CSS, right here we define the styles. When we do so, this will be useful only
when a single page requires a unique style sheet because once we declare an external style sheet then
all the pages within that website is going to be rendered using that particular external CSS file. So if
amongst all the pages if we want that one particular page is such that we do not want external style
sheets to be applied to it then for bringing uniqueness to that page we may define styles right within
that html page or the aspx file in the <head> section as shown in the slide using the <style> tag.
Inline CSS
38 Cascaded Style Sheets Building Portals Through ASP.NET
When we use inline CSS with each element we can really apply the style. For example, we may say
<p style = "color: yellow; font-family: verdana"> where p stands for paragraph. If we do this then in
that case this particular paragraph would appear in yellow color and in a font verdana. This is the
least flexible way of applying styles because this works specifically for the paragraph tag wherever it
is being used. Rather than applying this to all the paragraphs, we are applying it for one particular
paragraph within that page. So for every single paragraph, we will apply the same style again and
again. If we really intend to do that then we had lost the advantage of using the css. This is so because
for every single tag if we start applying the style inline in that case the very purpose of using the css
gets defeated. So we should do this, only if we want to carry out overriding of external or internal
styles.
CSS Syntax
In this we have to understand five things i.e. selector, class, id, div and span.
Selectors
Basic syntax for declaring a selector is to say Selector { property: value }. In the example shown in
the slide, we are giving ColHdg as the selector name and text-align: left and color: red are two pairs
of properties and values. This marks the basic syntax of css. Property: value together is also often
known as declaration. We can also think of using the same declaration for multiple selectors. For
example h1, h2, h3, h4, h5, h6 are the standard tags for applying headings. If we so desire, we can
apply color: yellow as the property: value pair for all these different headings. So when we start using
it, we are saying <h1> This is a level 1 heading </h1> and <h2> This is a level 2 heading </h2>. For
both of them, we are going to make use of the yellow color. The sizes of this are come out to be
different but they are all going to appear in yellow color. We can also make use of descendant
selectors. If we want to use descendant selectors we have to declare them by saying P B { color: red
}. We are saying that wherever within a paragraph tag bold is used, it should appear red in color. But
if we just use paragraph then it should not appear red in color. If we want to get this effect then in that
case we can declare descendant selectors by saying P B.
Selector Class
Here the syntax is, for the paragraph tag or paragraph html element, we are proposing to apply
different styles. For example, we are declaring p.right saying that text alignment should be right
whereas when we say p.center then text should be aligned in center. While declaring the paragraph
tag, we are saying make use of a class called right for this particular paragraph. Hence This para will
be right aligned would indeed be right aligned when it gets displayed in the browser. If we say <p
class = "center"> then the text would be centrally aligned means for the same paragraph tag we are
applying different styles. So right and center are known as selector classes. Now if we so desire that
whichever tag makes use of center attribute, for all of them a particular style as defined by .center
should get used. When we say p.center, it applies only to the paragraph tag but if there are other tags
which have a center attribute then for all of them if we want the same style to be used then in that
case we need not declare it as p.center, we just say .center. Here by saying .center, we are saying all
the tags which has center as the attribute for all of them, this particular style i.e. center aligned style
be used whenever the text is displayed using those tags. In the example, we are saying that h1 and p
i.e. two tags are used and for both of them we are saying class = "center". Hence the text that appears
in h1 and the text that appears in paragraph come out to be center aligned because we have defined
.center rather than saying h1.center or p.center.
Selector id
Here we are saying p#firstpara { text-align: center; color: red }. If we are so desire that a particular
paragraph within the html document, it should be applied the firstpara style whereas all other
Building Portals Through ASP.NET Cascaded Style Sheets 39
paragraphs need not have the firstpara style. If we say p.firstpara then every single firstpara or every
single paragraph would have been forced to make use of this firstpara style. If we do not want that
and we want that only limited paragraphs should get this particular style then we can make use of this
selector id. Then we have another issue wherein if we so desire, we can make our style sheet more
descriptive by adding suitable comments to it. These are C style or C++ style comments wherein
within /* and */ combination, we describe any note or remarkable about a particular style. In this case
we are saying /* use this style only for emphasis */.
<div>
<div> allows to create customized block-level elements. The way to declare this is to say
DIV.introduction
{
font-size: 14pt ;
margin: 24 pt ;
}
While using it, we can say
<DIV CLASS = "introduction">
This is a simple introduction to the document
</DIV>
Wherever this division i.e. DIV occurs, this introduction style is get applied to it and whatever are the
properties or styles we defined in the introduction those would become effective for that entire
division.
<span>
<span> allows to create customized inline elements. Suppose we say
SPAN.logo
{
color: white ; background-color: black ;
}
then it’s a style declaration. When we use inline CSS for example, in the paragraph tag we say
<P>Welcome to the <SPAN CLASS = "logo"> KSET </SPAN>Web site. We want that the word
KEST should appear white in color on a black background. So we are applying SPAN.logo to KEST
alone. When we do so, we are doing this inline right where we are using a paragraph tag.
Conflict
We may create a style which is there in external CSS, it’s also there in the internal CSS. In that case,
how this conflict is resolved is we need to appreciate. We also have to remember multiple CSS can
also be included in one html document. If a particular style is there in the external CSS and is also
declared internally in the head section then see how this conflict is resolved. For example, in the
external CSS we might be declaring h3 { color: red ; text-align: right } whereas in the internal CSS in
the head section we are saying h3 { text-align: center; font-size: 12pt }. There is no conflict between
color and font-size because in the internal CSS we did not mention the color and in the external CSS
we did not mention the font-size. In the text-alignment there is a conflict. In the external CSS, we are
saying that text should be right aligned whereas in the internal CSS we are saying that text should be
centrally aligned. Whenever we do this, the resultant style is going to be h3 { color: red; text-align:
center; font-size: 12pt }. Here text-align: center got a higher priority. Now the fact that the two styles
are being combined to create a third virtual style is cascading all about. We cascade several styles
into one virtual style so it is known as a cascaded style sheet. While doing the cascading effect, it
always give the higher priority to the internal CSS over the external CSS. The order in which this
40 Cascaded Style Sheets Building Portals Through ASP.NET
precedence is applied is the lowest precedence is the default that the browser has. Still higher
precedence is to the external CSS, still higher to the internal CSS and then highest precedence is to
the inline style. Means right there at the point of using a particular tag, there if we want to make
certain changes in the style that has the highest priority. Priority moves from left to right.
Benefits Of CSS
CSS is completely rule based. Since it is rule based, it is less error prone. It is very easy to write
descent CSS. It leads to shorter development time. The advantage with external style sheet is that
once we visit a page and the CSS gets downloaded there onwards every time the style elements do
not have to be downloaded. If we apply the styles inline then every single time we go to a page that
inline style will also have to be downloaded. Instead if we download the external style sheet once
then all other webpages if they have been rendered using the same style sheet then downloading of
the style elements get completely eliminated. That is going to lessen the network traffic and improve
the performance. So download once and use often is good with external style sheets. We get much
better control over the placement of elements because we can plan things in advance. We can reuse
the same styles again and again throughout the website.
Summary
CSS has its own simple language. Best way to learn CSS is to start typing to change various
properties and then try to make use of the intellisense that Visual Web Developer offers and try to
build the style sheets. Do not create too many .css files. We should think before we act.
Building Portals Through ASP.NET Contacts Addition 41
Contacts Addition
In this lecture you will understand:
Requirements - Add new contacts
Steps involved
Interaction of all classes involved
42 Contacts Addition Building Portals Through ASP.NET
Steps Involved
First we have to make some changes in the ContactList class. Then in the ContactsManage.aspx page
where we had listed all the contact information that is there in the Contacts text file, there we would
try to insert one more table such that the user is indeed able to enter the new name, new telephone
number and new mobile number for the contact that he wishes to add to the text file. Then we will
also provide a Add button. Once the entries of name, telephone number and mobile number are done,
to confirm that this is the contact information that the user intends to add, we would provide a button.
The moment a button is clicked, its corresponding associated function should get called. That
function is commonly known as a handler and clicking of the button is known as an event. In short
the function that gets called whenever we click on the Add button is commonly known as an event
handler. Then we will have to add the code to this function which facilitates addition of the new
contact into the text file. Once we are done with all these then we want to compile and test the
program.
Write Contacts
44 Contacts Addition Building Portals Through ASP.NET
In the WriteToTextFile( ) function, we will first create a new FileContact object. Once this
FileContact object is created, we will invoke the 1-argument constructor of the ContactList class.
When we invoke this constructor, we need to provide the path of the ContactsList.txt file. To provide
the path, we have to use Server.MapPath ( "~/App_Data/ContactsList.txt" ). ~ will act as root. It will
find out actual full physical path. Now the ArrayList collection is populated with current Contact list.
Then we would try to pick up the values from three text boxes and once this text is picked then if
within that text if there is , then replace it with space. This is important because finally our text file is
going to be a CSV file where we have values separated by commas. Once this is done then we try to
store that replaced name, telephone number and mobile number into con.name, con.telno and
con.mobile. So we say con.name = nameInput.Text.Replace ( ',', ' ' ), con.telno =
telInput.Text.Replace ( ',', ' ' ) and con.mobile = mobInput.Text.Replace ( ',', ' ' ). Then we say
clist.AddContact ( con ). So this new FileContact we passed to AddContact( ), it is going to add to the
ArrayList and the updated ArrayList, it is going to save into the text file.
How It Works
The slide shows the ContactsManage webpage. When we click on this Add button, inside the
ContactsManage class which is our partial class AddButton_Click( ) handler would get inserted.
From this AddButton_Click( ), we call two functions; one is WriteToTextFile( ) and another is
UpdateListTable( ). Both these functions are part of ContactsManage class. WriteToTextFile( ) 1st
going to create new FileContact object and then it proceeds to create a new ContactList object. When
it creates the new ContactList object, to the 1-argumnet constructor we had passed the path of the text
file. That path would be used to load the ContactsList.txt and ArrayList is populated with all the
contact information. Subsequent to this we had called the AddContact( ) function to add the new
contact into the ArrayList and this AddContact( ) function having added a new FileContact into the
ArrayList, it had called the ContactList’s SaveToFile( ) function such that the updated ArrayList
should get saved into the ContactsList.txt file. Then we had called UpdateListTable( ) function of the
ContactsManage class wherein we had just prepared the table and then manage to load all the latest
contact information from the text file and displayed that within the table that was already there.
Difference In Environments
The different environments in which we work are one is the development environment and another is
the production environment. Development environment means we are trying to do the development
of the website on the local machine and production environment means once the website is created,
we deploy it on the web server remotely and then make request to that web server through the client
machine. But to begin with, the server as well as the client both are on the same machine and that is
the development environment. When we have listed the contacts or added new contacts, we did
CTRL + F5. The moment we do CTRL + F5, our ASP.NET application gets build means compilation
and linking takes place and once this is over, automatically the Visual Web Developer launches the
browser i.e. Internet Explorer. Once this browser is launched, it sends request to the startup page of
the local web server. During development phase this is important that the web server is present right
on our machine such that debugging and testing becomes easier for us and a request is made by
default to the page that we have marked as the startup page. So request would be made for this page,
whatever response comes that would be rendered in the browser. But in the production environment,
we do not do CTRL + F5 because CTRL + F5 we will do on our machine but website is not there on
our machine. The website is deployed remotely on the web server. Moreover that website is already
running on the web server. Hence we start our browser and then from our machine i.e. the client
machine we send a request to the ContactsManage.aspx page or any other page that we wish within
the website can be invoked by giving the aspx filename for that particular page. So send the request
to ContactsManage.aspx because we had set ContactsManage.aspx as the startup page. Hence in the
development environment that’s the one that would get requested from the web server whereas in the
production environment we can make a request to any of the pages. We would usually want to make
a request to ContactsManage.aspx page. There is a Request – Response model is used. We send the
request and then the response comes back from the web server and that response is always in the form
of HTML. That response is properly displayed within our browser.
Difference In Requests
When we make these requests, for listing we just make a request; we are not going to send any data to
the server for that. As against that, imagine if we are going to do addition, searching or deletion, we
will have to pass data to the server. For example, while adding we will have to say that add this
particular data to the existing contact list. When we want to search a contact, again we will have to
send some information saying that this contact we want to search or when we wish to delete, again
Building Portals Through ASP.NET Get And Post Requests 47
we will have to pass the contact information saying that this particular contact is being deleted from
the contact list that is maintained on the server. Means in addition, deletion and searching, data has to
be passed to the server whereas when we are listing, we are not sending any data to the server. So for
listing we will make use of a HTTP Get request whereas for addition, searching and deletion, we will
make use of a Post request. These are two very commonly used HTTP requests.
differentiated whether it’s going to be a GET request that is going to happen or a POST request that is
going to happen. When we make the request, in the aspx page the method is written. If its method =
GET then a GET request is made. If its method = POST then a POST request is made.
URL Anatomy
In the URL http://localhost:1827/Contacts/ContactsManage.aspx, http:// stands for the protocol that is
being used for making the request. It can be ftp:// or file://. It all depends upon which protocol we are
using. After http://, we are giving the name of the server. localhost means the local machine or
development machine. In place of localhost there might be a name of the machine which is the
remote machine where the websites stand deployed. Then we have the port number which in this case
is 1827. Then we have /Contacts/ContactsManage.aspx which indicates the location of that webpage
on the web server.
Deletion Steps
When we carry out deletion, it’s a collection of requests and not only one request. For example, we
would type out the URL in the browser. When we do so, it will be a GET request. The page would
get loaded. What is going to be loaded into the page is going to come as a HTML response for the
GET request that we made. So when we are carrying out the deletion 1st we are going to show a list of
existing contacts. To get that list of existing contacts, we just have to type out the URL of
ContactsManage.aspx. That would become a GET request and its response will be rendered in the
browser. Once that response comes, if we decide to delete a particular response, we must first search
whether it is there or not. To do that, we will have to make a POST request. When we make a POST
request, a response would come back which would indicate the result of the search that we had tried
to initiate. Means we are trying to delete a particular contact, if its name is present or if its telephone
number or mobile number is present, it would be displayed to us before we go ahead with the
deletion. But if the contact that we are trying to delete is not there in that case a suitable response will
have to be send to the client saying that such a contact does not exist. Means for searching also we
have to make a POST request and then get back a POST response. Once that is over, we are going to
click on the Delete button. That time also a POST request would be send because here too we want to
send data that this particular item be deleted from the contacts list. Hence for that request a POST
Building Portals Through ASP.NET Get And Post Requests 49
response is come back to us. So we are talking about one GET request and two POST requests. This
is a scenario where there is a multiple request-response interactions are happening on the same
webpage. There must be an ability to correlate these different multiple request-response interactions.
To do so, ASP.NET provides a concept of sessions. HTTP is a stateless protocol. If there are multiple
requests that are happening then there is no way for us to ensure that our information is remembered
on the server when we make the next request i.e. when we make the 2nd request, information about
the 1st request is never going to be maintained by HTTP protocol. But that is a requirement. In our
example, there are multiple POST requests coming from the webpage and we want that when we
make the 2nd request, something about the 1st request should be memorized on the server. To provide
this facility, ASP.NET provides a concept of sessions. This session is able to remember things across
multiple POST requests that we make.
Types Of Requests
Apart from the GET and POST request, we also have HEAD, OPTIONS, DELETE, PUT and
TRACE requests. GET request’s job is to fetch a document from the website whereas POST is used
for sending the data. HEAD is used to get only the header information and not the body of the
response. When the response comes back, header as well as the content comes. If we want to get only
access to the header then we have to make use of the HEAD request. Then there is a OPTIONS
request. When we use OPTIONS request, we can come to know what different types of requests are
being supported for a particular application. DELETE deletes a particular resource or a document
from the given website whereas PUT puts a resource or a document on the given URL. TRACE is
used to figure out the request that we are sending to the server, if is not going to the server, if it is
passed through several proxy servers or gateways, in that case is our request going to get modified
before it finally lands with the web server or not, if that we want to figure out that time we want to
make use of a TRACE request. It is kind of a loop back. TRACE request is useful in debugging if
something is not working for the website. These many requests can really be made.
Delete Contacts
In this lecture you will understand:
Delete existing contacts
Steps involved
What are sessions
How are they managed
Building Portals Through ASP.NET Delete Contacts 51
Steps Involved
First we will have to update backend class i.e. the ContactList class. Then we will try to insert Search
and Delete Buttons within the webpage i.e. ContactsManage.aspx. Once the buttons are created, we
will try to provide event handlers for these buttons. Once these event handlers are created, we will
have to add code into these event handlers. Finally we will build and test whether this webpage is
working all right according to our expectations or not.
Contact to be deleted:, we once again put two blank lines using <br /><br />. Now we would put a
label by saying asp:Label. The way there is a button control, similarly there is a Label control. We
will give an ID as DelContact and make it a server side control using runat = "server". Whenever the
search is over, if the search is successful, the information about the contact that is to be deleted
should be done on this particular label. Subsequent to that, we want the Delete button. To get that
Delete button, we once again leave two blank lines. Then we have asp:Button tag where ID is
DeleteButton, text is Delete and set runat = "server". We will also set Enabled = "false" because to
begin with, we do not want this Delete button to be available for selection and we can ensure that by
saying Enabled = "false". Later on we will enable it. By enabling, it will not appear gray in color. So
it will be available for selection. As shown in the slide, the Delete button is disabled.
When the use clicks on the Delete button, this DeleteButton_Click( ) handler would get called. The
same parameters are received in the DeleteButton_Click( ) button handler. Inside this we now try to
make use of the information that is saved in the Session object and we can retrieve that by saying
Contact oldCon = ( Contact ) Session [ "contact" ]. Session we can treat it as if it’s an array and
contact becomes an index to that array. Whatever is stored in Session object is collected in oldCon.
Then we create a new ContactList object then try to load the existing contacts that are there in
ContactsList.txt by calling the LoadFromFile( ) method. Once the ArrayList has been populated with
existing contact information, now we can call DeleteContact( ) method in the ContactList class by
saying clist.DeleteContact ( oldCon ). The change that happened in ArrayList has to be reflected in
our webpage. To do so, call UpdateListTable( ) method. Then we say AddTable.Disabled = false i.e.
the table is enabled. User should be able to add new information or should be able to carry out new
search. Then make the Delete button disabled i.e. DeleteButton.Enabled = false. Then the text which
is written on the label is to be emptied using DelContact.Text = "".
Search Results
When we click on the Search button, Search button handler would get called. This handler would
search for Rajesh contact and then try to display that information below Contact to be deleted:. In the
label the information about Rajesh now would appear. Now the Delete button is enabled. Search table
is now disabled. To delete this contact, we will now click on the Delete button.
Updated contacts
When we click on the Delete button, the Delete button handler would get called. We had deleted this
particular contact whose information is kept in the session. Now as shown in the slide, the Rajesh
contact has been deleted from the contact list and there are only two contacts remaining in the list.
54 Change Contacts Building Portals Through ASP.NET
Change Contacts
In this lecture you will understand:
Change existing contacts - requirements
Change existing contacts - procedure
Building Portals Through ASP.NET Change Contacts 55
Steps Involved
First we will update the backend class called ContactList. Then we would try to insert a new table
along with a button. We will call this table as Edit table wherein the user should be able to make
changes in name or telephone number or a mobile number and once the editing is done the user
should click on the Save button. All these insertions of the suitable tags for the ASP.NET control is
done within ContactsManage.aspx file. Then we will also have to suitably enable / disable the Edit
table after the searching or the deletion. Then we would try to add save event handler. Once the event
handler is ready, we will put code into it to carrying out actual saving of the contact list. Finally build
and test whether the functionality is being implemented as per our expectation.
All Done!
Building Portals Through ASP.NET Change Contacts 57
As soon as we click on the Save button, the Save button’s handler is going to get called. Within the
Save button handler, we had updated the ArrayList and we had also made changes in the
ContactsManage.aspx page such that the modified name should appear in the recent contact list. So as
shown in the slide, the changes are reflected in the contact list.
58 XML Contacts - I Building Portals Through ASP.NET
XML Contacts - I
In this lecture you will understand:
Understanding XML
Important XML terminologies
Using XML file to store contacts
Important XML classes
o XmlReader
o XmlWriter
Building Portals Through ASP.NET XML Contacts - I 59
What is XML?
XML is an eXtensible Markup Language. In XML, we can create our own tags whereas whenever we
are using HTML, we are restricted to using the standard tags that are made available as per the
HTML standard. In XML, the format in which we layout these tags is a text format. It contains
different tags the way HTML document has. Only thing is that we can decide the tag names. XML
provides a very easy way to exchange data between different modules of the applications or from one
application to another. It’s a standard which has been created by World Wide Web Consortium.
Hence it’s a universally acceptable standard. Then we make use of readymade classes that are present
in the .NET Framework Library to read/write XML files. It’s extremely easy to learn and use. Entire
World has embraced XML to a great extent whenever there is need to exchange data.
Steps Involved
60 XML Contacts - I Building Portals Through ASP.NET
Since many things are common from the Contacts project that we had created, 1st this we need to
copy Contacts project into a folder Contacts_xml. Then try to create an empty XML file. Do not
populate it by hand. Then we create XML reader/writer class and its name is XmlContact. Then
suitably update the ContactList class to be able to load a XML file, save an XML file i.e. we need to
add XML load/save functions to ContactList. Then make changes in ContactsManage.aspx.cs. Within
the webpage, we will have to make changes in all the handlers that we had written i.e. Add, Save and
Delete contact handlers. Then we will have to replace the FileContact class with XmlContact class.
Then loading and saving calls for a text based file, those calls also we will have to change for
corresponding XML related file.
ContactsList.xml
When we do this, an empty XML file will now get created which is shown in the slide. In this file,
there is a declaration at the top which contains XML version number and the encoding that this
document makes use of. By default this line has been inserted by the wizard in ContactsList.xml. We
need to add the root element here i.e. <contacts></contacts>. This we have to type by hand. Inside
this, what is to be populated, we have to do that in a programmatic fashion.
XmlContact
At the top we say using System and using System.Xml. XmlReader and XmlWriter classes would
become available to us only when we import System.Xml namespace. This XmlContact class is
going to be derived from the Contact class. Inside this class we try to declare constant strings i.e.
const string contactStr = "contact", const string nameStr = "name", const string telStr = "telephone"
and const string mobStr = "mobile". We want to create tags and we are trying to give names of these
tags contact, name, telephone and mobile which we are storing in four constant strings. const
indicates that these strings are unchangeable. These correspond to the XML element that we intend to
create within the XML file. Then we have a 0-argument constructor which right now is kept as
empty.
Slide 11
Building Portals Through ASP.NET XML Contacts - I 61
LoadFromXml( ) function will read a contact information from the XML file. To be able to carry out
that reading, XmlReader object will be passed to it. Whichever XmlReader object will be passed to it,
using that it will try to read a contact from the XML file. Our contact is organized in an XML file in a
manner as shown in the slide. Within <contact>, we are going to have <name>, <telephone> and
<mobile> elements. We want to read the contact information of only one contact and then go back
from this LoadFromXml( ). We will begin with bool ret = false. This indicates the return value of
LoadFromXml( ) function. Then using the XmlReader object that this LoadFromXml( ) function
receives, we will start reading the XML file. So long as xr.Read( ) returns true till that time this loop
should continue i.e. the loop is while ( xr.Read( ) ). Inside the loop we would check that the node at
which we are present right now is it an element or not i.e. if ( xr.NodeType ==
XmlNodeType.Element ). NodeType is a property of the XmlReader class. XmlNodeType.Element is
an enumeration. If it is an element then we should try to access name of it. Then we check if (
xr.Name.ToLower( ) == nameStr ). Name is a property of the XmlReader class which returns the
string present in that node. If it matches with nameStr then we say m_name = xr.ReadString( ) i.e.
read the value present inside that name element and ret = true. m_name is a property which is
available to the XmlContact class. m_name property was declared in the Contact class which we have
inherited in this class. If it is not name then check whether we have come across a telephone element
or not i.e. else if ( xr.Name.ToLower( ) == telStr ) and if it is then say m_telno = xr.ReadString( ). If
it is a mobile number i.e. else if ( xr.Name.ToLower( ) == mobStr ) then say m_mobile =
xr.ReadString( ). Then we check else if ( xr.NodeType == XmlNodeType.EndElement &&
xr.Name.ToLower( ) == contactStr ) i.e. we are finding out that the node at which we are present is it
an element or not. If it is an element and if it happens to be the contactStr means have we reach the
end or not. If we have reach the end of that contact then break. Finally return the value present in ret
using return ret. So we are going to read one contact information any time LoadFromXml( ) is called.
Slide 12
To create an XML document, we will have a WriteToXml( ) method and it expects XmlWriter object
to be passed to it. Firstly we say, xw.WriteStartElement ( contactStr ) which will create the element
<contact> within the XML file, the file which is associated with the XmlWriter object and whose
reference has been passed to WriteToXml( ). Then we would write the <name> element by saying
xw.WriteStartElement ( nameStr ). Inside that <name> we propose to have Mansoor Shaikh which
can be written using xw.WriteValue ( this.name ). Then we would write the </name> element by
using xw.WriteEndElement( ). To write <telephone> tag we say xw.WriteStartElement ( telStr ),
write value of telephone using xw.WriteValue ( this.telno ) and write </telephone> tag using
xw.WriteEndElement( ). Finally we want to write the <mobile> tag which is written using
xw.WriteStartElement ( mobStr ), value of mobile is written using xw.WriteValue ( this.mobile ) and
the </mobile> tag is written using xw.WriteEndElement( ). Lastly to write the </contact> tag, we
once again say xw.WriteEndElement( ).
62 XML Contacts - II Building Portals Through ASP.NET
XML Contacts - II
In this lecture you will understand:
Updating ContactList class
Updating ContactsManage class
Build and Test
Building Portals Through ASP.NET XML Contacts - II 63
ContactList – LoadFromXmlFile( )
Inside the LoadFromXmlFile( ) function, we have a XmlReader reference xr which is set to a value
null. Within a try block, we will try to create a XmlReader object by saying xr = XmlReader.Create (
m_path ). Then in an infinite while loop, we should create a new XmlContact object. Once the
XmlContact object is created, store its reference in XmlContact con. Using con, call the
LoadFromXml( ) function which is present inside the XmlContact class. We check if ( !
con.LoadFromXml ( xr ) ) and if it is then break. The contact information that is read using
con.LoadFromXml( ), we will try to add that to our ArrayList by saying m_list.Add ( con ). In
ArrayList, we are going to maintain several contact objects. For the try block, we may or may not
have a catch block. Now we will have a finally block. finally goes to work whether an exception
occurs or does not occur within the try block. In the finally block, we check if ( xr != null ) and if it is
then close the reader by saying xr.Close( ). m_list.Add( ) is going to maintain the ArrayList of
XmlContact objects.
have to save this updated contact information present in the ArrayList in the XML file by calling
SaveToXmlFile( ) function.
ContactList – SaveToXmlFile( )
Into SaveToXmlFile( ) function, we have to write the contact information that includes the contact
within which we have name, telephone number and mobile number. First we would create an object
of XmlWriterSettings and once this object is created its reference is collected in variable settings.
Then we create a reference xw of XmlWriter which is set to null. Inside the try block, we would set
the Indent property of the XmlWriterSettings object to true. Unless we set this Indent property to
true, we find that if we write the XML tags into the XML file, all of them would come in same line.
But we do not want that. We want that the contact information should get stored in the file in a
readable fashion to ensure that we have to mark Indent property to true. Then we will create a
XmlWriter object using xw = XmlWriter.Create ( m_path, settings ). Then we say
xw.WriteStartElement ( "contacts" ). So <contacts> get written into the XML file. Then we will
iterate through the ArrayList by finding the number of elements in it, those many times. Number of
contact information in the ArrayList can be found using m_list.Count property. Inside the for loop,
we would first extract the information about the XML contact from m_list i.e. we say XmlContact
con = ( XmlContact ) m_list [ i ]. Then we call con.WriteToXml ( xw ) which will write the contact
information into the XML file. Then we will have to put </contact>. So we say
xw.WriteEndElement( ). Then we can flush out the writer by saying xw.Flush( ). In the finally block,
we check if ( xw != null ) and if it is then we say xw.Close( ).
ContactsManage – Page_Load( )
In this method, we are going to add three columns by calling AddHeader( ) function. So we say
ListTable.Rows.Add ( AddHeader( ) ) which adds a header but addition actually happens through the
AddHeader( ) method. Then we call a function LoadFromXmlFile( ). In the ContactsManage.aspx.cs
file, we have to import System.Xml. The LoadFromXmlFile( ) function creates a new ContactList
object. We pass the path of the XML file to that ContactList object. Then it will iterate through the
list and each time through that it will call AddContactRow( ) method i.e. AddContactRow ( ( Contact
) clist.List[ i ] ). So as many items are there those many times a new row will get added through the
AddContactRow( ).
In the WriteToXmlFile( ) method, we first create a new XmlContact. Then create a new ContactList
object and pass path of the XML file to that. Whenever we give / Windows convert it to \. If we write
the path using \ then we will have to provide \\ otherwise it will create a problem. Once that is done,
we will try to pick the values from the three fields i.e. textboxes and if within those textboxes, if there
are commas then replace them with spaces. Now the contact is ready. We should add this contact first
to the ArrayList by calling AddContact( ) method which updates the ArrayList and the updated
ArrayList is also going to save into the XML file. The UpdateListTable( ) first clear out all the
information that is there in the ListTable. Once the existing contact information is cleared from the
ListTable, now we are going to populate it. For that first we need to add the header and after that we
have to load the XML file by calling LoadFromXmlFile( ) method. LoadFromXmlFile( ) method read
the XML file and populate this ListTable.
All Done!
When we test this, we will get a table shown in the slide. One table shows the existing contacts,
another the AddTable and the EditTable but the EditTable is not visible because it will become
visible only when search is over.
66 Contacts Revisited Building Portals Through ASP.NET
Contacts Revisited
In this lecture you will understand:
Working of ArrayList
How is it different
Recap of Contacts and Contacts_Xml
Steps involved in List, Add, Search, Delete, Modify
Building Portals Through ASP.NET Contacts Revisited 67
Operations
The operations that we carried out are Listing, Addition, Searching, Deletion and Modification. All of
these make use of the ArrayList. ArrayList is used to maintain the contact information in memory but
whatever is present in memory is not enough because ultimately any information unless it is stored in
a consistent and proper state on a disk, we would never be able to retrieve it back. Means we got to
persist the information present in the ArrayList onto the disk. In the websites that we created we did
manage to write that information into the txt file or the xml file. When we created Contacts website,
that time we had used ContactsList.txt to persist the information present in memory in the ArrayList
onto the disk in the file ContactsList.txt. When we created the Contacts_Xml website, that time
ArrayList was same but this time instead of writing the information about the contacts in a text file in
a comma separated pattern, we decided to make use of the data standard i.e. Xml standard to write
information into an XML file. We did manage to read this information back from the XML file and
we also populate the ArrayList with this information and carried out variety of operations on that
particular ArrayList.
ArrayList
ArrayList is a collection of either a FileContact objects or XmlContact objects. The ArrayList is
wrongly construed as a collection of objects whereas if we look carefully the ArrayList really is not a
collection of objects. It is collection of references of these different objects. So in ArrayList, in each
individual slot, reference of an object is stored. In Contacts website, each reference was a reference to
a FileContact object whereas in Contacts_Xml website each reference was a reference to a
XmlContact object. Each element is of the type reference to an object. We created the Contact class
in both websites. From that we derived FileContact object or an XmlContact object. But the Contact
class itself is derived from another class and name of that class i.e. the base class is Object rather than
a class. All datatypes in .NET are derived from the Object class. So from Object, Contact is derived
and from Contact either FileContact or XmlContact is derived. So the ArrayList collection class is
able to hold sometimes the FileContact objects and sometimes the XmlContact objects because in a
base class reference we are always allowed to store address of a derived class objects. This process is
known as upcasting of that reference. So ArrayList is a collection of upcasted reference. We can store
references to any objects within the ArrayList. That is the reason why whenever we tried to extract
from the ArrayList, we are always required to cast what we have extracted suitably. ArrayList is
somewhat different than the array means we can access its element using an index. ArrayList has a
special property whereby it can increase in size or decrease in size as per the requirement which is not
possible with a conventional array. In conventional array, we have to always mention the size of the
array upfront and once this size is mentioned, there onwards during course of execution of program
there is no question of increasing the size of the array or decreasing the size of the array. So
expansion and shrinking is not possible in normal array, its possible in case of ArrayList which
makes it special.
Operations On ArrayList
The two operations that we performed in building of these two websites, Contacts and Contacts_Xml
website were addition of a new contact into the ArrayList or removal of an existing contact from the
ArrayList. Add( ) and Remove( ) functions receive an argument of the type Object o. Means we
might pass it a FileContact object’s reference or a XmlContact object’s reference but Add( ) and
Remove( ) are going to access that reference into a pointer to the base class or a reference to a base
class. Suppose we have an ArrayList where we have already addresses or references of different
XmlContact or FileContact objects. If we decide to add one more XmlContact or FileContact object,
firstly that XmlContact or FileContact object needs to be created and reference of this particular
object will have to be passed to the Add( ) function. ArrayList class has one of the member variable
which keeps track of how many elements have been filled in this ArrayList. No sooner we had passed
68 Contacts Revisited Building Portals Through ASP.NET
to the Add( ) function the reference to a FileContact or XmlContact object, it will increment that
count and then in the next empty slot present in the ArrayList, it would try to store the reference to
this new XmlContact or FileContact object. Every single time we add a new element to this
ArrayList, that time the ArrayList does not grow because that would be quite inefficient. For example
the ArrayList grows by multiple of 5 slots. Means this is commonly known as a grow size. Means
suppose that any time the grow size is 5 then the moment we create the 1st contact object and try to
store it in the ArrayList, the ArrayList will create 5 slots. Out of that we will consume only the 1st.
Till the time we make next 4 requests, there is no need to increase the size of the ArrayList. But the
moment all the 5 slots have been consumed, if we try to add one more i.e. the 6th XmlContact or
FileContact object to the ArrayList, at that time the ArrayList size would expand by 5 elements or it
will expand by whatever is the value of grow size. This is all about the addition of new XmlContact
or FileContact object to the ArrayList is concerned. Now we want to perform elimination of an
existing contact from the ArrayList and for that the Remove( ) function is used. We may ask it to
remove a XmlContact or FileContact object but Remove( ) function is always going to receive these
reference to XmlContact or FileContact objects into a Object reference i.e. o which is once again
going to be an upcasted reference. Suppose we decide to carry out deletion of the 3rd contact present
in the ArrayList. The moment this 3rd contact is to be removed by calling the Remove( ) function, the
Remove( ) function makes sure that 3rd reference in the ArrayList becomes null. The moment it
becomes empty, the XmlContact object or FileContact object will not be pointed to by any reference.
So next time the Garbage Collector present in the ASP.NET runtime will immediately eliminate this
XmlContact or FileContact object because nobody is referring to that object. So that object is
eliminated from memory. It is known as Garbage collection. If the 3rd contact gets deleted then that
slot will fall vacant in the ArrayList. Hence the ArrayList implementation is done in such a manner
that anytime a slot falls free, elements to the right of that slot automatically pushed to the left. Means
left shifting takes place anytime the element goes away from the list.
Addition
When we carried out addition of a new contact, we had three text boxes in which we could type the
information and once that information about name, telephone number and mobile number was typed,
we had to click on the Add button. When we clicked on the Add button, the ContactsManage class’s
AddButton_Click( ) handler get called. This function inturn call two more functions; one was
WriteToTextFile( ) and another was UpdateListTable( ). WriteToTextFile( ) became
WriteToXmlFile( ) in the XML based contacts book. WriteToTextFile( ) inturn created a new
FileContact object. In case of WriteToXmlFile( ), it must have created a new XmlContact object.
Once the FileContact or XmlContact object is created, we also manage to create a new ContactList
object. To create a new ContactList object, we must have invoked the constructor. The constructor
manages to load ContactsList.txt or ContactsList.xml whatever the case may be. Having done that the
WriteToTextFile( ) having read the ContactsList.txt or ContactsList.xml, it tried to replace commas
with spaces in the new contact that we must have typed within the three textboxes in the webpage.
Once that is done the ContactList’s AddContact( ) function got called. AddContact( ) added a new
contact to the ArrayList which get appended to the existing contact in the ArrayList. After updating
the ArrayList then we manage to call the ContactList class’s SaveToFile( ) or SaveToXmlFile( )
function to save the data that is in the ArrayList now in either the txt file or in the XML file. The
information that is been written to the XML file, it should also try to update that information on the
webpage. To carry out that updation, we had called UpdateListTable( ). UpdateListTable( ) had
prepared the table and then it manage to call LoadFromTextFile( ) or LoadFromXmlFile( ) to load the
contacts from the disk into the ArrayList and then manage to populate all of that within this
ListTable.
Search
We have typed out the name of the person to be searched in the 1st textbox out of the three textboxes.
No sooner we click on the Search button, the SearchButton_Click( ) of the ContactsManage class i.e.
button handler got called. When this button handler got called, it created a new ContactList object. As
soon as the new ContactList object is created, the 1-argument constructor of the ContactList class is
used to invoke and then we have to pass the name if the txt file or name of the XML file to this
constructor. It used to load the contents of the txt or XML file into the memory and then populate the
ArrayList. Once the ArrayList is populated with existing contact information, we call the ContactList
class’s Search( ) function. This Search( ) function might either be successful or unsuccessful.
Assuming that it is successful, the contact information that is searched used to get displayed in a
label. Then we manage to store the search contact reference in Session object. Once that is done, we
manage to call the ContactsManage’s ShowEditTable( ) function such that the information that was
shown in the label also got displayed in this EditTable. ShowEditTable( ) displayed the searched
contact information in the EditTable. Means what is searched is displayed in the label, it also got
displayed in the EditTable. So EditTable is populated only with a motive to edit the information.
Delete
As shown in the slide, we have searched for a name Rajesh and in the label, we have displayed
Rajesh Diwan, his telephone number and mobile number. Subsequent to this, once the information is
shown in the label and the user actually decides to delete this particular contact, he would click on the
Delete button. As soon as he clicks on the Delete button, the Delete button’s handler i.e.
DeleteButton_Click( ) got called. It tried to create a new ContactList object. The constructor manages
to load the ContactsList.txt or ContactsList.xml file. Whatever information we had stored in the
Session about the contact that is to be deleted, that object would be retrieved from the Session object.
Once that information is retrieved from the Session, we manage to call ContactList class’s
DeleteContact( ) function. DeleteContact( ) function search for the contact that was retrieved from the
Session in the ArrayList and we called it as old contact. The searched contact is eliminated from the
ArrayList. The updated ArrayList then got finally saved into the disk by calling either SaveToFile( )
70 Contacts Revisited Building Portals Through ASP.NET
or SaveToXmlFile( ) function. Once this is done, it should also get deleted in the webpage. Hence we
called UpdateListTable( ) which updated the ListTable by first putting the columns in place and then
calling the LoadFromTextFile( ) or LoadFromXmlFile( ) to read the current contact information and
display it in the ListTable.
Modify
If we have searched for a particular contact, it will get displayed in the label. It will also get displayed
in the EditTable. Once the EditTable is shown, the user may click on the Save button. No sooner does
he do that the SaveButton_Click( ) handler in the ContactsManage class would get called. This
handler created a new ContactList object. Then it retrieved the old contact information from the
Session and then manage to call the UpdateContact( ) function. Loading or populating the ArrayList
was done by the constructor which manages to load the txt file or XML file. Now the ArrayList
stands populated. Information about the existing or old contact that has been retrieved from the
Session. Then UpdateContact( ) manages to search update and then save the updated list into the disk
by calling SaveToFile( ) or SaveToXmlFile( ) function. Lastly UpdateListTable( ) prepares the
column headers and loaded the information from the text file or the XML file and displayed it in the
ListTable.
from the ArrayList. To do that a search is carried out. But when we carry out the search, we are
searching for what that has to be clear and that can be retrieved from the Session because Session
object is indeed pointing to the contact object which we had searched successfully. This contact
object is compared for with every single object that is there in the ArrayList. Once this retrieval has
been done, the searched contact is deleted or modified. Then the updated ArrayList is saved to file.
Subsequent to that the page object would die, the ArrayList and ContactList object would also die.
The Session object is left in memory being referred to by page objects of other clients.
layer is the persistence layer or a backend layer or a data layer. This data layer makes use of a
relational database i.e. RDBMS. There are different implementations of this relational database. One
of which is carried out by Oracle. Another has been carried out by Microsoft’s SQL Server. Then
there is open source implementation in the form of MySQL. Out of all these, Oracle implementation
is possibly the best. So, different implementations of this RDBMS is done by different companies.
Even though the implementations are different, the mechanism to use these different implementations
remains same. We as programmers do not have to bother about how Oracle actually manages to store
the data internally or how MS SQL manages to store the data internally. We have to look at the
access mechanisms and these fortunately are standard. No matter what exactly is the implementation
of the database. Communication that is carried out between different tiers, that we can never bypass a
tier. Separation of layers ensures a good design for the application. If we separate our logic into these
different layers, it’s much easier to manage the overall application.
separation of concerns is happening. The moment we have separated the concerns and assigned the
efficiency to each of these software pieces, the overall web application performance is bound to be
good. Typically in database applications we can build variety of things. For example, a bank carries
out the financial transactions using database applications. In airlines website, we carry out online
reservations or we have access to schedules of airlines. We can also keep track of which flight has
originated from which place at what time. All this information is available on websites. eCommerce
websites where online stores are there where we can go and purchase different products. In
manufacturing databases have large role to play. In typically an automobile company, there would be
100s and 1000s of components that go into manufacturing of an automobile. There might be spares of
different machine that are involved in the manufacturing process. So inventory of products that are
being produced, the stores information has to what different parts are there in the stores, issuing of
that to the Production or manufacturing department, taking it back, issuing tools, issuing different
materials which are necessary for helping in the production of the end product, all that information
ultimately has to be stored in a meaningful manner and for that database management system is used.
In HR departments of companies where people keep track of the employee records or their salaries or
their skill sets, when did they join the company, what is their experience level, how much they have
gained in this company, all this information can easily be managed by using a database management
system. These are some examples of the DBMS. There are other 100s of application also present in
real life.
columns and rows. For example, we may have a Contacts table containing three columns, Name,
Telephone and Mobile. Then there would be rows which will have different data. That is how a
database is logically organized in the form of one database having multiple tables and each table
having rows and columns. Columns indicate the items of information whereas rows containing the
actual data against those items.
Communication With DB
There are three things that we need to consider when we want to communicate with the database.
First is how do we connect to the database. There are two ways to do so. If our database server
software is at a remote place then we carry out the connection using a TCP/IP connection. That is a
flexible way of doing it because once we are doing it over the network from which physical machine
we connect it does not matter. So in that sense, it is more flexible. That’s why through the web
browser that is present on different machine, we connect to web server and that web server present on
2nd machine connect to the database server that is present on the third machine. During development
when the web server and the database server are present on the same machine, the communication
happens using a technology known as Named Pipes. When named pipes are used, replication of data
gets avoided as it gets copied from source to target. Once we try to establish the connection,
whosoever is going to get connected he has to be authenticated. Whether such a person is an authentic
user of that database or not has to be verified. For doing credential check, are we allowed or are we
not allowed that can be figured out using the username and password that we use for logging into
Windows. When we do that, it is known as Windows Built-in way of authenticating. As against this
we nay also try to connect to the database server by passing the username and password to the SQL
server and SQL server internally maintains a table of valid users and their passwords. So every time a
user connects along with his username and password, it would be figured out whether is this an
authenticated user or not. Once that is done, we have to now start communicating with the database
and to do so, different commands are to be used. Earlier different commands are used for different
database servers to be able to retrieve the data or store the data in a database. Now all of that has been
standardized in the form of a Structured Query Language or SQL. There are some non-standard
extensions to SQL also available.
Class Organization
When we propose to create the SQL database based contact book, we must be aware of what different
classes are we proposing to deal with. The slide shows two figures with the help of which we can
compare SQL based contact book with the XML based or text based contact book. When we created
those contact books, we used to have a contact class which merely had protected strings standing for
name, telephone number and mobile number and then we had properties through which we can set
values into these or retrieve the current values through those properties. So we have get and set
clauses within those properties. From the Contact class, we had derived a FileContact class or an
XmlContact class. FileContact and XmlContact would be able to read one contact information from
the contact book or write one contact information into the contact book. Then we had a ContactList
class which could do this for multiple contacts and in the process of doing so, it did make use of the
FileContact or XmlContact class to read or write one record into the XML file or text file.
ContactList used to maintain a list of contacts. It also used to manage a list of contacts in memory
using a variable of the type ArrayList. We had a ContactsList.txt file or ContactsList.xml file where
the contacts were stored in a persistent fashion. This all became the backend logic. To interact with
this backend logic, we had created a Webpage which had ContactsManage as the class within it
which we had derived from the Page class. ContactsManage had different helper functions and the
button handlers. For example, we had a button handler for Add, Search, Delete and Save button.
ContactsManage become a front end. In our SQL based contact book, more or less things are similar
except for FileContact or XmlContact class now we propose to have a SqlContact class and in place
of file ContactsList.txt or ContactsList.xml, we are going to have a Contactsdb.mdf file. SQL
database files are always stored with .mdf extension. So ContactList and ContactsManage we are
going to change in this project whereas we are going to derive a SqlContact class from the Contact
class and we are going to create this class completely newly. As we had copied Contacts project into
the Contacts_Xml folder, likewise we can copy Contacts_Xml project into a new folder wherein we
can have a copy of Contacts_Xml and then try to make changes in it.
Steps Involved
1st thing is we have to copy everything. Subsequent to that, we are going to create a database and a
Contacts table inside that database. Then we will create a SQLContact class which is derived from
the Contact class. Subsequent to that we will update the ContactList class which is a backend class
and which is going to maintain a list of contacts for us. Then we will update ContactsManage class
which is the front end class.
Result
Now as shown in the slide, on the screen we would start noticing a Database Explorer is come up in
place of Solution Explorer. In the Database Explorer, we can notice that there is a ContactsDB.mdf
entry already present. Several items are present here. In ContactsDB.mdf, we can create database
diagrams. Means when we create multiple tables, what all tables in the database, what is the
relationship between those tables, all of that can be depicted in a pictorial fashion using the database
diagram. In the Tables branch, we can notice all the tables that we would create in a database. So if
80 Contact Book Using Database Building Portals Through ASP.NET
we create one table then it goes into this Tables entry. Then there can be Views, Stored Procedures,
Functions, Synonyms, Types and Assemblies. Select Tables from here. Then right click on that.
Select Add New Table from the menu that pops up.
Slide 7
The moment we select Add New Table, the screen would change. On the screen a window would
appear in which we have Column Name, Data Type and Allow Nulls as three columns. We propose
to create three columns in our database. We know that within a database there are going to be
multiple tables. We are going to create a 1st table. It asks how many columns we are proposing to
have within the table. We propose to have three columns; one for Name, another for Telephone
number and 3rd for the Mobile number. Each of these columns has certain properties. For example,
each column will have name. Then each column will have some or the other type. Type would
indicate what kind of data we would store under this particular column. Allow Nulls indicate should
we allow a Null entry within that column or not. For that the checkbox is given. If we click on that
checkbox then in that case a null value will be allowed in this column. Means whenever we add a
new row to the table, will this column be allowed to have a null entry or not is decided by Allow
Nulls column. We try to create three columns. In the 1st column we give Name of the person. So
column name is going to be Name and data type we give to it is nvarchar(50). nvarchar(50) indicates
that we propose to have maximum of 50 characters against a Name. Means even if somebody has a
long name, we would be able to accommodate that. Then we have a Telephone as the column name
and its type is nvarchar(15) which indicates that in this column we would accept maximum of 15
characters. In the third column, we would give column name as Mobile with type as nvarchar(15)
indicating that maximum of 15 characters can be accessed as a mobile number. We might think that
nvarchar(50) as we give type for the Name then there would be too much wastage of space because if
we give Name of the person as John then John needs only 4 characters and there is large amount of
wastage of space. But that is not so. Even though we are specifying nvarchar(50), it means is length is
going to vary. So we have a var in nvarchar. It is going to vary from 1 to 50 characters. Minimum can
be 1 and maximum can be 50. If the person name is John then 50 characters will not be sacrificed. It
will definitely save based on what is the length of the name. Type the name of the column directly in
the textbox which is against the column name. Data Type column shows all the available types. There
are other data types also available. We can have types like smallint, int, bigint. smallint is like a short
whereas bigint is like a long int. In addition to that we can have datetime field, money field stores big
numbers and we also have varbinary which can be used for storing binary data like images. For all
the three columns Name, Telephone and Mobile, we uncheck the Allow Nulls checkbox.
Slide 8
Three columns stand created Name, Telephone and Mobile within our ContactsDB.mdf database.
These columns will have to belong to some or the other table. To store all these columns in a table,
we have to click on the Save button. The moment we do so, it will ask for the name of the table. The
slide shows the names that we had given for columns as well as their types and also we can notice the
Allow Nulls field in all the three checkboxes are unchecked or empty. As soon as we click on the
Save button, a dialog will pop up where we have to provide the name for the table. Give the name of
the table as Contacts and click on OK.
Result
As soon as we click on OK, the database stands created. A shown in the slide, if we look at the
Database Explorer, we can see inside the Tables there is a Contacts table entry is also present. Those
rows and columns indicate that it’s a table and it’s a visual way of communicating to us and Contacts
is the name of the table.
Now through our application, we need to connect to the SQL server. That is typically done using a
connection strings. The reason why these connection strings are used is that tomorrow we should be
able to move the database to some other place other than our own machine and still be able to
communicate with that database by connecting to it without being required to make changes in our
program. We just make a change in the connection string and we would be able to connect to a
database even though it is moved to some other machine. So that’s the way to access the database
without hard-coding anything in the project that we are creating. Connection string is a string without
any break, one complete string. As shown in the slide there is a connection string having different
name, value pairs like Data Source=.\SQLEXPRESS;
AttachDbFilename=|DataDirectory|ContactsDB.mdf;Integrated Security=True;User Instance=True.
So the connecting string is going to begin at Data Source and end at True. Within the connection
string there is different name, value pairs which are separated using ;. The connection string specifies
where is this database server and the credentials using which we can connect to that database server.
So, physical location of the database server as well as username and password kind of thing using
which we can connect to that database server are given. That is called as credentials. Within the
connecting string shown in the slide, we cannot see the username and password. Here credentials are
given by just giving name, value pairs by saying Integrated Security=True. When we say Integrated
Security=True, it means is use the same login name and password to connect to the database, the one
that we use for logging into Windows, same username and password we used for connecting to the
database server. Connection string is similar to URLs. In Data Source=.\SQLEXPRESS, . indicates
that our database is going to be present in the local machine. SQLEXPRESS is the default instance
name of the database server. Microsoft has come up with different database servers. We are using
SQL Server 2005 Express Edition. So default instance name is SQLEXPRESS. Then we say
AttachDbFilename=|DataDirectory|ContactsDB.mdf. DataDirectory is written within | |.
DataDirectory finally expands to C:\ASP.NET\Contacts\App_Data. To represent this whole thing we
had written DataDirectory. Advantage of mentioning it in this manner is that tomorrow if physically
the location of ContactsDB.mdf changes, still within our connection string we have not hard-coded
the path for that mdf file. We will just mention DataDirectory wherever the ContactsDB.mdf file is
present physically that path will be pasted in place of DataDirectory. This ensures that we do not
hard-code any entry within the connection string. If we hard-code data directory then there would be
a problem in deployment when we move the database from one machine to another or one folder to
another or one path to another. If the path changes then in that case deployment will become difficult.
Integrated Security=True means use current windows account User ID and Password. If we want, we
can also avoid this Integrated Security=True and then use SQL’s username and password to make a
connection to the database. SQL server internally maintains a table of valid usernames and passwords
and if we do not want to use the Integrated windows Security, we can think of connecting to the
database server using the login name and password by mentioning that within the connecting string.
Then we say User Instance=True. Whenever we mention User Instance=True in the connection
string, it means create a separate server instance for the current user. There can be multiple instances
of MSSQL server’s exe file. Name of that is sqlserver.exe. Whenever this sqlserver.exe is executed,
we say that there is an instance of sqlserver.exe now running in memory. There can be multiple such
instances running in memory. Each instance can have different databases associated with it such that
even if one server exe crashes still only the databases associated with that, those who would crash
others can continue to be alive. That’s the idea behind permitting multiple instances of sqlserver.exe
in memory. Databases are not going to be shared across multiple instances. The default name given
for the instance is the name of the computer if it is MSSQL server 2005 and the default name happens
to be SQLEXPRESS if it is MSSQL server 2005 Express Edition.
SQLContact Class
In this lecture you will understand:
Types of SQL FCL classes
Methods of SqlCommand class
SQLContact class
Why is it different
How to implement its methods
84 SQLContact Class Building Portals Through ASP.NET
SQLCommand Methods
The three methods in SqlCommand class that are of our interest are ExecuteReader( ),
ExecuteNonQuery( ) and ExecuteScalar( ). Each one of the method has a different ability with them.
Each one of them ultimately executes a SqlCommand which is commonly known as an SQL query.
Query word is used for SQL commands. So ExecuteReader( ), ExecuteNonQuery( ) and
ExecuteScalar( ) is ultimately going to execute some or the other SQL command. When
ExecuteReader( ) goes to work, it returns all the records that qualify a particular query. For example,
we may fire a query which looks like Select * from Customers. When we say this query then
Customers become the name of the table. * indicates all the columns in that table. This query gives
all the records and fields present in that database table called Customers. Once we establish the
connection with a particular database server, there onwards we have to deal only with the tables
inside that database. So ExecuteReader( ) returns all the records that qualify a particular query. We
can also do selective searches. We can say Select * from Customers where AmountOfPurchase >
10000. Then not every record would qualify this query. The records which qualify this query only
those records would be returned by this ExecuteReader( ). Then there is ExecuteNonQuery( ) which
executes the query. Typically this query could be insertion of records into the database or updation of
existing records. It returns back is how many rows in the database got affected as a result of
executing this query. For example, we may decide to update all the records in the database based on
certain condition. We wish to update all those records wherein amount purchased in more than
10000, we propose to give 10% discount. Only some records would qualify this query and only some
of them would get updated. Whenever that updation takes place, if we had done that using
ExecuteNonQuery( ) then out of 1000 records if only 50 got affected then 50 will be returned in the
form of a number which indicates the number of records or rows get changed or affected. So the
return value of ExecuteNonQuery( ) indicates how many rows really got affected as a result of
execution of the query. Then we have ExecuteScalar( ) which returns the first column of the first row
whenever we fire a query. Typically ExecuteScalar( ) can be used to count how many records are
there in the database which satisfy a particular criteria or we can use the Min command or the Max
command to find out the minimum value that is there in a particular column or the maximum value
that is there in a particular column or we can also think of finding out average of a particular column.
In all such cases, one value is to be returned i.e. the value present in the first column of a first row or
sometimes we may want to update a particular record or may be insert a particular record. If we have
a ordered table and we insert the order information then first column will be the order id, that order id
would be returned to us when this ExecuteScalar( ) method is called.
to pass the suitable reader object to WriteToXml( ) and LoadFromXml( ) method. The SqlContact
class is going to be a bit different. There are several methods. Apart from 0-argument constructor, we
also propose to have Insert( ), Delete( ) and Update( ) methods here. We are also planning to have
three more methods; LoadFromReader( ), ExecuteCommand( ) and ExecuteReader( ).
LoadFromReader( ) is going to read only one record from the reader. Insert( ), Delete( ) and Update( )
allows to insert a new record, delete an existing record or update an existing record respectively. Each
one of these Insert( ), Delete( ) and Update( ) to actually do an insertion, deletion and updation are
going to call the ExecuteCommand( ) method. Since the code to execute the command is similar for
all three, rather than writing the same repetitive code for Insert( ), Delete( ) and Update( ), we
propose to take out that code and write that in ExecuteCommand( ). ExecuteReader( ) is going to read
all the records from the database. In the FileContact or XmlContact project, we were managing our
contact book through a file like a txt file or XML file. There we did not have a mechanism to insert
one record into the XmlContact book or the text based contact book or delete one record or update
one record. Now we are making use of the SQL database based contact book, it’s not our headache to
figure out how one record can get inserted or one can get deleted or one can get updated. That
headache is SQL server is going to take care for us. Hence, we propose to have Insert( ), Delete( ) and
Update( ) methods within the SqlContact class.
SQLContact Class
We have SQLContact class derived from the Contact class. At the beginning we have a public
constant string called connectionString and within the connection string we will have a Data Source
as .\SQLEXPRESS. Then the name, value pair that is going to follow Data Source is
AttachDbFilename=|DataDirectory|ContactsDB.mdf. Then Integrated Security=True and User
Instance=True. This is one full string. We have concatenated different name, value pairs to build one
common full connectionString. Then we have to make sure that this connectionString is used for
actually connecting to the database. But by making it as a public const string, we are making sure that
it’s available to us wherever we need it. Then we will create a method called ExecuteCommand( )
which is called from Insert( ), Delete( ) and Update( ) methods. Since the code that we propose to do
to execute a command is going to be common for Insert( ), Delete( ) and Update( ), hence we are
taking out that code and writing that in ExecuteCommand( ) method. This method receives a
queryString which indicates what command is to be executed on the connection that we propose to
establish. ExecuteCommand( ) is a shared or static method. Means anytime this ExecuteCommand( )
is to be called, we will have to call it by saying classname.method-name. Classname is SQLContact
and method name is ExecuteCommand( ). This method connects to the SQL server and executes the
desired command i.e. the command which is passed to it in the string called queryString. Whatever
command we receive in queryString that’s the one ExecuteCommand( ) is going to actually execute.
ExecuteCommand( ) first will have to create a SqlConnection object. It does so by saying
SqlConnection conn = new SqlConnection ( connectionString ). At this juncture the connection has
not established, we had merely created a SqlConnection object. Once the object is created then we cal
also create a new SqlCommand object to which we pass the queryString and a conn reference. At this
stage we have merely created two objects, a connection object and a command object. Once both
these objects are created, now the connection would be established when we say conn.Open( ). This
is responsible for establishing the connection with the database server. Now that the connection
stands established, on this connection we would now try to execute the command by saying
cmd.ExecuteScalar( ). It executes the command on the specified connection object, the one which
stands opened and information about this connection object is there with SqlCommand object
because when we created the SqlCommand object, we can see, the 2nd parameter that we had passed
to the constructor of SqlCommand is a connection reference. It stores this connection reference in one
of its private variables. So cmd.ExecuteScalar( ) is going to finally execute our command on the
connection that stands established. Whatever values returned by ExecuteScalar( ), same thing we
would return back and that type we are giving as object when we are defining the ExecuteCommand(
) method. So return type of ExecuteCommand( ) is object.
86 SQLContact Class Building Portals Through ASP.NET
Read, Insert
To read a record, we are going to use a method called LoadFromReader( ). It receives SqlDataReader
reference and we write three lines. By using the indexed property we access the Name, Telephone
number and Mobile in the SqlDataReader object called reader. We are saying this.name = ( string )
reader [ "Name" ], this.telno = ( string ) reader [ "Telephone" ] and this.mobile = ( string ) reader [
"Mobile" ] where this.name, this.telno and this.mobile are the elements present in the SQLContact
object. name, telno and mobile are the properties which we have derived from the Contact class. We
are using these properties to setup the name, telephone number and the mobile number. Then we have
an Insert( ) method in which we are going to construct a query that is needed for inserting a record in
the database. When we say string queryString = string.Format( ). This method allows to construct a
string. We are going to construct a string which reads like INSERT INTO Contacts ( Name,
Telephone, Mobile ) VALUES ( 'Ramesh', '223344’, '9856712345'). That’s the final queryString that
we propose to construct. Contacts is the name of the table that we had created in a database called
ContactsDB.mdf. To be able to do so, we are saying "INSERT INTO Contacts ( Name, Telephone,
Mobile ) " + "VALUES ( '{0}', '{1}', '{2}' )", name, telno, mobile. This string is passes as an
argument to the string.Format( ) method. This string finally would get constructed in the form of a
string which is shown in the box in the slide. Once this queryString stands constructed, we call
ExecuteCommand ( queryString ) where ExecuteCommand( ) actually going to open the connection
and fire this query.
Delete
In the Delete( ) method, we are again going to construct the queryString. Subsequent to that we call
ExecuteCommand( ) method. This time the queryString will look like DELETE FROM Contacts
WHERE Name = 'Ramesh' AND Telephone = '223344' AND Mobile = '9856712345'. So for this
query to fire, we will construct a query as "DELETE FROM Contacts WHERE " + "Name = '{0}'
AND Telephone = '{1}' AND Mobile = '{2}'", this.name , this.telno , this.mobile and then call
ExecuteCommand ( queryString ) method once again. Once again a connection is opened with the
database and this query is fired on it. As a result of which that record in the database got deleted
whose name is Ramesh, whose telephone number is 223344 and whose mobile number is
9856712345.
Update
In the Update( ) method, we will again construct a queryString. This time in place of INSERT and
DELETE, a UPDATE SQL command is used. While updating set the Name, telephone number and
mobile number to a set of values and which name, telephone number and mobile number has to be
updated the one which has name, telephone number and mobile as present in this.name, this.telno and
this.mobile. So whatever n, t and m are received, those are the new values whereas this.name,
this.telno and this.mobile are the current values present in the database. So it will search according to
whatever is present in this.name, this.telno and this.mobile and once that is searched, it will change
these values to the one that are there in n, t and m. So wherever 0, 1, and 2 are present, there values of
n, t and m were go whereas 3, 4 and 5 would be replaced with this.name, this.telno and this.mobile.
So create the string using string.Format( ) and then using it call again ExecuteCommand( ) to execute
this command after having established the connection with the database. For example, as shown in
the slide, the query is UPDATE Contacts SET Name = 'Ramesh K', Telephone = '556677', Mobile =
'9912356745' WHERE Name = 'Ramesh' AND Telephone = '223344' AND Mobile = '9856712345'.
So use one set to locate the record and use another set to write the final values on top of the record
that got searched.
ExecuteReader( ) method reads all the records from the database. queryString would be the command
that would be executed on the SQL server. ExecuteReader( ) is going to execute this command on the
specified connection object and moreover its going to return the SqlDataReader with rows that
qualify the query. Means multiple rows are going to return in the form of SqlDataReader. So return
type of ExecuteReader( ) is SqlDataReader. So create a SqlConnection object. Having done that
create a new SqlCommand object. As yet the connection has not been opened. Now open the
connection and having opened the connection, execute the command that is there in queryString by
saying cmd.ExecuteReader( ). Means now we are calling the 2nd method from the SqlCommand class
and the one which is capable of returning multiple rows. So cmd.ExecuteReader( )’s return type is
SqlDataReader and that SqlDataReader is we are returning.
88 ContactList And ContactsManage Implementation Building Portals Through ASP.NET
ContactList And
ContactsManage
Implementation
In this lecture you will understand:
Details of ContactList class
Details of ContactsManage Class
Building Portals Through ASP.NET ContactList And ContactsManage Implementation 89
ContactList Code
At the beginning, we will have to import using System.Collections and using System.Data.SqlClient
namespaces. In the ContactList class, we have a protected ArrayList m_list. In the constructor, we
would create a new ArrayList object. So any time a ContactList object is created, we can assume that
an ArrayList object would also get created. Then we expose a property List and it is going to return
m_list. So anytime from outside the class, somebody to have an access to the ArrayList, he can utilize
this property List and he would then be able to access the ArrayList from this class. Then we have the
Search( ) function. In the Search( ) function, we are going to receive a string needle. This string
would represent the name of the person whom we wish to search in the contact book. We need not
supply the entire name to the Search( ) function. Means if part of names we want to search through
the Search( ) function, we can do so. Inside this function, in a for loop, go through the ArrayList from
0 to m_list.Count. Iterate through that ArrayList. Each time through the ArrayList, we should try to
find out the name that we have in needle, is it there in name of the current contact as we traverse
through this ContactList. For that we first create a Contact reference. This is necessary because when
we extract the contact from m_list that time we have to cast it appropriately. Then we can check if (
con.name.ToLower( ).Contains ( needle.ToLower( ) ) ) and if it is true then we return con. Outside
the for loop we should return null i.e. in case of failure we return null.
Slide 5
To be able to load the data from the SQL database, we are proposing to use LoadFromSQL( )
function. Here we will have a SqlDataReader reference reader which is set to a value null. In the try
block, we would first create an ArrayList and stores its reference in m_list. Then we will call a
method called ExecuteReader( ) which is static function of SQLContact class and to that we are
passing a query string SELECT Name, Telephone, Mobile FROM Contacts. ExecuteReader( ) would
collect this query and then fired that query after having opened the connection with the database. It
returns SqlDataReader. Now the reader that we have, we must use it to iterate through all the records
that qualify this query which is done in the while loop. We have to keep saying while ( reader.Read( )
). The Read( ) function loads the next row from the result of the query means if 10 records qualify the
query then the next record that is there from the qualified list of records would be loaded and this
would continue to happen till the time we are not done with the last record from the list of qualified
records. Qualified indicates those records which were searched successfully based on the queryString.
The Read( ) method returns true till the time we have records to go to. If we have gone through the
90 ContactList And ContactsManage Implementation Building Portals Through ASP.NET
last record of the qualified list of records then reader.Read( ) return false and the while loop would
come to an end. Inside the while loop, we must first try to create the SQLContact object. Its reference
is collected in con. Then call SQLContact’s function con.LoadFromReader ( reader ). It used to
extract from the reader i.e. from the current record it used to extract the name, telephone number and
mobile and assign it to the name, telephone number and mobile of the SQLContact object. Once this
assignment is over then we can add it to the ArrayList using m_list.Add ( con ). So this reference is
added to the ArrayList. In the finally block, we propose to check if ( reader != null ) and if it is not
null then we close the reader using reader.Close( ).
Slide 6
Any time the contact is to be added the SQLContact c would be received in the AddContact( )
function. We have to use that c to insert contact by calling SQLContact’s Insert( ) function into the
ArrayList i.e. c.Insert( ). Likewise in the DeleteContact( ), which contact is to be deleted that
information will come to us as a parameter in SQLContact c. In DeleteContact( ), we do c.Delete( )
which will eliminate the contact from the contact book by calling the Delete( ) function of the
SQLContact class. On similar lines we will have a UpdateContact( ) function which receives the
contact which is to be updated. That information would be in the SQLContact c. n, t and m would be
the new name, telephone number and mobile which are to be updated into the database. For that we
will call c.Update ( n, t, m ) method. We do not have to pass the current contact information because
we are calling Update( ) using current contact i.e. c.
List Contacts
The Page_Load( ) method always receives an object and an EventArgs. Within this, we have to list
the contacts on the webpage. To do so we say ListTable.Rows.Add ( AddHeader( ) ). AddHeader( )
adds the three column headings. ListTable is the name of the table that we had created. Subsequent to
that we call a function called LoadFromSQL( ). In the LoadFromSQL( ) function, we are going to
create a new ContactList object. As soon as we create the new ContactList object, we are sure that a
new ArrayList object should also get created. Once that has been done we can call
clist.LoadFromSQL( ) which loads the data from SQL database and populate ArrayList with
references to multiple SQLContact objects. Now we have to display this list of contacts on the
webpage. To do that we will run a loop going from for ( int i = 0 ; i < clist.List.Count ; i++ ). Each
time through this loop, make a call to the function AddContactRow ( ( Contact ) clist.List [ i ] ).
UpdateListTable( ), that’s the one that is going to update the list of contacts on our webpage the
moment addition of a new contact is done.
Helper Functions
WriteToSQL( ) and UpdateListTable( ) are helper functions. In WriteToSQL( ) function, we are
going to create a new SQLContact object and then we are going to replace any commas that are there
with spaces by saying con.name = nameInput.Text.Replace ( ',', ' ' ), con.telno = telInput.Text.Replace
( ',', ' ' ), con.mobile = mobInput.Text.Replace ( ',', ' ' ). Once that is over we will create a new
ContactList object and call a AddContact( ) method on it i.e. clist.AddContact ( con ). AddContact( )
function updates the ArrayList. In the UpdateListTable( ) function, we will first clear out everything
that is there in the ListTable right now. To do that we say ListTable.Rows.Clear( ). Then we say
ListTable.Rows.Add ( AddHeader( ) ) which adds new header of Name, Telephone number and
Mobile and then call LoadFromSQL( ). LoadFromSQL( ) loads all the contacts from the SQL into the
ArrayList. It also writes all the rows that are there in the ArrayList into the webpage.
flaw. Moreover, the security implications of that are quite severe. To deal with this SQL injection
attacks, we should never trust input that comes from the different textboxes because that’s when the
user types new input. Never trust it. Don't think that users will always use well-formed input. You got
to validate before using any input in your database. We should never attempt to build a “query string”
directly from the input unless we have validated it. Moreover, instead of building the query string
directly from the input, we should use parameterized queries which MS SQL provides to us. We
should also try to reject special characters like ; ' --. These characters we should never be accepted in
an input. So if we notice these characters in the input, reject them. We have to do this
programmatically because once he enters and you receive it, we will have to validate it naturally in a
programmatic fashion. So better way to build a query is that to pass “parameters” to the INSERT
command and those parameters should be type safe parameters and MS SQL Server supports
parameterized queries. Once we know how to build them, we can know thoroughly well that nobody
is going to touch the data within the database.
Change Delete( )
In the Delete( ) function, we will have a query which is "DELETE FROM Contacts WHERE Name =
@name " + "AND Telephone= @telephone AND Mobile = @mobile". Once the query is
constructed, we can create a SqlConnection object using the connectionString. Then create a
SqlCommand object and pass the query as well as the SqlConnection reference to the constructor.
Then add parameters to the SQLParameterCollection by saying cmd.Parameters.Add ( new
SqlParameter ( "@name", this.name ) ), cmd.Parameters.Add ( new SqlParameter ( "@telephone" ,
this.telno ) ) and cmd.Parameters.Add ( new SqlParameter ( "@mobile" , this.mobile ) ). Once this is
done, now we can open the connection using conn.Open( ) and fire the query on this connection by
calling cmd.ExecuteScalar( ).
Change Update( )
Building Portals Through ASP.NET Secure Database Programming 95
In the Update( ) function, we will first construct the query as "UPDATE Contacts SET Name =
@newname, " + "Telephone = @newtel, Mobile = @newmobile WHERE " + "Name = @name AND
Telephone= @telephone " + "AND Mobile = @mobile". Name should have the value as present in
@newname, Telephone should have the value as specified by @newtel and Mobile should have a
value as specified by @newmobile. Before we set the values we must be able to search the record. So
we have used the WHERE clause. In the WHERE clause, we will search for the name, telephone and
mobile as specified by @name, @telephone and @mobile. Means we are having 6 parameters here; 3
of the old contact and 3 of the new modified values. All these we will have to be added to the
Parameter Collection. First we will create the SqlConnection object and then create the SqlCommand
object. Then call cmd.Parameters.Add ( new SqlParameter ( "@newname", n ) ),
cmd.Parameters.Add ( new SqlParameter ( "@newtel", t ) ) and cmd.Parameters.Add ( new
SqlParameter ( "@newmobile", m ) ) i.e. we were added new SqlParameter object each time. Old
values are assigned using cmd.Parameters.Add ( new SqlParameter ( "@name", this.name ) ) and
cmd.Parameters.Add ( new SqlParameter ( "@telephone", this.telno ) ).
Slide 9
Old value of mobile is assigned using cmd.Parameters.Add ( new SqlParameter ( "@mobile",
this.mobile ) ). Then we will open a connection using conn.Open( ) and then fire the query by calling
cmd.ExecuteScalar( ).
Moral
We have to validate every single value that we receive as input. Assume that every input that is going
to come from the user is harmful till the time it is proven otherwise i.e. validates it thoroughly. Look
for valid data and reject everything else other than that valid data. Constrain, reject, and sanitize user
input by performing type checks thoroughly, perform length checks correctly. Range checks are also
important where the value of a particular field to be within a range and also formatting is checked.
96 Employee Management Website Building Portals Through ASP.NET
Employee Management
Website
In this lecture you will understand:
Different types of Web Controls
Employee Management Web application
Steps involved in building the application
Displaying Flash files on web pages
Building Portals Through ASP.NET Employee Management Website 97
Web Controls
Suppose we decide to have two controls on a webpage. One is the textbox in which a name can be
typed and then can be a button like Add which we click. As a result of which, we are able to add this
name may to a database or to a XML file or to a text file or to an ArrayList in memory. So there are
two controls inserted on a webpage. The moment we insert the textbox control, an <asp> tag is
inserted within the aspx page which reads like <asp:TextBox id = "fname" runat="server"/>.
runat="server" indicates that control is going to get executed on the server. When we say id =
"fname", this id is really gets converted into the reference to an object that gets created of the type
98 Employee Management Website Building Portals Through ASP.NET
TextBox. There is also a tag for button which is <asp:Button id = "ab" Text="Add" runat="server"/>.
The id given for the button is ab. There is a Text attribute which says that its value is Add because
Text attribute has a value Add, on the button surface we see that the text Add is written over there.
On the server side, suppose the MyPage class is created which is derived from the Page class. Inside
the MyPage class, we can see that there are two references created; one by the name fname and
another by the name ab and TextBox and Button which we used as the asp tags become classes on the
server side. There is a class TextBox which is derived from the WebControl class and there is a
Button class which is also derived from the WebControl class. For every single control that we drag
and drop on the webpage, there is a parallel class available in the Framework Class Library. Most of
these control classes are derived from a generic WebControl class. Each of these classes contains
properties and events. For example, TextBox can have properties like Text, Width and Enabled. Text
lets you determine what text is being typed out within that TextBox control and Width decides the
width of the control. Enabled property depending upon it is set to true or false will decide whether the
webpage should appear or should not appear on the webpage. Using the properties we can control the
behavior and appearance of the control. In addition to that, there are events as well. For example,
with Button there are events like Init( ), Load( ) and Click( ). Whenever the button is clicked, its
Click( ) handler is going to get called but that does not mean that with a button only one event can be
associated. There are multiple events that can be associated with a particular web control. Based on
what action is going to happen, a suitable event will be fired. As a result of which a handler would
get called. Handler would be present not only in the Control class but in the Page class that we have.
In the MyPage class, there is ab.Text = "ADD" means we are trying to change the Text property of
the ab control. Means properties that are there within the TextBox class can be easily accessed
through the reference for that TextBox whereas if somebody clicks on the Add button then the event
Click( ) would occur for which the event handler called ab_Click( ) would get called. For every single
control that we put on the webpage, there would be a Control class present which would contain
events and properties. Those properties we can use within the Page class to manipulate the
appearance and behavior of the control whereas the event handlers can be written for corresponding
events that have been declared inside that Control class. As and when those events occurred, suitable
event handlers would then get called.
Goal
We wish to display a webpage with different controls and some flash animation at the top. In the
Employee website, we would want to receive information about an employee may be that we wish to
store in a database. For doing so, we will have different TextBoxes, Drop down list, Calendar control,
so on. These we would use to receive information like name of the employee, address of the
employee; within the address, there are two address lines and then there is a state and then the city.
State and city information is important in any address. State information can be done using a drop
down list box. Whenever we have a drop down list box, we will have names of different states. The
Building Portals Through ASP.NET Employee Management Website 99
moment we pick a state appropriately the cities within that state will be listed in the list box for city.
Then we have a TextBox to receive the pin, Radio buttons to decide the gender, Male/Female,
Calendar control to accept the date of joining of that employee in our organization. When all this is
being displayed, at the top we can see that there is a small snail is being displayed there. It’s an
animated flash file. So we want to play that animated flash file where the snail moves from right to
left. At the top this flash file would continue to get played. Then the name, address, gender, date of
joining, etc. are displayed. In addition to this information, we would also want the user to upload his
photograph. To upload the photograph, we will have a browse button wherein we can navigate
through different drives and directories. Select the file in which photograph is there. The path of the
image file will now get displayed within the TextBox for photo. Email address would also be there. If
Email address is entered then we will have to validate that Email address. Following that we will
have the hobbies of the employee stored in the database. One person can have multiple hobbies, so
checkbox is used. When we click on Add Now! Button, then only the addition should happen.
Desired Result
Not only all the information that is either typed or selected from the different controls, all this
information has to go into the database. In addition to that whatever was entered, the summary of that
is displayed on the webpage and to do so, we will put a webpage showing clearly the entire
information as shown in the slide. So, all the information along with the photograph, all of that
should be displayed in the form of a result of the addition that we just now done. So for every
employee, we would go on adding information, it should get displayed in the form of summary along
with the photograph on our webpage.
Steps Involved
First step would be to create a new website. Once that is done, we would proceed to creation of a
database. Then we would also be required to create a backend class called Employee. Then we will
also be required to create a Webform using which we would try to retrieve the information or receive
the information from the user and then display it in the form of a summary. For that we need to deal
with a Webform. Now we would try to create a 1st step i.e. creation of a new website. In this process,
we will have to give name of the project and we provide it as EmpMgmt. Then we will change the
title of the webpage to Employee :: Management. Then we will add a flash file to that webpage is
flyingsnail.swf. Flash files have a .swf extensions standing for shockwave file. Then the background
color of the webpage is changed to cream color. These four steps are carried out as a part of Part I of
building of this website.
that there is flyingsnail.swf. That indicates the location of the shockwave file. Then we use another
attribute called type which stands for MIME type i.e. Multimedia Internet Mail Extension type which
basically indicates the contents of that swf file. The <object> tag can not only be used for playing swf
files but it can also be used for variety of other things like displaying images, displaying photographs,
playing sound, playing video. Hence what type of MIME content is there, that we have to indicate
and for our swf file, the MIME type that we have to mention is application/x-shockwave-flash. It is
typed as it is when you create this <object> tag. Then we have to mention the width and height of the
swf file. Then we are giving the runtime initialization data which will be useful for actually playing
the shockwave file. There we have to give the name which is given as movie and value as
flyingsnail.swf. So parameters that are to be given to the ActiveX control which is actually going to
play this shockwave file that initialization data is always given in the form of name, value pairs using
the <param> tag. So we mention that within the <object> tag and then we are ready to play the swf
file.
Result
The slide shows the result of the swf file. The flyingsnail.swf file is shown in the Default.aspx page
in the Design format.
Result
When we see the result, we find that the page color is changed and the flyingsnail moves from right
to left. All the information about an employee is displayed on the webpage which is a cream color
webapge.
Building Portals Through ASP.NET EmpMgmt Website – Database Design 101
EmpMgmt Website –
Database Design
In this lecture you will understand:
Goals of Database Design
Database related terminologies
Database design approaches
Creating database & tables for EmpMgmt app
102 EmpMgmt Website – Database Design Building Portals Through ASP.NET
some mechanism to identify each employee in a unique fashion which will have no conflict with any
other employee even though the data of that employee is same as the first one. So the uniqueness
aspect has been accounted for while doing the database design. Thirdly this is a inflexible database
that we have created because today there are only 5 hobbies. But tomorrow if we decide to add two
more categories of this then it will create a problem. Because we agreed that we will not change the
database once it is designed. Hence even though this is a workable way, this cannot be the best way.
We cannot change the columns later on. We have to do it in some other fashion.
Solution
Solution to the problem I is we can create different tables for cities, so also for states. In cities table
we can have list of cities along with the unique identifier for each. In the States table, we can have
names of different states along with unique identifiers to identify each state in a unique way. So we
will have to take out this data from the table where we have employee information and create
separate tables one for City and another for States. The problem of inability to identify a row in a
unique fashion can be solved by creating identity columns within our tables. So we now finalized at
least three tables. One is Employees, 2nd is Cities and 3rd is States table. For each one of these tables,
we will have some or the other way to identify each row in a unique way and to do that, we will
establish an identity column within each of these tables. The inflexibility can be sorted out by
creating a separate table which maintains a list of possible EmployeeHobbies. So if there are 5 rows
in EmployeeHobbies table; one row can contain Cricket, another can contain Swimming, so on. If
there is a 6th hobby, we can add one more new row because that’s the data. We are not talking about
addition of a new column because when we add a new column, we are modifying the database or we
are changing the database design. But when we are adding a new row, we are adding a new record to
the existing database without changing any of its design. So, all these three problems can be sorted by
creating multiple tables. We have at least four tables here; Employee, City, States and
EmployeeHobbies. Once we create these tables, they should not remain there in isolation. Whatever
natural relationships that exist between these tables, that relationship we need to establish. Because
once it is established then only we will find that the true benefits of a good database design will keep
accruing to us.
Terminology
Primary Key – A column whose value is guaranteed to be unique in each row of a table.
Foreign Key – A column whose values are primary keys in other table.
Identity Column – A numeric column whose value is automatically assigned by SQL server and
incremented after every insertion.
Composite Primary Key – A combination of columns which together gives a unique value in each
row of a table.
Steps Involved
First step that we would do is creation of the database. Part I we had done last time. Creation of a
database involves creation of the database means the mdf file and subsequent to that creating
different tables inside that mdf file. Within one mdf file, we can have multiple tables. In
ContactsDB.mdf we had created a Contacts table. Similarly here we will also create a mdf file in
which in place of one table, we will have multiple tables.
When we do so, a dialog would appear as shown in the slide. Select SQL Server Database from the
dialog that appear and give the name as EmpDB.mdf. Then click on Add.
Save Table
Once we do that, a menu will pop up from where we can Add New Table. Once we select Add New
Table, we will be allowed to give names of the columns, the data types and either check or uncheck
the Allow Nulls column. So for Employees table, we are going to have several columns; EmpId
which is bigint, EmpName which is nvarchar(100), AddLine1 which is nvarchar(100), AddLine2
again nvarchar(100), then CityId is smallint, Pin is nchar(6), Gender is bit, PhotoUrl is nvarchar(100),
Email is again nvarchar(100). All these columns we should create within the database. We will
uncheck every Allow Nulls because we do not allow to have null values. Then click on the Save
button. As soon as we do so, a dialog will pop up where we will be asked to enter the name for the
table. Give the table name as Employees. So EmpDB.mdf is the database file. Inside that we have
created our first table i.e. Employees. Then click on OK. So Employees table now stands created.
Result
We can watch this Employees table against the Tables entry in the Database Explorer. The slide
shows that within EmpDB.mdf, there is Employees table now stands added.
EmpMgmt – Database
Relationships
In this lecture you will understand:
What are PKs and FKs
How to set PK
How to set Identity column
How to establish relationships between tables
106 EmpMgmt – Database Relationships Building Portals Through ASP.NET
Steps Involved
We had divided the entire project in four parts as shown in the slide. Pot of four parts, first part is
complete. 2nd part is partly complete. While creating a database, we had given the database name as
EmpDB.mdf. Then we had created five different tables in the EmpDB.mdf. Those five tables are
Employees, Cities, States, Hobbies and EmployeeHobbies. Hobbies table is used to keep list of all
valid hobbies. EmployeeHobbies is going to have which employee has which of the hobbies that are
there in the Hobbies table. We will also need to establish this relationship clearly. Out of creation of
database, first two parts are completed i.e. creation of database and creation of tables. The other two
parts are setting the primary key and the identity column in each table and then represent the
relationships that exist between these tables.
Result
Once we set EmpId as primary key, we would find that in the table, now a key would be marked in
yellow color. The key indicates that EmpId has now been marked as a primary key within this table.
Result
Once we do that, the result is shown in the slide. We can see in the Properties window, against
Identity Column an EmpId is shown indicating that that is being accepted as the Identity Column.
Then we save whatever we have done i.e. setting of the primary key and setting of the Identity
column for Employees table. The EmpId column is going to act as the primary key column and it is
also going to act as the identity column. Means the values that are there inside this column, those are
going to be unique. By setting EmpId as Identity Column, we are ensuring that entries within this
Identity Column will not be made by us. They will be made by the SQL database server. As and
when we add a new row to the Employees table, automatically the EmpId for that row will get
incremented. We can never touch the Identity Column. Then only database server can guarantee the
uniqueness in that column. So the primary key column itself can act as the Identity Column. With
what unique number an Identity Column should begin and by what increment should it keep on
changing every time we add a new row, we can control that. That’s known as initial value and the
step value. We can set initial value to 5 and step value to 10. If we do so then the 1st record that we
add in the Identity Column 5 gets entered. After 5, next record is marked as 15, so on. CityId here is
the foreign key because CityId’s value will be unique in the Cities table.
Select CityId
Once we do that, the column names of the Cities table will be shown. We can see CityId, CityName
and StateId in the slide. From here, we will select CityId as the primary key for the Primary key table.
Relationship Name
The name given to this relationship is FK_Employees_Cities. Employees is the foreign key table and
Cities is the primary key table and both tables have common Id as CityId. Then click on OK.
Close
Building Portals Through ASP.NET EmpMgmt – Database Relationships
109
Lastly we close this by clicking on the Close button. We can save this relationship by clicking on the
Save button.
Close
Finally we close this by clicking on the Close button.
Save Changes
110 EmpMgmt – Database Relationships Building Portals Through ASP.NET
All the changes that we have made, we have to save them by clicking on the Save button. It will ask
you that the changes have been made, do you really wish to continue to save them. Click on Yes
button. Now all the relationships that we have made get saved in the database.
Relationship Summary
The relationships are shown in the slide. We have five tables; Employees, Cities, States,
EmployeeHobbies and Hobbies. Each table has a primary key. EmployeeHobbies has a composite
primary key. CityId is foreign key in Employees table and StateId is foreign key in Cities table. As
shown in the figure, between Cities table and Employees table, there is a linkage. At one end of the
linkage there is yellow colored key. At the other end there is infinity sign (∞) is present. The moment
we have a ∞ sign, it means that there is 1 to many relationship between Cities and Employees. Means
in the CityId, there is going to be a unique key. That unique key may have several occurrences in the
Employees table. If there are 20 employees belonging to the same city then CityId would be
occurring at multiple rows in the Employees table whereas that Id will occur only once in the Cities
table. That’s why one city occurring against multiple employees which is 1 to many relationship. So
∞ and yellow colored primary key clearly indicates 1 to many relationship. In the linkage between
Cities and States table, at one end there is ∞ symbol and at other end there is a yellow colored key
which is a primary key symbol. This also indicates 1 to many relationship. There is again 1 to many
relationship between Hobbies and EmployeeHobbies table. There is also 1 to many relationship
between Employees table and EmployeeHobbies table. EmpId and HobbyId are foreign keys in
EmployeeHobbies table. EmployeeHobbies has no Identity column. So the relationship that we
establish can be seen in the database diagram. There is a provision to create this database diagram
through the database server.
Building Portals Through ASP.NET EmpMgmt – Database Diagrams And Data Entry 111
EmpMgmt – Database
Diagrams And Data Entry
In this lecture you will understand:
How to create Database Diagram
How to enter initial data in tables
How to create backend class - Employee
112 EmpMgmt – Database Diagrams And Data Entry Building Portals Through ASP.NET
Database Diagram
Go to the Database Explorer pane. Right click on the Database Diagram. A menu will pop up. Select
Add New Diagram from the menu that pops up. Then it will ask that do you want to create a new
diagram? We say Yes. So we click on Yes.
Add Table
As soon as we do so, a dialog as shown in the slide is displayed. What tables do we want to display in
this database diagram is asked to you. The dialog shows five tables; Cities, EmployeeHobbies,
Employees, Hobbies and States. We want to select table from here. Suppose we select Cities table.
Then click on the Add button.
Result
Once we do that, in the Database Diagram, all the five tables will be shown along with the
relationship that we established between them as shown in the slide. The database diagram gives the
visual appearance of how we want the data to be presented.
Result
So having entered few states, the States table data would look like as shown in the slide. The slide
shows the difference in color in the values in StateId column and the values in the StateName
column. StateId column values are shown in gray color whereas StateName column values are shown
in black color. StateId column values are gray in color means they have not been typed by us; they
are auto generated. This is the purpose of Identity Column.
Again go to the Database explorer. Select EmpDB.mdf. Expand the Tables branch from there. Then
right click on the Cities table. As soon as we do so, a menu would pop up. Select Show Table Data
from the menu that pops up.
Type Data
When we do so, an empty table as shown in the slide will be shown because nothing has been added
to the table right now. We are required to enter data in the table. In the Cities table, CityId, StateId
and CityName columns are present. Again CityId is gray in color whereas StateId and CityName are
black in color. Means in StateId and CityName, we can type values whereas values in the CityId will
be auto generated by the database server, the moment we enter a new row in the table.
Result
After typing certain values for StateId and CityName in the Cities table, the result is shown in the
slide. While entering these values, we have to keep States table data handy to indicate for which city
the State belong. CityId values are unique which get incremented when we went on adding new row
to the table. StateId is not unique but it is unique in the States table.
Steps Involved
The four parts of this application were creation of a new website, creation of a database, creation of a
backend class and creation of a webpage. First two steps are now stand done completely. Now we
will try to create a backend class where name of the class is Employee.
Slide 15
On similar lines, we will declare a variable private string mName. Then we will declare a Name
property having get clause which returns the value of mName and a set clause which sets the value in
mName. Then we have private string mAddLine1 variable and a property called AddLine1. This
property has a get clause which will return the value of mAddLine1 and a set clause which sets the
value in mAddLine1. On similar lines we have private string mAddLine2 and a property called
AddLine2. This property again has get clause to return the value of mAddLine2 and a set clause to set
the value in mAddLine2. Then we have private string mState variable. We have a property called
State and within the property we have get and set clauses which returns the value present in mState
and sets the value in mState respectively.
Slide 16
Then we create a variable private string mCity. Then we create a property City having get and set
clauses. get clause returns the value present in mCity and set clause sets the value in mCity variable.
Then we create a variable private string mPin. A property Pin with get and set clauses are created. get
114 EmpMgmt – Database Diagrams And Data Entry Building Portals Through ASP.NET
clause returns the value present in mPin and set clause sets the value in mPin variable. Again we
create a variable private bool mGender. A property Gender with get and set clauses are created. get
clause is used to return the value present in mGender variable whereas set clause is used to set the
value in mGender variable. Then we will create a GenderText property which is a readonly property.
This property will check the value present in mGender. In this property we are saying return Gender.
The moment we say Gender, we are going to have access to the get clause of the Gender property
which will return mGender value. If the mGender value is true then this GenderText property should
return Male, otherwise it should return Female.
Slide 17
Now we will create a variable private DateTime mDateOfJoining. Then we will create a property
DateOfJoining having get and set clause. get clause returns the value present in mDateOfJoining
whereas in set clause, we set the value in mDateOfJoining. Then we will create a variable private
string mPhotoUrl and a property called PhotoUrl. This property has get and set clauses. get clause
returns the value present in mPhotoUrl variable whereas set clause sets the value in mPhotoUrl
variable.
Slide 18
Now we create a variable private string mEmail and a property called Email with get and set clauses.
get clause returns the value in mEmail variable and set clause sets the value in mEmail variable. Then
we will create a variable private ArrayList mHobbies. We need ArrayList because there is a list of
hobbies. We have a property called Hobbies which has a get clause. Means this is a readonly
property. get clause returns mHobbies. Then we have a constructor of the Employee class. Inside the
constructor, we will create a new ArrayList and set its reference in mHobbies.
Building Portals Through ASP.NET EmpMgmt - WebForm 115
EmpMgmt - WebForm
In this lecture you will understand:
Creation of webform
Insertion of different controls
Data-binding of controls
Resultant aspx tags
116 EmpMgmt – WebForm Building Portals Through ASP.NET
Steps Involved
In this example, the steps involved are creation of a new website, creation of a database, creation of a
backend class and creation a webform. In this lecture we will study how to create a webform.
triangle appears next to that. This is called as the smart tag. If we click on that with mouse button, it
shows the tasks or the kind of things that we can do with this data bound control. Right now it says
that it is unbound which means that the data is not there. We are trying to bind it. So among the
options, it says there is option to PostBack automatically. We click this button to ensure that every
time the selection of state changes, a POST message should be generated and send to the server. The
list of cities that we are going to see down below after this row, is going to be dependent on the state
which is selected. So every time the state that user had selected changes, the box that appears below
shows the cities also has to be refreshed. That means we have to let the server know that the user has
changed the selection. For that the AutoPostBack property has to be turned on. Then we have to say
from where exactly the data is going to come from. So we click on Choose Data Source.
Connection String
118 EmpMgmt – WebForm Building Portals Through ASP.NET
What is the connection string? If we want to see the connection string then we have to expand the +
link.
Save CS in Web.config
In this step, it is going to ask do we want to save the connection string somewhere. Whenever you
walk through these wizards, make a habit to read the title in the wizard. In this case the title is Save
the Connection String to the Application Configuration File? Description says that we are going to try
and save to Application Configuration File. Such a file exists in the Application’s own directory and
the filename is Web.config. If it does not exist, at this time it will be created. Why are we saving this
connection string in a file? This connection string is not going to be used in just one page; it is going
to be used in multiple pages, multiple forms in the same web application. Every time we do not want
to repeat the process of defining the connection string. This web application configuration file stores
it so that every page can use it. Suppose we had deployed our application to the actual hosted web
server, there the connection string is totally different. Since we are not hard coded the connection
string inside the aspx file, if we change the web.config file with the correct connection string directly,
the new connection string is automatically used in all the places where it is referred. We have to give
some name to this connection string. So in this case we are going to call it EmpConStr. So connection
string stands defined. Then we click on Next.
Configure Select
When we click on Next, the wizard is going to connect to the database server, get the list of all the
tables, all the columns, types of all the columns in the table and so on. It might take some time
depending upon how many tables exist in the database. As shown in the slide, by default the Cities
table is highlighted. It shows that we are trying to configure a Select statement. Select will give the
list of anything that we want. But in this case we want list of States. For that we click the drop down
link.
Choose Fields
Once we select the States table, in the textbox below that, it shows those columns which are in the
States tables. So it shows StateId and StateName columns. If we want to select all the columns, we
can click *. If we do not, we can select one by one column by clicking corresponding boxes. These
checkboxes allow to select only certain columns if we are not interested in all the columns. We click
on * because we want to select all the columns.
Select Statement
As soon as we select *, the Next button becomes highlighted because the SELECT query in the
SELECT box clearly indicates that the SELECT expression is SELECT * FROM [States] which
means it is going to return all the states in the table. Then we click on Next.
Test Query
Building Portals Through ASP.NET EmpMgmt - WebForm 119
When we click on Next, it allows to test the query that we have configured. Sometimes we write the
SELECT query manually. In the manual process, if there is a mistake, we may not get exactly what
we are looking for. So the test step allows to check if our expected results are what exactly we are
going to see. So we click on the Test Query button.
Result
As soon as we click on the Test Query button, it shows the list of 5 states. These are the states that we
had entered manually in the step where Data Entry is to be made. Then we click on Finish. This
completes configuration of data source.
Result
The result is as shown in the slide. It shows that now the source has been selected. In that same row,
we will see a DropDownList control. The word Databound comes instead of Unbound. In the task,
there is Configure Data Source, Choose Data Source, more options are present. Down below there is
SqlDataSource control and its id is sqlSourceStates. SqlDataSource is also a server control but its
purpose is to feed the data to a DropDownList control. So depending upon what kind of purpose a
control has, it may or may not have a user interface.
Select Fields
Now we come to the selection of tables and creating a SELECT query. Cities table is already
selected. We want to select all the columns from the Cities table. So we select *. But we do not want
all the cities. We want cities in the state which has been selected using the State’s DropDownList. For
that we have to click on the WHERE clause which allows to add a portion to the SELECT statement.
So we click on WHERE clause.
Building Portals Through ASP.NET EmpMgmt - WebForm 121
Choose Column
As soon as we click on the triangle, three column names would appear in the list. We have to select
by StateId column. So we select StateId column.
Choose Operator
We have to use the type of Source here with a = operator as Control on the same page. So we first
select = operator. Then we click on the drop down list for the selection of source.
Choose Source
From the list we choose Control as the source.
Choose Control Id
From the list, we select lstState.
Sql Expression
In lstState whichever StateId gets selected that becomes the input parameter for us, that becomes the
parameter in the WHERE clause. So the SQL Expression is [StateId] = @StateId and Value is
lstState.SelectedValue. Then click on Add.
Finish
We do not want to test the query this time. So we click on Finish.
Result
Now as shown in the slide, both Databound controls stand created.
122 EmpMgmt – WebForm Building Portals Through ASP.NET
EmpMgmt – Finishing
Touches
In this lecture you will understand:
Regular Expression Validator
Calendar Control
CheckBoxList Control
File Upload Control
Database Transactions
Inserting a record in DB
124 EmpMgmt – Finishing Touches Building Portals Through ASP.NET
Steps Involved
The steps involved in creating this application were, creation of a new website, creation of a database,
creation of a backend class and creation of a webform. In this lecture we will perform the 4th step i.e.
creation of a webform. Part of it is done in previous lecture. Remainder of that is being done in this
lecture.
character, there could be -, . or + sign. These are valid characters in Internet email address. After that
at least one alphabetic character comes, followed by a ., + or – sign and then this is itself optional but
it has to be followed by at least one actual . ( dot ). To represent actual . character, we are writing \.
which means it’s a literal dot. So it’s an escape character. . matches any character. In [ ], we do
grouping. Sometimes these standard validators that Microsoft has provided, does not meet our
requirement. In that case we can use the CustomValidator control which allows to write C# code,
which takes care of the complete validation of all the input parameters that a user might have typed in
a web application and report error in case the validation is found to be incorrect or the combination of
input is found to be incorrect.
Slide 12
If somebody changed the selected date, chance will be given to us and if the selected date has
changed, we can write C# code to correct that and change the selected date back to what we want. So
we will double click on the SelectionChanged event.
Slide 14
We write the code which ensures that the one which checks if ( calDoJ.SelectedDate >
DateTime.Now ) and if it is true then we say calDoJ.SelectedDate = DateTime.Now. It can never go
beyond the current time. This allows to reset the selection back to a date of our choice. Calendar
control when sees this value being changed, automatically reverts back to the current date and will
never allow the user to go beyond today. So we avoided date in future with the help of event handler.
Slide 19
When we do so, a new window opens. It shows some readymade regular expressions for commonly
validated input. Among them, we will find Internet email address as one of the expressions. We will
select that.
Slide 20
Once we select that, the corresponding regular expression will be shown in the textbox below that.
We haven’t written that regular expression. We are used it. Then click on OK.
Slide 29
As soon as we double-click on the Add Now! button, a btnAdd_Click( ) event will get added in the
code behind.
In the Insert( ) function, the parameter that is going to be cityid in which the employee resides. We
are going to make use of the connection string in the web.config, also in this class. So we create new
SqlConnection object. ConfigurationManager is a class that allows us to access a section in the
connection strings in web.config. We use EmpConStr and say
ConfigurationManager.ConnectionStrings ["EmpConStr"].ConnectionString. Now we must create the
INSERT query. We must create a parameterized query and set it in the SqlCommand object. We have
created SqlTransaction object reference in variable t. We create a query "INSERT INTO Employees "
+ "( EmpName, AddLine1, AddLine2, CityId, Pin, " + "Gender, PhotoUrl, Email) VALUES " + "(
@EmpName, @AddLine1, @AddLine2, @CityId, " + " @Pin, @Gender, @PhotoUrl, @Email);
SELECT @@IDENTITY ". If there is @@ then it indicates that there is a special variable in SQL
server which we do not have to define. At the end of INSERT, the record is also going to get
automatically assigned a numeric identity field value. If we write the SELECT statement which
selects the variable @@IDENTITY, the SQL database server will give us the value of that Identity
Column. Unless we do that, we will not know the Id of the employee. In this SQL statement there are
two statements, one followed by another. To execute the command, we set the cmd.CommandText =
insertQuery and then say cmd.Connection = conn.
Slide 31
Now we need to add all parameters. So we have added all the parameters one by one as shown in the
slide using cmd.Parameters.Add( ). To execute the command, we open the connection. But instead of
executing the command immediately, we start database transaction. In the process of insertion, we are
going to update the Employee table. So, one record gets created there. We are also going to update
the EmployeeHobbies table multiple times. Because if the employee has 4 hobbies then we are going
to make 4 insertions in that table. So together we are performing 5 insertions. Any time when we are
changing database in more than one rows, in more than one tables, we have to use transactions to
ensure, in case the operation is terminated for any reason, in the middle of everything the database is
not left in an inconsistent state. Transactions allow us to do that. Transaction will keep track of all the
changes that are made against a particular transaction that we begin and unless we commit it those
changes will never be visible to anybody else. As the transaction is happening, nobody else can make
changes and mess around with these changes in the middle of it. If we say that in a middle of a
transaction, we cannot finish the transaction because we have encountered the error, we have to roll
back the transaction and then every change that we have made so far will be reverted back. So
database will be brought back to the original state. So transaction ensures atomicity; either the old
state or the completely new state. To begin a transaction, we have to use a connection object i.e.
conn.BeginTransaction( ). The method BeginTransaction( ) can only be called after the connection
has been opened. We have collected the return value of that in variable t. Then we have assigned this
transaction reference to the property cmd.Transaction i.e. cmd.Transaction = t. Then we fire the
query. For that we use ExecuteScalar( ). So we say cmd.ExecuteScalar( ) because we are going to
return the Employee’s Id. We collect the return value in mEmpId. So we get the Id for newly created
employee.
Slide 32
Now we want to clear the parameters array in the ArrayList because we are feeding new parameters.
So we say cmd.Parameters.Clear( ). Then we want the text for insertion. So the text is "INSERT
INTO EmployeeHobbies ( EmployeeId, HobbyId ) " + "VALUES ( @EmpId, @HobbyId )". For
every hobby, EmpId is not going to change. So for 1st parameter we say cmd.Parameters.Add ( new
SqlParameter ( "@EmpId", SqlDbType.BigInt ) ). Then we add the 2nd parameter using
cmd.Parameters.Add ( new SqlParameter ( "@HobbyId", SqlDbType.TinyInt ) ). Then we assigned
the value to the 1st parameter by saying cmd.Parameters [ "@EmpId" ].Value = EmpId. We obtained
the EmpId after doing insert in the Employee table. Then we run a for loop on the list of hobbies that
we have obtained. Inside the loop, we say cmd.Parameters[ "@HobbyId" ].Value = Convert.ToByte (
Building Portals Through ASP.NET EmpMgmt – Finishing Touches 129
hobby ) and then fire the query using cmd.ExecuteNonQuery( ). Now we commit the changes to the
database using t.Commit( ).
Slide 33
If there is an exception, the transaction is no longer committed. For that inside the catch block, we
check if ( t != null ) and if it is true then we roll back the transaction using t.Rollback( ). In the finally
clause, we check if ( conn != null ) and if it is true then we close the connection using conn.Close( ).
Default.aspx.cs: DisplayEmployeeInfo
When we display the employee information, we have to put line breaks between different properties
of that employee and then create a string using String.Format( ). We set the return value of that into
the property lblEmpInfo.Text and it ensures that the correct text had displayed. For hobbies we walk
through collection of hobbies using foreach loop and then append it to the label lblEmpInfo. Then we
make lblEmpInfo.Visible = true and imgPhoto.Visible = true. The URL for that image control that we
had inserted has to be set to the PhotoUrl Employee object i.e. we say imgPhoto.ImageUrl =
emp.PhotoUrl.
Default.aspx.cs: btnAdd_Click
Inside this first we create the Employee object and get the object’s properties using
GetEmployeeInfo( ). Then we check if the file has indeed been uploaded by checking
fileUplPhoto.HasFile. So we check if ( fileUplPhoto.HasFile &&
fileUplPhoto.PostedFile.ContentLength < 200 * 1024 ) and if these two conditions are satisfied then
we are going to create a directory called as images in the root directory. For that we use
Server.MapPath( ) method to map ~/images/. Then we use Directory.Exists( ) method to check if the
directory already exists. If it is there then we do not want to create it. If it is not there then we call
Directory.CreateDirectory ( dir ) to create the images directory. Then we call
fileUplPhoto.PostedFile.SaveAs ( dir + fileUplPhoto.FileName ). Then we say emp.PhotoUrl =
"~/images/" + fileUplPhoto.FileName. Once this is done, we have to actually insert the employee
inside the database including the URL for the photograph. For that we have to select city using
lstCity.SelectedItem.Value and pass it as a parameter to the emp.Insert( ) function. This actually
inserts the record in a database. Then we say tblReg.Visible = false and then we call the function
DisplayEmployeeInfo ( emp ).
Slide 38
Then we insert the name, address line1, address line2, state, city and pin code. Then we selected the
gender and lastly the date of joining for the employee as shown in the web browser in the slide.
130 EmpMgmt – Finishing Touches Building Portals Through ASP.NET
Slide 39
Then we browse the photo url, enter the email address and select different hobbies. Then we click on
Add Now! button.
Result
When we click on the button, actual addition will happen to the database. Then we will also see the
label which indicates that information is inserted in the database and photograph tells that file was
actually uploaded to the server. So the final result is as shown in the slide.
Building Portals Through ASP.NET GridView Control 131
GridView Control
In this lecture you will understand:
Data access approaches
Declarative approach - Data-binding model
Players involved in declarative model
Using GridView control to display contact book
132 GridView Control Building Portals Through ASP.NET
file and the new is LINQ DataSource. LINQ stands for Language Integrated Query. These four
primary DataSource controls feed into the popular DataBound controls that we have in ASP.NET 3.5.
We have seen ListBox, CheckBoxList and DropDownList. There are several others like DetailsView,
GridView, TreeView, a Menu control and FormView. There is large number of such DataBound
controls. Their ability to work with the display purpose of data makes them special. But they could be
receiving the data from any one of these DataSource controls. For example, now the GridView
control might be displaying the data from the SQL server database but the GridView is capable of
displaying data even from an Object source. So DataSource control is a generic mechanism whose
purpose is to feed the data to the corresponding DataBound controls. So this three layer separation
between the DataSource and the DataBound controls allows to plug-in different kinds of sources that
feed to various DataBound controls.
Goal
Our goal is to load the data from ContactsDB.mdf which is a Microsoft SQL server database file. To
work with that, we are going to use SQLDataSource control so that we can generate queries for
loading the data, inserting the data, updating the data and deleting the data and the data that gets
retrieved is displayed inside a GridView control. GridView control is about displaying the data in a
tabular format. Earlier we wrote our own code to create the table, to add the rows, to add the data to
the rows. All of that was done ourselves. Now we are going to see a declarative approach for doing
this with the help of GridView and SQLDataSource control. Our end objective is shown in the slide.
Steps Involved
In this case there are four distinct steps. First is we copy the previous project Contacts_SqlSimple to
the project Contacts_GridView which is the name of the new project. Once we do that, we have to
open the Default form and then add the GridView control to that form. Once the GridView control is
added, we have to specify where the data for this GridView control is going to come from. For that
we need DataSource control. Once the DataSource control is bound to a database, we are going to
display the data in the GridView.
Change Title
Once the form is added, the default title is Untitled Page. We change it to Contacts :: GridView. Then
go to the Design view.
Once we drag and drop, in the Design view, we will see a default view of this GridView control
which says that there is Column0, Column1 and Column2. There is abc in the cells of the columns.
This is the pictorial representation of how the data would be presented to the user or displayed to the
user. GridView right now does not know what is going to be displayed in Column0, Column1 and
Column2. We have to help it to do that. For that we have to go to the tasks for GridView. For that we
have to select the GridView and click on the Smart tag which is next to the GridView control. Among
the tasks it says, there is a Choose Data Source task. If we click on the drop down, we will find that
there is currently no data source. So we will begin with New Data Source.
Select Fields
So the default SELECT statement is SELECT * FROM [Contacts]. Then we click on Next.
Finish
If we want, we can test the results of the query and then we click the Finish button.
Test ContactView
When we come back, on the page just below GridView, we will actually see the SqlDataSource
control with the name ContactsDataSource and that is the DataSource to which our DataBound
control GridView is bound. Now we see a 3 tier model; DataBound control, DataSource control and
an actual database. We have to set ContactsGrid.aspx as the startup page by right clicking on that
page and then say Set As Start Page. Then we hit CTRL + F5.
Building Portals Through ASP.NET GridView Control 135
Result
When we load the form, we will see that in the GridView window, the column Name, Telephone and
Mobile number appears. Then the name appears Sachin R Tendulkar appears in the 1st row. His
telephone number and the mobile number appear in the next two cells of the same row as shown in
the slide. The SELECT query once we configure is being fired by the DataSource control to fetch the
data. The results of that query are being fed into the GridView control and GridView control takes it
and creates the HTML markup necessary to display the data in a tabular format.
136 GridView Edit And Delete Building Portals Through ASP.NET
Goal
As we did in the past, our objective is to display the data in the SQL server database file
ContactsDB.mdf in a GridView. For that we have used the SqlDataSource control as an intermediary
and the GridView is no longer going to be expected to perform the display operation. We expect that
the GridView should allow to edit existing information and delete the existing contacts from the
table. Snapshot given in the slide contains links to edit a contact and to delete a contact in every row
of the GridView. Those capabilities certainly exist.
Steps Involved
There are total 4 steps of doing this process. First is to change the database design and then save it.
2nd is to change the Data Source control because right now the SqlDataSource control fetches only
three columns from the database. We have to change it. In addition to be able to make the changes,
we have to also make it aware of the Update query and the Delete query. We will then provide some
additional event handlers. Each control generates a set of events. GridView also generates events
when certain action happens with the GridView. For example, a contact gets deleted. If the contact
gets deleted, our requirement is that, the display should be refreshed automatically. Similarly if the
contact gets updated, the display should be refreshed automatically. Once all this is done, then we
will build it and test it.
going to be int. Mark it as a Primary key. Then go in the Properties window and then select ID as the
Identity Column. Once this is done, then we save the changes so that the database is updated. For
existing data in the database, the Identity Column automatically assigns unique values. Database
server takes care of this.
Finish
Then we come back, we click Next and then finally by clicking the Finish button, we finish the Data
Source configuration. We have selected additional column from the database table Contacts, we have
added a set of queries that would be required by the DataBound control to be able to make changes.
All these things are necessary before GridView can perform editing and deletion. So GridView is
capable of doing Editing and deletion only if the DataSource control to which it is bound, is capable
of doing it.
GridView tag. Everything between <asp:GridView> and </asp:GridView> remains same. Once the
GridView is made aware of the fact that the key in the database column or table that it is being
displayed is a column name ID, it can now uniquely identify a column and generate that as a
parameter for the Update as well as Select statement. So it can generate a right kind of request and
make those parameters available for the SqlDataSource. GridView and SqlDataSource work together
closely to actually carry out these operations and unless GridView knows which is the primary key
column, it will not be able to supply the correct parameters during the Update as well as deletion
process. Then save the aspx file.
Result
If we go back to the Design view, we will notice that in the Design view, the first column has
changed. In the 1st column, there are three hyperlinks for each row. 1st hyperlink is Edit, 2nd hyperlink
is Delete and 3rd hyperlink is Select. These are the links that the user will have to click on to carry out
those particular operations.
Make changes
When we click on Edit button, GridView automatically converts all the columns into editable format.
It converts Sachin R Tendulkar as a textbox. It converts telephone, mobile and ID columns into the
editable columns by making them look as a textbox. In the 1st column instead of Edit, Delete and
Select links, now two different links are displayed; Update and Cancel. In this we can make changes
in the name, telephone and mobile. ID cannot be changed because it’s a database primary key and it’s
an Identity Column.
Commit Changes
If we want to confirm the changes after the typing, then click on Update button. If we want to cancel
the changes then click on Cancel. It is like a Yes / No link. Suppose we change the name from Sachin
R Tendulkar to Sachin Ramesh Tendulkar and then click on Update link. Behind the scene this
140 GridView Edit And Delete Building Portals Through ASP.NET
generates the PostBack to the server. PostBack to the server causes the GridView to send a request to
update that specific record in the database with the help of SqlDataSource. After the Update has been
done, a RowUpdated event will be generated by the GridView. Since we have an event handler
registered, our event handler ContactView_RowUpdated( ) would be called automatically and inside
that we rebind the control to the DataSource, thereby loading the most up-to-date source.
Delete Contact
So finally when we go back to the normal view of a GridView which is the readonly view, the name
Sachin R Tendulkar has been replaced by Sachin Ramesh Tendulkar. So the database indeed has been
updated. Our display has also been refreshed. If we want to do deleting, we have to click the Delete
button. Delete button actually does the deletion immediately. There is no Yes / No type of prompt
which is available to the user. Once we click Delete, in the next page the Delete query is generated by
the SqlDataSource control. It is send to the database server. The row gets deleted. After that the
GridView generates a RowDeleted event. We have an event handler registered for this event with the
name ContactView_RowDeleted( ). So this event handler is going to be called on the server. All
these requests are Post requests which are send back to the server except that actual operations are not
being performed by us. We are doing something after the fact that the deletion has happened.
Result
When we do that, there is only one row which gets deleted. So in the final result the page is empty.
There is only title Contacts :: GridView. Data has been deleted because there was only one row in the
database table.
Building Portals Through ASP.NET DetailsView Control 141
DetailsView Control
In this lecture you will understand:
What is DetailsView control
Using DetailsView ASP.NET control
o Add New contact
o Bind to database
o Update existing contact
o Delete existing contact
142 DetailsView Control Building Portals Through ASP.NET
Steps Involved
To perform the task of adding a DetailsView control to a page, there are 5 distinct steps. First is to
add the DetailsView control to the page. Then we will bind it to the database. We will enable the
Edit, Insert operations. Then we will add some event handlers. At the end we will test the capabilities
of DetailsView.
Now we are required to configure the SELECT statement. We want all the columns from the table
Contacts but we want only single row. So we need a WHERE clause. So we select * and click on
WHERE.
Choose Column
From the list of columns we select ID as the column.
WHERE Expression
Expression is going to be a equality expression. So we select = operator. We have to specify where
the value of ID is going to come from i.e. we have to specify Source. So we click on the Source drop
down list.
Add Expression
Once we select that, in the Value box we can see that ContactView.SelectedValue. So SelectedValue
is a property in the GridView object. We use that as the input for selecting the single record to be
displayed in a DetailsView control. Then we click on Add button.
Result
When we do so, it adds the expression to the WHERE clause. Then we click on OK.
Select Advanced
When we click on OK, we come back to the main screen where it displays the SELECT statement as
SELECT * FROM [Contacts] WHERE ([ID] = @ID). To generate Update, Insert and Delete queries
we click on the Advanced button. So we click on Advanced button.
Finish
144 DetailsView Control Building Portals Through ASP.NET
Finish (2)
Now we can test the query to make sure that the results are acceptable or we can click on Finish. So
we click on Finish button.
Result
When we do so, we will notice that in a row below the four rows that just got created, two links got
created; one link is Edit and another link is New. One is for editing the existing contact and another is
for inserting a new contact.
Click Edit
When we click the Select button, just below that the DetailsView will appear displaying the
information about exactly the same contact. So Sachin Tendulkar is displayed in a row-wise fashion
with Name, Telephone and Mobile followed by ID appearing as the rows in the table created by
DetailsView control. Final row contains Edit and New links. Now we click on the Edit link.
Building Portals Through ASP.NET DetailsView Control 145
Make Changes
If we click the Edit button, Edit and New are replaced by Update and Cancel. Depending upon what
we are doing, different links appear at the bottom of the table. Existing values are there. There are
textboxes to indicate that those values can be edited now. User can edit those values. Once we made
the changes, we can click the Update button to actually make the changes.
Commit Changes
So we change Sachin Tendulkar to Sachin R Tendulkar. Then we click the Update button.
Click New
Now both the views are updated as shown in the slide. Because after the item was updated,
ItemUpdated event was generated on the DetailsView inside which we called DataBind( ) on both
GridView as well as DetailsView control. So both GridView and DetailsView are refreshed
appropriately. To insert a new record with the help of DetailsView, we click on New button.
Insert Information
When we click on New button, the DetailsView enters in Insert mode. In Insert mode, textboxes
would appear wherever we are required to supply some parameters. So Name, Telephone and Mobile
are only become textboxes. ID does not get displayed because ID is a readonly field which comes
from the database server itself. We never write to the Identity Column ourselves. So Insert query will
have to be generated with only three parameters Name, Telephone and Mobile. Whenever the record
gets inserted, its ID will be assigned by the database server. The links have now changed to Insert and
Cancel which is like Yes and No.
Click Insert
Suppose we type Name as Rahul Dravid, his telephone number and mobile. Once we had done that,
we can click the link Insert.
Result
Moment we do that, on the server the request get send through the POST. Actual effect of that
request will be made by firing a query and getting the changes done in the database server. Followed
by which the event ItemInserted would be generated. Newly inserted item must appear in the
GridView. So we will refresh GridView and newly inserted item also appears in the DetailsView. So
we must refresh the data binding for that. So we call DataBind( ) function on both of these in the
ItemInserted event handler.