Final IT Lab Manual
Final IT Lab Manual
CERTIFICATE
has satisfactorily completed the lab exercises prescribed for Internet Technologies
Lab [CSE 4111] of Fourth Year B. Tech. Degree in Computer Science and Engg. at
Date: ……...................................
Signature
Faculty in Charge
CONTENTS
LAB PAGE
TITLE REMARKS
NO. NO.
Course objectives and outcomes 1
Evaluation Plan 1
Course Outcomes
At the end of this course, students will have the
Ability to develop a basic website using a modern web development tool.
Ability to design websites with better look and feel.
Expertise to create real-world web applications.
Evaluation Plan
Internal Assessment Marks : 60%
Continuous evaluation component (for each experiment):10 marks
The assessment will depend on punctuality, program execution, maintaining the
observation note and answering the questions in viva voce.
The marks of the 10 experiments except the mini project is valued out of 40 marks.
The mini project is valued out of 20 marks.
The total lab internal marks is 60.
1
INSTRUCTIONS TO THE STUDENTS
Pre-Lab Session Instructions
1. Students should carry the Lab Manual Book and the required stationery to every lab
session.
2. Be in time and follow the institution dress code.
On receiving approval from the instructor, copy the program and results in the Lab
Record.
Prescribed textbooks and class notes can be kept ready for reference if required.
o Programs should perform input validation (Data type, range error, etc.) and give
appropriate error messages and suggest corrective actions.
o Comments should be used to give the statement of the problem.
2
o Statements within the program should be properly indented.
o Use meaningful names for variables and functions.
Plagiarism (copying from others) is strictly prohibited and would invite severe
penalty in evaluation.
The exercises for each week are divided under three sets:
o Solved exercise
o Lab exercises – to be completed during lab hours.
3
LAB NO.: 1 Date:
I. DESCRIPTION
HTML5 is the 5th and newest version of HTML standard, providing new features
like rich media support, interactive web applications etc.
Several elements of HTML4 have been removed in HTML5 like <big>, <center>,
<font>, <frame>, <frameset>, <strike> etc.
To indicate that your HTML content uses HTML5, simply add <!DOCTYPE html>
on top of the html code.
4
In notepad type the necessary code & save with the file name mentioned with
.html or .htm extension.
Example:
<html>
<head>
<title> My First Page </title>
</head>
<body>
<h1> Hello </h1>
<h2> Welcome to Internet Technologies Lab </h2>
</body>
</html>
HTML5 Elements
HTML5 offers new elements for better document structure. The below given
table gives a brief description on few HTML5 elements.
TAG DESCRIPTION
5
<source> Defines multiple media resources for media elements
The above figure lists the new input types and attributes of HTML5.
HTML5 Events
On visiting a website the user perform actions like clicking on links or image,
hover over things etc. These are considered to be examples for Events.
6
Event handlers are developed to handle these events and this can be done using a
scripting language like JavaScript, VBScript etc wherein event handlers are specified as
a value of event tag attribute.
HTML5 Canvas
7
The HTML <canvas> element is used to draw graphics, on the fly, via JavaScript.
The <canvas> element is only a container for graphics. The user must use JavaScript to
actually draw the graphics. Canvas has several methods for drawing paths, boxes, circles,
text, and adding images.
A canvas is a rectangular area on an HTML page. By default, a canvas has no
border and no content. The markup looks like this:
<canvas id="myCanvas" width="200" height="100"></canvas>
Note: Always specify an Id attribute (to be referred to in a script), and a width and height
attribute to define the size of the canvas. To add a border, use the style attribute.
Example: To draw a circle
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(95,50,40,0,2*Math.PI);
ctx.stroke();
</script>
</body>
</html>
Output
Figure 1.4
8
HTML5 Web Forms
The HTML <form> element defines a form that is used to collect user input. Form
elements consist of various input elements like text field, check boxes, radio buttons,
submit buttons etc.
<form>
</form>
Input Element
It is the most important form element and can be displayed in several ways,
depending on the type attribute.
Action attribute
The action attribute defines the action to be performed when the form is submitted.
Usually the form data is sent to a web page on the server when the user clicks on the
submit button.
// action_page.aspx contains a server side script that handles the form data.
If the action attribute is omitted, the action is set to the current page.
Method attribute
The method attribute specifies the HTTP method (GET or POST) to be used
when submitting the form data.
9
The default method when submitting form data is GET. When GET is used the
submitted form data will be visible in the page address field. Therefore it must not be
used when sending sensitive information.
Use POST method if the form data contains sensitive or personal information. It
does not display the submitted form data in the page address field. It has no size
limitations and can be used to send large amounts of data.
1) Inline style – Right next to the text it decorates, by using style attribute.
<h1 style = “color : blue ;”> Hello </h1>
2) Internal style – At the top of the web page document, using <style> element in
<head>
<head>
<style>
h1 { color : blue ;}
</style> </head>
</head>
style.css
h1 { color : blue ;}
10
The style definitions are usually saved in an external stylesheet since changing
one single file can help in redesigning the entire web document with new look and feel.
CSS syntax
A CSS rule set consists of a selector and a declaration block. The selector points
to the HTML element to be styled. The declaration block contains one or more
declarations separated by semicolons.
CSS Selectors are used to “find” or select HTML elements based on their element
name, id, class, attribute etc. The element selector selects the elements based on the
element name. The id selector uses the id attribute of an HTML element to select a
specific element. The id of an element should be unique within a page. To select an
element with a specific id, write a # character followed by the id of the element.
#para1{
text-align: center;
color:red; }
The class selector selects the elements with a specific class attribute. To select
elements with a specific class, write a period (.) character, followed by the name of the
class.
.center {
text-align: center;
color:red; }
11
JavaScript
Syntax
It can be implemented using JavaScript statements that are placed within the
<script>….</script> HTML tags in a web page. The <script> tags, containing the
JavaScript code can be placed anywhere within the web page, but normally recommended
to place within the <head> tags.
The <script> tag alerts the browser program to start interpreting all the text
between these tags as script. The script tag have mainly two attributes language and type,
specifying the scripting language used.
</script>
12
Program:
Login.html
<!DOCTYPE html>
<html>
<head>
<title> Login page </title>
<style>
body {
background-color: lightblue;
}
h1 {
color: white;
text-align: center;
}
p{
font-family: verdana;
font-size: 20px;
}
</style>
<script language="javascript">
function check(form) /*function to check userid & password*/
{
/*the following code checkes whether the entered userid and password are
matching*/
if(form.userid.value == "myuserid" && form.pswrd.value == "mypswrd")
{
window.open("https://www.google.com", "_blank");
/*opens the target page while Id & password matches*/
}
else
{
alert("Error Password or Username") /*displays error message*/
}
}
</script>
13
</head>
<body>
<h1> Validate Credentials </h1>
<form name="login">
Username<input type="text" name="userid"/>
Password<input type="password" name="pswrd"/>
<input type="button" onclick="check(this.form)" value="Login"/>
<input type="reset" value="Cancel"/>
</form>
</body>
</html>
Output
Figure 1.5
14
III. LAB EXERCISE:
15
LAB NO.: 2 Date:
I. DESCRIPTION
Variables can store numbers, text, dates, times, and they can even point to full-
fledged objects. When a variable is declared, it is given a name, and the type of data it
will store is specified.
//Declare a string variable named myName.
string myName;
Conditional logic - deciding which action to take based on user input, external
conditions, or other information.
To build a condition, any combination of literal values or variables along with
logical operators can be used.
The comparison operators (<, >, <=, >=) with numeric types and with strings can
be used.
C# has three basic types of loops.
for loop: loop a set number of times
foreach loop: loop all the items in a collection of data
while or do…while loop: loop while certain condition holds true
C# provides a foreach block that allows the user to loop through the items in a set of
data. Here a variable that represents the required type of data has to be created. The code
will then loop until each piece of data in the set has been processed. The variable in the
block is read only.
string[] stringArray = {“One”, “Two”, “Three”};
foreach (string element in stringArray )
{
16
//This code loops 3 times, with element variable set to “One”, then “Two”and then
“Three”
Console.WriteLine( element + “ ” ); }
6) Once the program compiles and runs, the Console window opens and the result
of addition of two integers is displayed. Press any key to exit the program.
Output:
Figure 2.1
Steps to create a Windows Forms Application:
1) On the File menu, click New Project.
The New Project dialog box appears. This dialog box lists the different
application types that Visual C# Express Edition can create.
2) Select Windows Forms Application as the project type.
3) Change the name of the application if required.
4) Click OK.
Visual C# Express Edition creates a new folder for the project with the same name
as the project title, and then displays the new Windows Form, titled Form1
in Designer view. The user can switch between the Designer view and Code view
at any time by right-clicking on the design surface or code window and then
clicking View Code or View Designer respectively.
5) Drag and drop two TextBoxes, two labels and two buttons in the Designer from
the ToolBox. Name the buttons as Submit and Clear by right-clicking the buttons
and editing their names from the Properties Window.
6) Paste the following code in the Form1.cs file. Check the id’s of the various
controls in the code and change them according to the control id’s. button1_Click
and button2_Click are the event handlers for the two buttons in the Designer.
These event handlers can be generated by simply double-clicking on the buttons
in the Designer View.
using System;
namespace WindowsFormsApplication1
18
{
public partial class Form1 : Form
{
private void button1_Click(object sender, EventArgs e)
{
double n1;
double.TryParse(TextBox1.Text, out n1);
TextBox2.Text = (n1 * 2).ToString();
}
private void button2_Click(object sender, EventArgs e)
{
TextBox1.Text = TextBox2.Text ="";
}
}
}
7) Build and Run the program.
Output:
Figure 2.2
20
LAB NO.: 3 Date:
C# PROGRAMMING –
ARRAYS, CLASSES, INHERITANCE AND POLYMORPHISM
Objectives:
In this lab, student will be able to:
Understand the fundamentals of C# Programming Language.
Learn how to use arrays, class, inheritance, polymorphism and simple windows
controls.
I. DESCRIPTION
Arrays:
Arrays allow you to store a series of values that have the same data type. All arrays
start at a fixed lower bound of 0.
//Create an array with four strings (from index 0 to index 3).
string[] stringArray = new string[4];
stringArray = {"1", "2", "3", "4"}
//Create a 2 x 4 grid array (with a total of eight integers).
int[,] intArray = new int[2, 4];
intArray = {{1, 2}, {3, 4}, {5, 6}, {7, 8}}
//Access the value in row 0 (first row), column 1 (second column).
int num;
num = intArray[0, 1] // num is now set to 2.
Classes:
Classes are the code definitions for objects. Several instances of a class can be
created. Classes interact with each other with the help of three key ingredients:
Properties: Properties allow the user to access an object’s data. (Some of the
properties are read-only. Ex: Length)
Methods: Methods allow the user to perform an action on an object. (Ex: Open()
used to connect to Database)
Events: Events provide notification that something has happened. (Ex: if a user
clicks a button, the Button object fires a Click event.)
Creating a simple class:
public class Product
{
//Class code goes here
21
}
If there is a class named ‘Product’, then its object can be created as follows:
Product saleProduct = new Product();
Product objects can be manipulated in a safe way. This can be done by adding
Property Accessors.
Accessors usually have two parts.
Get accessor - Allows the code to retrieve data from the object.
Set accessor - Allows the code to set the object’s data.
public class Product
{
private string name;
private decimal price;
private string imageUrl;
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
}
In Main:
Delegates:
Delegates allow to create a variable that “points” to a method. The first step when
using a delegate is to define its signature.
The signature is a combination of several pieces of information about a method:
its return type, the number of parameters it has, and the data type of each parameter. A
delegate variable can point only to a method that matches its specific signature.
private string TranslateEnglishToFrench(string english)
22
{
//Code here
}
The declaration of Delegate
private delegate string StringFunction(string inputString);
functionReference = TranslateEnglishToFrench;
Events:
Classes can use the events to allow one object to notify another object that’s an
instance of a different class. As an illustration, the Product class example has been
enhanced with a PriceChanged event that occurs whenever the price is modified through
the property procedure. This event won’t fire if code inside the class changes the
underlying private price variable without going through the property.
Static properties and methods can be used without a live object. Static members
are often used to provide useful functionality related to an object. For example a static
variable can be used to keep a count of number of times the object of a class has been
instantiated.
To create a static property or method the static keyword is used after the
accessibility keyword
public class TaxableProduct
{
public static decimal taxRate = 1.15M;
}
The tax rate information can now be obtained directly from the class, without
24
needing to create an object first:
TaxableProduct.taxRate = 1.24M;
string collegeName;
string principalName;
26
}
}
Output:
Figure 3.1
27
IV. ADDITIONAL EXERCISES:
1) Write a program in C# to demonstrate declaration, instantiation, and use of a
delegate, TaxCalculator, that can be used to reference methods, TaxIndia
(decimal) and TaxUS (decimal), which calculates tax for salaried individuals
based on various tax slabs according to government rules of the particular nation
and returns the tax payable value in decimal.
2) Create a class named EBBill. This class contains four variables named
ownerName, houseNumber, unitsConsumed and metreRent. Among these four
variables, the variable metreRent is a shared variable, while other three variables
are instance variables. Create simple C# windows application to compute
electricity bill and display the name of the owner and electricity bill. (Total
amount = 1.2 * Units Consumed + Metre Rent).
28
LAB NO. : 4 Date:
WEB FORMS AND WEB CONTROLS
Objectives:
In this lab, student will be able to:
Understand the fundamentals of web forms creation
Design ASP.NET web applications using various web controls
I. DESCRIPTION
ASP.NET websites include multiple web pages. Server controls are considered to
be the basic building block of every web form. Using these server controls, ASP.NET
applications (a combination of files, pages, handlers, modules and executable code that
can be invoked from a virtual directory on a web server) are created.
Eg: <input type = submit value = “OK” ID = “Click” runat = “server” />
29
validation controls. These controls begin with “<asp:” and contain the attributes
runat and id with them.
The file types that end with .cs are code-behind files that contain C# code. They allow
the user to separate the application logic from the user interface of a web page. The
web.config is the configuration file for the ASP.NET application. It includes settings for
customizing security, state management, memory management, and much more. The
basic web control classes and the underlying HTML elements are shown in the table
below:
1. Right-click the website in the Solution Explorer and choose Add ➤ Add New Item.
2. In the “Add New Item” dialog box, choose Web Form (which should be first in the
list).
4. Make sure the “Place Code in Separate File” option is selected (it’s in the bottom-right
corner of the window).
The web form begins with a page directive that provides ASP.NET basic
information about how to compile the web page. It indicates the language the user is using
for the code and the way the user has connected the event handlers. If the user is using
the code-behind approach, which is recommended, the page directive also indicates where
the code file is located and the name of the custom page class.
The user needs to add the attribute runat = "server" to each tag that he/she wants
to transform into a server control. The user should also add an ID attribute to each control
that needs to interact with in code. The ID attribute assigns the unique name that can be
used to refer to the control in code.
CurrencyConverter.aspx
<!DOCTYPE html>
31
<html >
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label runat="server" id=”lb” >Input Currency:/>
<asp:TextBox runat="server" id="inputCurrency"/>
< asp:Label id="fromLable" runat="server" >From USD to:/>
<asp:DropDownList id="fromCurrencyDropDown" runat="server"/>
<br /> <br />
< asp:Label runat="server" id="labelAns" />
<br /> <br />
<asp:Button Text="Convert!" OnClick="SubmitClickedEvent" runat="server"/>
<br />
<br />
</div>
</form>
</body>
</html>
CurrencyConverter.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
32
fromCurrencyDropDown.Items.Add(new ListItem("INR", "65.3"));
fromCurrencyDropDown.Items.Add(new ListItem("Japanese Yen", "110.33"));
fromCurrencyDropDown.Items.Add(new ListItem("Euro", "0.85"));
}
}
string convertCurrency()
{
double oldValue = 0;
double newValue = 0;
double.TryParse(inputCurrency.Value, out oldValue);
ListItem temp =
fromCurrencyDropDown.Items[fromCurrencyDropDown.SelectedIndex];
newValue = oldValue * double.Parse(temp.Value);
Output
Figure 4.2
33
III. LAB EXERCISES:
1) Develop a simple ASP.NET web form that generates the front cover for a
magazine. The form should provide the options for selecting the image,
background color, changing font size, color etc. Input messages must be taken
from the user so as to display it on the front cover with legible font family and
font size. The controls added must be proportionate to the web page size.
2) Create a web form using web controls, with employee ids in dropdown list. When
the user selects the employee id, his image should be displayed in the image
control. Let the next focus be on the TextBox named “name of the employee”.
Use another TextBox for date of joining. Add a button as “Am I Eligible for
Promotion”. On clicking the button, if he has more than 5 years of experience,
then display “YES” else “NO” in the label control.
3) Develop a simple dynamic e-card generator. E-card generator should provide
options to select background colour, type of font, font size. An image can be
included in the e-card with an option to provide input message.
4) Develop simple application using web controls to reproduce the given Captcha.
Upon match, suitable message has to be displayed. If there is a mismatch for more
than 3 times, TextBox has to be disabled. (Hint: Use Hidden TextBox).
I. DESCRIPTION
The most significant difference between programming for the Web and
programming for the desktop is state management—how you store information over the
lifetime of your application.. This information can be as simple as a user’s name or as
complex as a stuffed-full shopping cart for an e-commerce store.
In a typical web request, the client connects to the web server and requests a page.
When the page is delivered, the connection is served, and the web server discards all the
page objects from memory. By the time the user receives a page, the web page code has
already stopped running, and there’s no information left in the web server’s memory.
The client side state management techniques include viewstate and cookies. The
session state and application state are considered to be a server side state management
technique. Cross page posting and querystring are the techniques used for transferring
information between web pages.
Client side objects are page(s) scope objects that used to keep data in safe from
postbacks, or to be transferred between pages.
1. Viewstate
The most common ways to store information is in view state.
Uses a hidden field that ASP.NET automatically inserts in the final, rendered
HTML of a web page.
The ViewState property of the page provides the current view state
information.
The “this” keyword refers to the current Page object. It's optional.
this.ViewState[“Counter”] = 1;
The key name is used to retrieve the value. The user needs to cast the
retrieved value to the appropriate data type using the casting syntax.
35
This extra step is required because the ViewState collection stores all items
as basic objects, which allows it to handle many different data types.
int counter;
counter = (int)this.ViewState[“Counter”];
2. Cookies
Cookies provide another way so that the user can store information for
later use.
They are small files that are created in the web browser’s memory (if
they’re temporary) or on the client’s hard drive.
Both the Request and Response objects (which are provided through Page
properties) provide a Cookies collection.
The user can retrieve cookies from the Request object, and set cookies
using the Response object.
To set a cookie, just create a new HttpCookie object.
HttpCookie cookie = Request.Cookies[“Preference”];
A cookie added in this way will persist until the user closes the browser
and will be sent with every request.
Creating a longer-lived cookie is by setting an expiration date.
cookie.Expires = DateTime.Now.AddYears(1);
To get more specific details, such as control values, you need to cast the
PreviousPage reference to the appropriate page class.
public partial class CrossPage2 : System.Web.UI. Page
{
protected void Page_Load(Object sender, EventArgs e)
{
if( PreviousPage != null)
{
lblInfo.Text = “You came from a page titled ”+PreviousPage.Title;
}
37
}
}
The page checks for null reference before attempting to access the
PreviousPage object. If it’s a null reference, no cross-page postback took
place.
4. Querystring (Transfer information between pages)
These are used to transfer the data through pages.
Common approach is to pass information using a query string in the URL.
This approach is commonly found in search engines.
http://www.google.co.in/search?q=organic+gardening
The querystring is the portion of the URL after the question mark. In this
case, it defines a single variable named q, which contains the string
organic+gardening.
Go to newpage.aspx. Submit a single query string argument named
recordID, and set to 10.
Response.Redirect("newpage.aspx?recordID=10")
The user can send multiple parameters as long as they’re separated with an
ampersand (&):
Go to newpage.aspx. Submit two query string arguments: recordID (10)
and mode (full).
Response.Redirect("newpage.aspx?recordID=10&mode=full")
It can receive the values from the QueryString dictionary collection exposed
by the built-in Request object:
string ID = Request.QueryString["recordID”];
It supports all characters that are alphanumeric or one of a small set of
special characters (including $-_.+!*'(),).
Some characters have special meaning.
o The ampersand (&) is used to separate multiple query string
parameters
o The plus sign (+) is an alternate way to represent a space
o The number sign (#) is used to point to a specific bookmark in a web
page.
If the user tries to send query string values that include any of these
characters, some of the data will be lost.
38
To solve this problem URL encoding is applied on text values before they
are placed in the query string.
With URL encoding, special characters are replaced by escaped character
sequences starting with the percent sign (%), followed by a two-digit
hexadecimal representation.
Example: The & character becomes %26
To perform URL encoding, the UrlEncode() and UrlDecode() methods of the
HttpServerUtility class are used.
string url= "QueryStringRecipient.aspx?"
Url += "Item=" + Server.UrlEncode(lstItems.SelectedItem.Text) + "&“;
Url += "Mode=" + chkDetails.Checked.ToString() ;
Response.Redirect(Url)
Use the UrlDecode() method to return a URL-encoded string to its initial
value.
ASP.NET automatically decodes the values when they are accessed through
the Request.QueryString collection in query strings.
Storing custom objects in viewstate
To store an item in view state, ASP.NET must be able to convert it into a stream
of bytes so that it can be added to the hidden input field in the page. This process is
called serialization.
To make the objects serializable, a Serializable attribute has to be added before
the class declaration.
[Serializable]
Then it can be stored in View State.
Customer cust = new Customer("Marsala", "Simons")
ViewState("CurrentCustomer") = cust
It is needed to cast the view state object.
39
Server side objects are domain scope objects that are used to store the data for
the use of whole application, including business logic and script language.
1. Session State
It allows the user to store any type of data in memory on the server.
The information is protected, because it is never transmitted to the client,
and it’s uniquely bound to a specific session.
Every client that accesses the application has a different session and a
distinct collection of information.
ASP.NET tracks each session using a unique 120-bit identifier.
ASP.NET uses a proprietary algorithm to generate this value.
This ID is the only piece of session-related information that is transmitted
between the web server and the client.
When the client presents the session ID, ASP.NET looks up the
corresponding session, retrieves the objects you stored previously, and
places them into a special collection so they can be accessed in the code.
This process takes place automatically.
For this system to work, the client must present the appropriate session ID
with each request.
The user can accomplish this in two ways:
Using cookies: In this case, the session ID is transmitted in a
special cookie (named ASP.NET_SessionId), which ASP.NET
creates automatically when the session collection is used. This is
the default.
Using modified URLs: In this case, the session ID is transmitted in
a specially modified (or munged) URL. This allows the user to
create applications that use session state with clients that don’t
support cookies.
The user can interact with session state using the
System.Web.SessionState.HttpSessionState class, which is provided in
an ASP.NET web page as the built-in Session object.
The syntax for adding items to the collection and retrieving them is
basically the same as for adding items to a page’s view state.
For example, the user might store a DataSet in session memory like this:
40
Session["InfoDataSet“] = dsInfo;
The user can configure session state through the web.config file for the
current application.
The configuration file allows to set advanced options such as the timeout
and the session state mode.
2. Application State
Application state allows to store global objects that can be accessed by
any client.
Application state is based on the System.Web.HttpApplicationState
class, which is provided in all web pages through the built-in Application
object.
Application state supports the same type of objects, retains information
on the server, and uses the same dictionary-based syntax.
Application state items are stored as objects, so the user needs to cast
them when retrieving them from the collection.
Items in application state never time out. They last until the application
or server is restarted or the application domain refreshes itself.
Count.aspx
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Counter</title>
41
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="buttonCounter" runat="server" OnClick="buttonCounter_Click"
Text="Click me!" />
<br /><br />
<asp:Label ID="labelCounter" runat="server" />
</div>
</form>
</body>
</html>
Count.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
ViewState["count"] = counter;
labelCounter.Text = "The button has been clicked " + counter.ToString() + "
times.";
}
}
42
Output
Figure 5.1
43
IV. ADDITIONAL EXERCISES:
1) Create a Register page and Success page with the following requirements:
i. Register page should contain four input TextBoxes for UserName,
Password, Email id and Contact Number and also a button to submit. Make the
username as compulsory field.
ii. On button click, Success page is displayed with message "Welcome
{UserName}" and also his Email and Contact Number has to be displayed.
iii. On button click without entering Username, an error message should be
displayed to the user in same page.
iv. Use secure technique to send details to the Success page.
2) Design a website with two pages.
First page contains:
Dropdown list with HP, Nokia, Samsung, Motorola, Apple as items.
CheckBox with Mobile and Laptop as items.
TextBox to enter quantity.
There is a button with text as "Produce Bill".
On Clicking Produce Bill button, item should be displayed with total
amount on another page.
44
LAB NO.: 6 Date:
VALIDATION, THEMES AND MASTER PAGES
Objectives:
The RequiredFieldValidator control ensures that the required field is not empty.
It is generally tied to a text box to ensure that the textbox is not empty.
<asp:RequiredFieldValidator ID="rfvcandidate"
runat="server" ControlToValidate ="ddlcandidate"
ErrorMessage="Please choose a candidate"
InitialValue="Please choose a candidate">
</asp:RequiredFieldValidator>
The RangeValidator control verifies that the input value falls within a
predetermined range.
<asp:RangeValidator ID="rvclass" runat="server" ControlToValidate="txtclass"
ErrorMessage="Enter your class (6 - 12)" MaximumValue="12"
MinimumValue="6" Type="Integer">
45
</asp:RangeValidator>
The CompareValidator control compares a value in one control with a fixed value
or a value in another control.
<asp:CompareValidator ID="vldRetype" runat="server"
ErrorMessage="Your password does not match." ControlToCompare="txtPassword"
ControlToValidate="txtRetype" >
</asp:CompareValidator>
The following two mutually inclusive properties list out the error message:
ShowSummary : shows the error messages in the specified format.
ShowMessageBox: shows the error messages in a separate window.
Themes:
To use the theme in a web application, the user needs to create a folder that defines it.
The created folder should be placed in the App_Themes folder placed inside the top-
level directory for the web application. An application can contain definitions for
multiple themes, but each theme should be in the separate folder. Only one theme can
be active on a given page at a time.
47
To make the theme accomplish the work, the creation of at least one skin file in the
theme folder is necessary. A skin file is a text file with the .skin extension. Skin file is
essentially a list of control tags; the control tags do not need to completely define the
control. Set the properties that need to be standardized.
To add a theme to the project, select Website ➤ Add New Item and choose Skin File.
Master Pages:
ASP.NET master pages allow the user to create a consistent layout for the pages in the
application. A single master page defines the look and feels and standard behavior that
the user wants for all of the pages (or a group of pages) in his application. The user can
then create individual content pages that contain the content he wants to display. When
users request the content pages, they merge with the master page to produce output that
combines the layout of the master page with the content from the content page.
The master page is identified by a special @ Master directive that replaces
the @ Page directive that is used for ordinary .aspx pages.
In addition to static text and controls that will appear on all pages, the master page also
includes one or more ContentPlaceHolder controls. These placeholder controls define
regions where replaceable content will appear. In turn, the replaceable content is defined
in content pages.
Sample Master Page
<%@ Master Language="C#" CodeFile="MasterPage.master.cs"
Inherits="MasterPage"%>
<html>
<head runat="server" >
<title>Master page title</title>
</head>
<body>
<form id="form1" runat="server">
<table>
<tr>
<td><asp:contentplaceholder id="Main" runat="server" /></td>
<td><asp:contentplaceholder id="Footer" runat="server" /></td>
</tr>
</table>
48
</form>
</body>
</html>
MainPage.aspx.cs contents:
using System;
public partial class MainPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
themeDropDown.Items.Add("Monochrome");
themeDropDown.Items.Add("DarkGrey");
if (Session["Theme"] != null)
{
//FindByText searches the DropDownList for an Item with a Text property
that equals the specified text.
themeDropDown.Items.FindByText(Session["Theme"].ToString()).Selecte
d = true;
}
}
}
}
protected void Page_PreInit(object sender, EventArgs e)//change the theme
{
if (Session["Theme"] != null)
{
// sets the theme of the page dynamically to selected value from the
DropDownList
Page.Theme = Session["Theme"].ToString();
}
}
protected void themeDropDown_SelectedIndexChanged(object sender, EventArgs
e)
{
50
Session["Theme"] = themeDropDown.SelectedValue;
Server.Transfer(Request.FilePath);
}
}
Monochrome.skin contents:
<asp:Label runat="server" Font-Bold="true" Font-Names="Comic Sans MS"
ForeColor="BlueViolet" Font-Size="Large" />
<asp:TextBox runat="server" Font-Bold="true" Font-Names="Comic Sans MS"
ForeColor="BlueViolet" Font-Size="Large" />
<asp:Button runat="server" Font-Bold="true" Font-Names="Comic Sans MS"
ForeColor="BlueViolet" Font-Size="Large" />
Darkgrey.skin contents:
<asp:Label runat="server" Font-Names="Times New Roman"
ForeColor="DarkGray" Font-Size="Small" Font-Italic="true" />
<asp:TextBox runat="server" Font-Names="Times New Roman"
ForeColor="DarkGray" Font-Size="Small" Font-Italic="true" />
<asp:Button runat="server" Font-Names="Times New Roman"
ForeColor="DarkGray" Font-Size="Small" Font-Italic="true"/>
2) Develop a Web Application using ASP.NET for an E-Commerce firm. The master
page should consist of name of the firm, Logo and contact details. Also, it should
provide hyperlinks to Electronics, Baggages and Offers zone. These three pages
51
should be designed as content pages. The hyperlinks should navigate to these content
pages associated with Master Page designed. The Electronics page should display the
categories namely mobiles, laptops and printers. Also display the vendor names for
all the categories in DropDownList controls. The Baggages page can have images of
laptop bags, trolley bags, and backpacks. In the Offers zone page, add images to
display at least two offers. All the pages must have the same background image
(something that represents the firm). All the pages should be neat and well designed
(the contents added must be proportional to page size) and have an attractive look.
3) Create two themes: Summer and Monsoon. For each theme, add the CSS layout,
which is applied to the site automatically. Use appropriate background images to
represent each theme. Configure the application to use one of the themes and then
switch to the other to see the differences. Extend the above-created themes by adding
a DropDownList control which contains the available themes so that a user can choose
to dynamically switch between the themes. (any other appropriate controls(e.g.,
TextBox) can be added to the page to show the effect of themes changing).
4) Create a web application which includes Master Page and two content pages. The
master page should contain header footer and left pane. Include the stylesheet file for
the master page formatting. In the left pane, there should be a label. It should display
the Mobile Name selected from the drop-down list box of the First content page. The
first content page should contain dropdown list box with different mobile names, and
button. Some theme should be set as default. When you click the button second
content page should be displayed. The second content page should contain the label
where selected mobile's specification (Screen, Memory, Camera, and Battery) should
be displayed. There should be a back button which when clicked will display the first
content page.
52
symbol, Phone should contain only numbers and UserId should only contain
capital letters)
2) Create a web application with a Master page having a Panel and a Label (My
Page), two buttons (Internal, External) and a DropDownList with values- Please
select a theme, Solid and Dotted. On selecting “Solid,” apply changes to panel
width, border, and background color. Also, change the button background and
foreground colors. Apply similar changes on the selection of “Dotted” theme. On
click of Internal and External buttons navigate to respective content pages with
internal style and external styles applied to a label (change font family, font size,
color, and font weight).
53
LAB NO.: 7 Date:
MINI PROJECT – PHASE 1
Objectives:
54
LAB NO.: 8 Date:
WORKING WITH DATA - I
Objectives:
Connect the Web pages to the SQL Server database using direct & disconnected
data access methods.
I. DESCRIPTION
There is a tab for the Server Explorer on the right side of the Visual Studio
window, grouped with the Toolbox and collapsed. Click the tab to expand it. If
not, choose View ➤ Server Explorer to show it (or View ➤ Database Explorer
in Visual Studio Express for Web). Using the Data Connections node in the Server
Explorer, the user can connect to existing databases or create new ones.
2. When the “Choose Data Source” window appears, select Microsoft SQL Server
and then click Continue.
3. If the user is using a full version of SQL Server, enter “localhost” as the server
name. This indicates that the database server is the default instance on the local
computer. (Replace this with the name of a remote computer if needed.) If the user
55
is using SQL Server Express LocalDB (the version that’s included with Visual
Studio), then enter (localdb)\MSSQLlocalDB instead of localhost. If it is SQL
Server Express, the user needs to enter localhost\SQLEXPRESS instead.
4. Click the Test Connection button to verify if the location of the database is
correct. If the user has not installed a database product yet, this step will fail.
Otherwise, the database server is installed and running.
5. In the Select or Enter a Database Name list, choose the required database. If the
user wants to see more than one database in Visual Studio, he needs to add more
than one data connection.
6. Click OK. The database connection appears in the Server Explorer window.
The user can now explore its groups to see and edit tables, stored procedures, and
more. For example, if the user right-clicks a table and choose Show Table Data,
a grid of records are seen that can be browsed and edited.
SQL Basics
When working with ADO.NET, however, the user will probably use only the
following standard types of SQL statements:
Data providers are customized so that each one uses the best-performing way of
interacting with its data source.
ADO.Net Namespaces
Imports System.Data
Imports System.Data.SqlClient
There are two types of Data Access.
57
It is well suited to ASP.NET web pages, which do not need to keep a copy of their
data in memory for long periods.
To query information with simple data access, follow these steps:
1. Create a Connection, Command, and DataReader objects.
2. Use the DataReader to retrieve information from the database, and
display it in control on a web form.
3. Close the connection.
4. Send the page to the user. At this point, the information which the user
sees and the information in the database no longer have any connection,
and all the ADO.NET objects have been destroyed.
To add or update information, follow these steps:
1. Create new Connection and Command objects.
58
ListItem newItem = new ListItem();
newItem.Text=reader["au_lname"]+","+reader["au_fname"];
newItem.Value = reader["au_id"].ToString();
lstAuthor.Items.Add(newItem);
}
reader.Close();
}
catch (Exception err)
{
lblResults.Text = "Error reading list of names. ";
lblResults.Text += err.Message;
}
finally
{
con.Close();
}
}
2. Disconnected Data Access
A copy of the data is kept in the DataSet object so you can work with it after the
database connection has been closed.
The user connects to the database just long enough to fetch your data and dump it
into the DataSet, and then disconnects immediately.
The user fills the DataSet in much the same way that you connect a DataReader.
Datasets store a copy of data from the database tables.
Datasets cannot directly retrieve data from Databases.
DataAdapters are used to link Databases with DataSets.
If we see diagrammatically,
59
The DataAdapter.Fill() method takes a DataSet and inserts one table of
information.
To access the individual DataRows, the user can loop through the Rows
collection of the appropriate table. Each piece of information is accessed by
using the field name, as it was with the DataReader.
The sample showed in solved exercise.
Creating Connection to the data source
Before the user can retrieve or update data, he needs to make a connection to the
data source. Write the database code inside a try/catch error-handling structure so the user
can respond if an error does occur, and make sure to close the connection.
When creating a Connection object, the user needs to specify a value for its
ConnectionString property. This ConnectionString defines all the information the
computer needs to find the data source, log in, and choose an initial database.
Data source: name of the server where the data source is located,
“(localdb)\MSSQLlocalDB”
Initial Catalog: Default database, change with
Connection.ChangeDatabase( )
Integrated security: Windows user account, SSPI (Security Support
Provider Interface)
ConnectionTimeout: How long the code will wait, in seconds, before
generating an error if it cannot establish a database connection.
Eg: SqlConnection myConnection = new SqlConnection();
myConnection.ConnectionString = "Data Source=(localdb)\MSSQLLocalDB;" +
"Initial Catalog=Pubs;Integrated Security=SSPI";
All the database code in the application will use the same connection string.
Therefore, it usually makes the most sense to store a connection string in a class
member variable or, even better, a configuration file.
The <connectionStrings> section of the web.config file is a handy place to store the
connection strings. Here’s an example:
<configuration>
<connectionStrings>
<add name="Pubs" connectionString=
"DataSource=(localdb)\MSSQLLocalDB;Initial Catalog=Pubs;Integrated
Security=SSPI"/>
60
</connectionStrings>
. . . </configuration>
The user can then retrieve the connection string by name. First import the
System.Web.Configuration namespace. Then the following code can be used:
string connectionString =
WebConfigurationManager.ConnectionStrings["Pubs"].ConnectionString;
This approach helps ensure that all your web pages are using the same
connection string.
Table definition
61
Table data
Page1.aspx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
64
Output
Figure 8.5
Figure 8.6
65
2) Develop a web application that contains a DropDownList, a ListBox and a
textarea as shown in figure 8.8 below. Use a dictionary collection with values
“comedy”, “romance” and “animated” to bind with the DropDownList. On
selecting the values from the DropDownList, corresponding names are to be
retrieved from the table “Legends” in the database “Test” using direct data access
and those are to be bound with the ListBox. The schema of the table “Legends”
from “Test” is shown in figure 8.7. The textarea should display the name and age
of the ListBox selection as shown in figure 8.8. Use appropriate data source
controls for binding the textarea.
Figure 8.7
Figure 8.8
3) Consider the schema in figure 8.9 for table “Items” in the database “Products.”
66
Figure 8.9 Figure 8.10
Modifying the price of “Vanilla” (data are shown in figure 8.10) to the value taken
from a TextBox and update the database. Use direct data access and parameterized
commands.
2. Create a web page with DropDownList, Textboxes and Buttons. Assume the table
‘Human’ with First name, Last name, Phone, Address and City as fields. When
the page is loaded, only first names will be displayed in the drop-down list. On
selecting the name, other details will be displayed in the respective TextBoxes.
On clicking the update button, the table will be updated with new entries made in
the text box. On clicking the delete button, the selected record will be deleted from
the table, and the DropDownList is refreshed. Use direct access method and avoid
SQL injection attack.
67
LAB NO.: 9 Date:
WORKING WITH DATA - II
Objectives:
I. DESCRIPTION
Repeated-value data binding works with the ASP.NET list controls. To use
repeated-value binding, one of the below controls is linked to a data source (such as
a field in a data table).
When DataBind( ) method is called, the control automatically creates a full list using
all the corresponding values.
Some of the list controllers are:
• ListBox, DropDownList, CheckBoxList, and RadioButtonList
• HtmlSelect (Select)
• GridView
68
Data Binding with Dictionary Collection:
A dictionary collection is a special kind of collection in which every item is indexed
with a specific key.
There are two basic dictionary-style collections in .NET:
• The Hashtable collection (in the System.Collections namespace)
• The Dictionary collection (in the System.Collections.Generic namespace)
Sample code:
Step 1: Create and fill the collection
Dictionary<int, string>CSE = new Dictionary<int, string>( );
CSE.Add(1,"Operating Systems");
CSE.Add(2,"DBS");
CSE.Add(3,"FLAT");
CSE.Add(4,"Compiler Design");
CSE.Add(5,"Computer Networks");
Step 2: Define the binding for list controllers
MyListBox.DataSource = CSE;
MyListBox.DataTextField = "Value";
MyListBox.DataValueField = "Key";
Step 3: Activate Binding
this.DataBind( );
Data Source Controls:
Data source controls allow the user to create data-bound pages without writing any
data access code at all. They can retrieve data from a data source and supply it to bound
controls. They can update the data source when edits take place. (GridView)
Some of the data source controls included in the .NET Framework are:
• SqlDataSource: This data source allows the user to connect to any data source
that has an ADO.NET data provider.
• AccessDataSource: This data source allows the user to read and write the data
in an Access database file (.mdb).
• ObjectDataSource: This data source allows the user to connect to a custom data
access class.
• XmlDataSource: This data source allows the user to connect to an XML file.
69
The SqlDataSource:
<asp:SqlDataSource ID="SqlDS1" runat="server"
ProviderName="System.Data.SqlClient"
ConnectionString="<%$ ConnectionStrings:Student %>"
SelectCommand="SELECT * FROM Student">
</asp:SqlDataSource>
The ProviderName property gives the name of the data provider factory that has the
responsibility of creating the provider specific objects that the SqlDataSource needs to
access the data source. The ConnectionString property points to the connection string
defined in the web.config file.
The SqlDataSource supports four more properties:
• SelectCommand
• InsertCommand
• UpdateCommand
• DeleteCommand
Parameterized Commands:
The <SelectParameters> section inside the SqlDataSource tag defines each parameter
that are referenced by the SelectCommand and tells the SqlDataSource where to find
the value it should use. The parameter has to be mapped to a value in control. (Example
is given in Sample Exercise)
QueryString Parameter:
When the user wants to map the parameter to a value in the QueryString instead of any
other control, this parameter can be used.
Here is a Button event handler code in the first page to copy the selected product to
the query string and redirect the page.
protected void cmdGo_Click(object sender, EventArgs e)
{
if (lstProduct.SelectedIndex != -1)
{
Response.Redirect("QueryParameter2.aspx?prodID=" +
lstProduct.SelectedValue);
}
}
Finally, the second page can bind the GridView according to the ProductID value
that’s supplied in the Query String:
70
<asp:SqlDataSource ID="sourceProductDetails" runat="server"
ProviderName="System.Data.SqlClient"
ConnectionString="<%$ ConnectionStrings:Northwind %>"
SelectCommand="SELECT * FROM Products WHERE ProductID=@ProductID">
<SelectParameters>
<asp:QueryStringParameter Name="ProductID" QueryStringField="prodID" />
</SelectParameters>
</asp:SqlDataSource>
<asp:GridView ID="GridProduct" runat="server"
DataSourceID="sourceProductDetails" />
GridView:
The GridView is an extremely flexible grid control that displays a multicolumn table.
Each record in your data source becomes a separate row in the grid. Each field in the
record becomes a separate column in the grid. The GridView provides a DataSource
property for the data object the user wants to display.
71
II. SOLVED EXERCISE:
Design a website to load the names of students from a ‘Student’ table in a database
to a DropDownList. On selecting the student name from the list, the entire
information of that student must be displayed in a GridView. Use data source control
for fetching data.
Default.aspx.cs contents:
<form id="form1" runat="server">
Select Student:
<asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="SqlDS1"
DataTextField="Name" DataValueField="id" AutoPostBack="True">
</asp:DropDownList>
<br /> <br /> <br />
Web.config:
<connectionStrings>
72
<add name="Student" connectionString="Data
Source=(localdb)\MSSQLlocalDB;Initial Catalog=Test;Integrated Security=True"/>
</connectionStrings>
Output:
Figure 9.1
2) Develop an ASP.NET website to display the names of the tour packages available
with a travel agency in a Listbox using Sqldatasource in Page1. Use Sqldatasource
and GridView control to display the entire detail of the package in Page2 based
on the selection made in Page1 (the selected value in Page1 has to be sent to Page2
via querystring and in Page2 use Querystring parameter in sqldatasource control).
Sample table data given below.
id nchar(10)
name varchar(10)
age nchar(10)
category varchar(10)
74
IV. ADDITIONAL EXERCISES:
1) Create a website to display the details and user reviews on various books available
in a bookstore stored in an XML file using a GridView and an XmlDataSource
control.
Sample xml file content:
<?xml version="1.0" standalone="yes"?>
<bookstore>
<book ISBN="10-000000-001"
title="The Iliad and The Odyssey"
price="12.95">
<comments>
<userComment rating="4"
comment="Best translation I've read." />
<userComment rating="2"
comment="I like other versions better." />
</comments>
</book>
<book ISBN="11-000000-002"
title="Computer Dictionary"
price="24.95" >
<comments>
<userComment rating="3"
comment="A valuable resource." />
</comments>
</book>
</bookstore>
75
LAB NO.: 10 Date:
GRIDVIEW, FILES & XML
Objectives:
I. DESCRIPTION
The GridView is an extremely flexible grid control that displays a multicolumn
table. Each record in your data source becomes a separate row in the grid. Each field in
the record becomes a separate column in the grid. The functionality of the GridView
includes features for automatic paging, sorting, selecting, and editing.
Next, set the GridView.DataSourceID property to link the data source to the grid:
<asp:GridView ID = "GridView1" runat = "server" DataSourceID = "sourceProducts"/>
Figure 10.1
GridView Styles:
Figure 10.2
77
How to change formatting for a specific row or just highlight a single cell?
The GridView.RowDataBound event can be used for the above purpose. This
event is raised for each row, just after it is filled with data. At this point, the current row
can be accessed as a GridViewRow object. The GridViewRow.DataItem property
provides the data object for the given row and the GridViewRow.Cells collection allows
retrieving the row content. The GridViewRow can be used to change colors and
alignment, add or remove child controls, and so on.
The following example handles the RowDataBound event and changes the background
color to highlight high prices (those more expensive than $50):
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Get the price for this row.
decimal price = (decimal)DataBinder.Eval(e.Row.DataItem,"UnitPrice");
if (price > 50)
{
e.Row.BackColor = System.Drawing.Color.Maroon;
e.Row.ForeColor = System.Drawing.Color.White;
e.Row.Font.Bold = true;
}
}
}
78
Sorting:
The GridView sorting features allow the user to reorder the results in the
GridView by clicking a column header. To enable sorting in the GridView.AllowSorting
property must be set to true. Next, a SortExpression for each column that can be sorted
has to be defined.
<asp:BoundField DataField = "ProductName" HeaderText = "Product Name"
SortExpression = "ProductName" />
Paging:
To use automatic paging, the GridView.AllowPaging property has to be set to true
and the PageSize has to be set to determine how many rows are allowed on each page.
<asp:GridView ID = "GridView1" runat = "server" DataSourceID = "sourceProducts"
PageSize = "10" AllowPaging = "True" > </asp:GridView>
Figure 10.3
The Column ‘Status’ in the above snapshot is generated using the defined TemplateField.
79
The template only has access to the fields that are in the bound data object. So if the
UnitsInStock, UnitsOnOrder, and ReorderLevel fields have to be shown, the
SqlDataSource query has to be designed to return this information.
Editing with Templates:
Suppose it is required to edit any item in the TemplateField then an
EditItemTemplate section has to be added as shown below.
<asp:TemplateField HeaderText = "Status">
<ItemTemplate>
<b > In Stock:</b > <%# Eval("UnitsInStock") % > <br />
<b > On Order:</b > <%# Eval("UnitsOnOrder") % > <br />
<b > Reorder:</b > <%# Eval("ReorderLevel") %>
</ItemTemplate>
<EditItemTemplate>
<b > In Stock:</b > <%# Eval("UnitsInStock") % > <br />
<b > On Order:</b > <%# Eval("UnitsOnOrder") % > <br /> < br />
<b > Reorder:</b>
<asp:TextBox Text = ' < %# Bind("ReorderLevel") % > ' Width = "25px"
runat = "server" id = "txtReorder" />
</EditItemTemplate>
</asp:TemplateField>
Figure 10.4
Files:
The simplest level of file access involves just retrieving information about existing
files and directories and performing typical file system operations such as copying files
and creating directories.
.NET provides five basic classes for retrieving this sort of information. They are
all located in the System.IO namespace (and, incidentally, can be used in desktop
applications in the same way they are used in web applications).
They include the following:
80
The Directory and File classes, which provide static methods that allow the user
to retrieve information about any files and directories visible from the server.
The DirectoryInfo and FileInfo classes, which use similar instance methods and
properties to retrieve the same sort of information as Directory and File classes.
The DriveInfo class, which provides static methods that allow the user to
retrieve information about a drive and the amount of free space it provides.
.NET also includes a helper class named Path in the same System.IO namespace.
The Path class does not include any real file management functionality. It simply provides
a few static methods that are useful when manipulating strings that contain file and
directory paths.
The following are the various methods under the Path class.
The Directory and File classes provide some useful static methods. Figure 10.6
and Figure 10.7 show an overview of the most important methods. Most of these methods
81
take the same parameter: a fully qualified pathname identifying the directory or file for
which the user wants the operation to act on.
To create a DirectoryInfo or FileInfo object, the user should specify the full path in the
constructor:
This path may or may not correspond to a real physical file or directory. If it does not,
then the Create() method can be used to create the corresponding file or directory:
// Now create them. Order here is important. A file cannot be created in a directory that
doesn't exist yet.
myDirectory.Create();
myFile.Create();
The .NET Framework makes it easy to create simple “flat” files in text or binary
format. The user can write to a text file and read from a text file using a StreamWriter
and a StreamReader—dedicated classes that abstract away the process of file
interaction.
w = File.CreateText(@"c:\Temp\myfile.txt");
Using the StreamWriter, the user can call the WriteLine() method to add
information to the file. The WriteLine() method is overloaded so it can write many simple
data types, including strings, integers, and other numbers. These values are essentially all
converted into strings when they are written to a file and must be converted back manually
into the appropriate types when the file has to be read.
On completing the operations with the file, the user must make sure to close it by
calling the Close() or Dispose() method. Otherwise, the changes may not be properly
written to disk and the file could be locked open.
w.Close();
84
To read the information, the user can use the corresponding StreamReader class.
It provides a ReadLine() method that gets the next available value and returns it as a
string. ReadLine() starts at the first line and advances the position to the end of the file,
one line at a time.
StreamReader r = File.OpenText(@"c:\myfile.txt");
ReadLine() returns a null reference when there is no more data in the file. This
means that the user can read all the data in a file using code like this:
// Read and display the lines from the file until the end // of the file is reached.
string line;
do
{
line = r.ReadLine();
if (line != null)
{
// (Process the line here.)
}
}
while (line != null);
}
As when writing to a file, Close the file once the operations are done:
r.Close();
The user can also read and write to binary files. Binary data use space more
efficiently but also create files that aren’t human-readable. To open a file for binary
writing, the user needs to create a new BinaryWriter object. The constructor accepts a
stream, which can be retrieved using the File.OpenWrite() method. Here’s the code to
open the file c:\binaryfile. Bin for binary writing:
FileStream fs = File.OpenWrite(@"c:\binaryfile.bin");
BinaryWriter w = new BinaryWriter(fs);
85
.NET concentrates on stream objects, rather than on the source or destination for
the data. This means that the user can write binary data to any type of stream, whether it
represents a file or some other type of storage location, using the same code. Also, writing
to a binary file is almost the same as writing to a text file.
XML
<?xml version="1.0"?>
<SuperProProductList>
<Product>
<ID>1</ID>
<Name>Chair</Name>
<Price>49.33</Price>
<Available>True</Available>
<Status>3</Status>
86
</Product>
</SuperProProductList>
.NET provides a rich set of classes for XML manipulation in several namespaces
that start with System.Xml. One of the simplest ways to create or read any XML
document is to use the basic XmlTextWriter and XmlTextReader classes. These classes
work like their StreamWriter and StreamReader relatives, except that they write and read
XML documents instead of ordinary text files. A sample is as shown below:
To start building a next XML document, the user needs to create the XDocument,
XElement, and XAttribute objects that constitute it. All these classes have useful
constructors that allow the user to create and initialize them in one step. For example, the
user can create an element and supply text content that should be placed inside using code
like this:
Both the XDocument and XElement class include a constructor that takes a
parameter array for the last argument. This parameter array holds a list of nested nodes.
Here’s an example that creates an element with three nested elements and their
content:
XElement element = new XElement("Product",
new XElement("ID", 3),
new XElement("Name", "Fresh Fruit Basket"),
new XElement("Price", 49.99) );
Here’s the scrap of XML that this code creates:
<Product>
<ID>3</ID>
<Name>Fresh Fruit Basket</Name>
<Price>49.99</Price>
</Product>
89
II. SOLVED EXERCISE:
Using XmlTextWriter write the xml file in “App_Data\Cars.xml” (given in Fig 10.9).
Fig 10.9
Default.aspx.cs contents:
using System.IO;
using System.Xml;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Place the file in the App_Data subfolder of the current website.
// The System.IO.Path class makes it easy to build the full file name.
string file = Path.Combine(Request.PhysicalApplicationPath,
@"App_Data\Cars.xml");
FileStream fs = new FileStream(file, FileMode.Create);
XmlTextWriter w = new XmlTextWriter(fs, null);
w.WriteStartDocument();
w.WriteStartElement("Cars");
w.WriteComment("This file generated by the XmlTextWriter class.");
// Write the first car.
w.WriteStartElement("Car");
w.WriteAttributeString("ID", "1");
w.WriteAttributeString("Name", "I20");
w.WriteAttributeString("Make", "Hyundai");
w.WriteStartElement("Price");
w.WriteString("700000");
w.WriteEndElement();
w.WriteEndElement();
// Close the root element.
90
w.WriteEndElement();
w.WriteEndDocument();
w.Close();
}
}
2) Develop a web page that retrieves author details from the table ‘Authors’ and
displays it in a GridView. The maximum records in each page can be 3. Change
background color to ‘green’ and text color to ‘red’ with bold font for the header.
Use data source control to fetch data. Give provisions to edit the values of
FirstName and CopiesSold. The GridView should look as follows:
Id Name Book Title Genre CopiesSold
LastName: Pinto
3) Create an xml file using XDocument class. The file should contain the following
elements. <Cars><Detail>
<Name>I20</Name><Make>Hyundai</Make><Price>700000</Price>
</Detail><Detail>
<Name>I20</Name><Make>Hyundai</Make> <Price>700000</Price>
</Detail> </Cars>
4) Create a Website with the following features:
91
a. Display all the drives in a DropDownList. When the user selects the Drive
its contents (files and folders) should be displayed in the ListBox.
b. When the user clicks delete button, any item selected in the ListBox should
be removed.
Qty: 2
2) Create a web application as shown in figure 10.10, which accepts multiline user
input and saves it to a text file under "App_Data" folder.
Figure 10.10
92
LAB NO.: 11 Date:
MVC & AJAX
Objectives:
Develop rich web applications that communicate with the server using
asynchronous postback.
I. DESCRIPTION
93
database, operate on it, and then write updated information back to a Products table
in a SQL Server database.
The following code gives us a basic idea of working with the MVC architecture by
demonstrating how to create the model, view and controller modules for the music store
application by implementing the two features listed below:
Visitors can browse Albums by Genre.
Visitors can view a single album.
Steps to follow:
95
Select MVC 5 Controller Empty Add Name it as HomeController
This will create a new file, HomeController.cs, with the following code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcMusicStore.Controllers
{
public class HomeController : Controller
{
// // GET: /Home/
public ActionResult Index()
{
return View();
}
}
}
As an example the Index method can be replaced with a simple method that just
returns a string. For this two changes have to be made:
Change the method to return a string instead of an ActionResult
Change the return statement to return “Hello from Home”
The method should now look like this:
public string Index( )
{
return "Hello from Home";
}
96
Adding a StoreController:
Another controller to implement the browsing functionality of the music store has
to be added. The store controller will support three scenarios:
A listing page of the music genres in our music store
A browse page that lists all of the music albums in a particular genre
A details page that shows information about a specific music album
Now add a new StoreController. Just like HomeController is added, right-click on
the “Controllers” folder within the Solution Explorer and choose the AddController
menu item
Start the StoreController implementation by changing the Index( ) method to return
the string “Hello from Store.Index( )” and add similar methods for Browse( ) and Details(
) as shown below:
97
{
return "Hello from Store.Details( )";
}
}
Accessing these URLs will invoke the action methods within the Controller and return
string responses:
Change the Browse action method to retrieve a QueryString value from the URL.
Add a “genre” parameter to the action method. ASP.NET MVC will automatically pass
any QueryString or form post parameters named “genre” to the action method when it is
invoked.
// // GET: /Store/Browse?genre=Disco
public string Browse(string genre)
{
string message = HttpUtility.HtmlEncode("Store.Browse, Genre = " + genre);
return message;
}
98
Now browse to /Store/Browse?Genre=Disco. The following output is obtained.
Next change the Details action to read and display an input parameter named ID.
Unlike previous method, the ID value is not embedded as a QueryString parameter.
Instead it is embedded directly within the URL itself. For example: /Store/Details/5.
// // GET: /Store/Details/5
public string Details(int id)
{
string message = "Store.Details, ID = " + id;
return message;
}
Now browse to /Store/Details/5. The following output is obtained.
Now add an appropriate View template to the project. To do this position the
text cursor within the Index action method, then right-click and select “Add View”. This
will bring up the Add View dialog:
When the Add button is clicked, Visual Web Developer will create a new
Index.cshtml view template in the \Views\Home directory, creating the folder if doesn’t
already exist.
The name and folder location of the “Index.cshtml” file is important and follows
the default ASP.NET MVC naming conventions. The directory name, \Views\Home,
matches the controller - which is named HomeController. The view template name,
Index, matches the controller action method which will be displaying the view.
Visual Web Developer creates and opens the “Index.cshtml” view template after
the “Add” button is clicked within the “Add View” dialog. The contents of Index.cshtml
are shown below.
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
This view is using the Razor syntax, which is more concise than the Web Forms
view engine used in ASP.NET Web Forms. The first three lines set the page title using
ViewBag.Title. Update the <h2> tag to say “This is the Home Page” as shown below.
@{
ViewBag.Title = "Index";
100
}
<h2>This is the Home Page</h2>
Running the application shows that the new text is visible on the home page.
Most websites have content which is shared between many pages: navigation,
footers, logo images, stylesheet references, etc. The Razor view engine makes this easy
to manage using a page called _Layout.cshtml which has automatically been created
inside the /Views/Shared folder.
101
Double-click on this file to view the contents, which are shown below.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>@ViewBag.Title</title>
<link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css"
/>
<script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")"
type="text/javascript">
</script>
<script src="@Url.Content("~/Scripts/modernizr-1.7.min.js")"
type="text/javascript">
</script>
</head>
<body>
102
@RenderBody( )
</body>
</html>
The content from the individual views will be displayed by the @RenderBody( )
command, and any common content that needs to appear outside of that can be added to
the _Layout.cshtml markup. To have a common header for the MVC Music Store with
links to the Home page and Store area on all pages in the site, add that to the template
directly above the @RenderBody( ) statement.
<body>
<div id="header">
<h1>ASP.NET MVC MUSIC STORE</h1>
<ul id="navlist">
<li class="first">
<a href="/" id="current">Home</a>
</li>
<li>
<a href="/Store/">Store </a>
</li>
</ul>
</div>
@RenderBody( )
</body>
103
Using a Model to pass information to the View:
A View template that just displays hardcoded HTML is not going to make a very
interesting web site. To create a dynamic website, pass the information from the
controller actions to the view templates. In the Model-View-Controller pattern, the term
Model refers to objects which represent the data in the application. Often, model objects
correspond to tables in the database.
Controller action methods which return an ActionResult can pass a model object
to the view. This allows a Controller to cleanly package up all the information needed to
generate a response, and then pass this information off to a View template to generate the
appropriate HTML response.
Create some Model classes to represent Genres and Albums within the store.
Right-click the “Models” folder within the project, choose the “Add Class” option, and
name the file “Genre.cs.”
104
Then add a public string Name property to the class that was created:
Next, follow the same steps to create an Album class (named Album.cs) that has a Title
and a Genre property:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
105
using Mvc.Models;
Update the Details controller action so that it returns an ActionResult rather than
a string, as done in the HomeController’s Index method.
Now Right-click within the Details method and select “Add View…” from the
context menu. This template view will by default be generated in a
\Views\Store\Index.cshtml file.
@{
ViewBag.Title = "Details";
}
<h2>Details</h2>
106
Update the <h2> tag so it displays the Album’s Title property by modifying that
line to appear as follows.
<h2>Album: @Model.Title</h2>
Now re-run the project and visit the /Store/Details/5 URL. The following output is
obtained.
Make a similar update for the Store Browse action method. Update the method so
that it returns an ActionResult, and modify the method logic so that it creates a new Genre
object and returns it to the View.
@model Mvc.Models.Genre
@{
ViewBag.Title = "Browse";
Re-run the project and browse to the /Store/Browse?Genre=Disco URL. The output is
as follows:
108
Update the Store Index action method and view to display a list of all the Genres
in the store. Use a List of Genres as the model object, rather than just a single Genre. (In
StoreController class)
public ActionResult Index( )
{
var genres = new List<Genre> { new Genre { Name = "Disco" },
new Genre { Name = "Jazz" }, new Genre { Name = "Rock" } };
return View(genres);
}
Right-click in the Store Index action method and select Add View as before, select
Genre as the Model class, and press the Add button.
109
Change the @model declaration to indicate that the view will be expecting several
Genre objects rather than just one. Change the first line of /Store/Index.cshtml to read as
follows:
@model IEnumerable<MvcMusicStore.Models.Genre>
Next, loop through the Genre objects in the model as shown in the completed
view code below.
@model IEnumerable<Mvc.Models.Genre>
@{
ViewBag.Title = "Store";
}
<h3> Browse Genres </h3>
<p>Select from @Model.Count( ) genres:</p>
<ul>
@foreach (var genre in Model)
{
<li>@genre.Name</li>
}
</ul>
Run the application and browse to /Store, both the count and list of Genres is
displayed as follows:
110
Adding Links between pages:
ASP.NET MVC includes HTML Helper methods which are available from the
View template code to perform a variety of common tasks. The Html.ActionLink( ) helper
method is a particularly useful one, and makes it easy to build HTML <a> links and takes
care of annoying details like making sure URL paths are properly URL encoded.
The link text and the Action method to go to, when the hyperlink is clicked on the
client has to be supplied. For example, it is possible to link to “/Store/” Index( ) method
on the Store Details page with the link text “Go to the Store Index” using the following
call:
111
The links to the Browse page will require to pass a parameter, though, so use
another overload of the Html.The actionlink method that takes three parameters:
Link text, which will display the Genre name
Controller action name (Browse)
Route parameter values, specifying both the name (Genre) and the value (Genre
name)
Putting that all together, the links to the Store Index view is written as follows:
<ul>
@foreach (var genre in Model)
{
<li>@Html.ActionLink(genre.Name, "Browse",
new { genre = genre.Name })</li>
}
</ul>
Run the project again and access the /Store/ URL to see a list of genres. Each
genre is a hyperlink – when clicked it will navigate the user to the
/Store/Browse?genre=[genre] URL.
112
III. LAB EXERCISES:
1) Create a simple question-asking site like stack overflow, Quora, etc using
ASP.NET MVC framework that allows logged users to ask a new question and
answer existing questions. The logged users should also be allowed to upvote or
downvote a question. Upvoting and down voting should happen asynchronously
without reloading the entire web page.
2) Create an ASP.NET MVC application for “Manipal Travels”. The application can
be accessed by Administrator and Anonymous user.
The administrator should be able to add new place and buses between two
places.
Anonymous users should be able to search for available seats between two
places asynchronously without reloading the entire web page.
Anonymous users should be allowed to book available seats by providing
the name and phone number.
3) Create an e-auction site using ASP.NET MVC framework. The site should allow
users to view different items available for bidding along with its due date. Only
logged users can bid for an item. On the due date, a user with the highest bid will
get the item. The administrator should be able to create additional items and
view/update all existing items.
113
LAB NO.: 12 Date:
Instructions:
The report format will be circulated during the lab.
The mini project is expected to cover all the ASP.NET concepts learned in the course
of the lab.
A team comprising of two members must share the work equally, and both members
must be aware of work done by one another.
Deadlines must be strictly followed.
114
REFERENCES
1. Achyut Godbole, Atul Kahate, "Web Technologies", McGraw Hill 3rd edition,
2013.
2. Matthew MacDonald, "Beginning ASP.NET 4.5 in C#", Apress, 2012.
3. Jason N. Gaylord, Christian Wenz, Pranav Rastogi, Todd Miranda, Scott
Hanselman, “Professional ASP.NET 4.5 in C# and VB” , Wrox, 2013.
4. Stephen Walther, Nate Scott Dudek, "ASP.NET 4.5 Unleashed", Pearson
Education Inc., 2013.
5. Adam Freeman, Matthew MacDonald, Mario Szpuszta, "Pro ASP.NET 4.5 in C#",
Apress, 2013.
6. Elliotte Rusty Harold, W. Scott Means, "XML In a nutshell", O'Reilly 3rd edition,
2005.
7. https://www.w3schools.com/html/html5_intro.asp
8. https://www.w3schools.com/css/
9. https://msdn.microsoft.com/en-us/library/4w3ex9c2.aspx
10. https://msdn.microsoft.com/en-us/library/dd381412(v=vs.108).aspx
11. https://www.tutorialspoint.com/javascript/
115