Page 1
1
MODULE I
1
WINDOWS FORMS APPLICATION,
CLASSES AND OBJECTS, UI
Unit Structure
1.0 Objectives
1.1 Introduction
1.2 Overview
1.3 Windows Forms Application
1.4 Classes and Objects
1.5 UI Controls
1.6 Inheritance
1.7 Interfaces
1.8 Abstract Classes
1.9 Summary
1.10 Unit End Exercises
1.11 List of References
1.0 OBJECTIVES This chapter would make the learners to understand:
The basics of data types, decision making statements and keywords of
C# language.
The practical implementation of web form app lication.
The concepts of defining methods and objects.
The usage of various User Interface controls in web forms.
The Inheritance and interfacing concepts to be applied in C#
programs.
1.1 INTRODUCTION C# is Microsoft‟s premier language for .NET developme nt. It leverages
time-tested features with cutting -edge innovations and provides a highly
usable, efficient way to write programs for the modern enterprise
computing environment. It is, by any measure, one of the most important
languages of the twenty -first century.
Features of C#:
It is simple: The symbols like -> and :: in C++ are removed in this. munotes.in
Page 2
2 Windows Forms Application, Classes And Objects, Ui Object oriented: It is truly object oriented and supports Encapsulation,
Inheritance
and polymorphism concepts of OOPs.
The entire C# class model is built o n top of the Virtual Object System of
the
.NET Framework In C#, everything is an object. There are no more global
functions, variables and constants.
Type safe: Type -safety promotes robust programs. C# incorporates a
number of type -safe measures:
All dyna mically allocated objects and arrays are initialized to zero.
Use of any uninitialized variables produces an error message by the
compiler.
Access to arrays is range -checked and warned if it goes out -of-
bounds.
C# does not permit unsafe casts.
C# enforces overflow checking in arithmetic operations.
Reference parameters that are passed are type -safe.
C# supports automatic garbage collection.
It is versonable : Making new versions of software modules work with the
existing applications is known as versioning. C# provides support for
versioning with the help of new and override keywords.
It is compatible: C# enforces the NET common language specifications
and therefore allows inter -operation with other .NET languages.
It is Interoperable and Flexible: Although C # does not support pointers,
we may declare certain classes and methods as „unsafe‟ and then use
pointers to manipulate them. However, these codes will not be type -safe.
Name space: It is having namespaces; a namespace to define a declarative
region
Applic ations of C#:
It can be used for a variety of applications that are supported by the .NET
platform:
Console applications
Windows applications
Developing Windows controls munotes.in
Page 3
3 Advanced Web Technologies Developing ASP.NET projects:
Creating Web controls
Providing Web services
Developing NET component library
1.1.3 C# and .NET:
The .NET framework is responsible for executing the C# program in the
system. Framework is the combination of common language runtime and a
set of class libraries. The implementation of Common Language
Infrastructur e (CLI) is done through Common Language Runtime (CLR).
Microsoft .NET framework consists of the following main components:
Common Language Runtime
Base class library
User Program interfaces
It also supports Common Type System (CTS) which sstandardizes the data
types of all programming languages using .NET under the umbrella of
.NET to a common data type for easy and smooth communication among
these .NET languages
1.2 AN OVERVIEW ABOUT C# The elements of Visual Studio .NET applications are mentioned below:
1) The Start Page
2) Solution Explorer window
3) Output Window
4) Class View Window
5) Code Editor Window
6) Error List Window
7) Standard ToolBar
munotes.in
Page 4
4 Windows Forms Application, Classes And Objects, Ui 1.2.1 A Simple program :
1.2.2 C# Program Structure :
1. Reference of.NET framework namespaces: Every .NET application
takes the reference of the necessary .NET framework namespaces that
it is planning to use with the using (Keyword) , Ex., using System;
2. namespace: (Keyword) Declares the namespace for the cu rrent class
Ex. Structure
3. class: (Keyword) Declares a class: Ex. DemoPrg2
4. Method : Main() is a method of DemoPrg2 class which is the entry
point of the console application.
5. String: It is a data type. Fig 1.2 Simple C# Program munotes.in
Page 5
5 Advanced Web Technologies 6. variable : msgs is a variable that holds the value of the specified (here
it is string) data type.
7. value : “Structure of C# Program” is the value of the message variable
„msgs‟.
8. static method: The Console.WriteLine() is used to display a text on
the console.
9. Ouput screen shows the output of t he program.
10. Every line or statement in C# must end with a semicolon (;).
Compile and Run C# Program :
To see the output of the above C# program, we have to compile it and run
it by pressing Ctrl + F5 or clicking the Run button or by clicking the
"Debug " menu and clicking "Start Without Debugging".
Data Types :
Variable: It is used to store the data value in a storage location and takes
different values during the execution time based on the input to be given.
These variables are represented through the defined data types. C# has two
main categories of data types such as i) value types and ii) reference types.
The other types are coming under these categories as given in Table 1.1. S.No. Data Types Examples datatype = value;
1 Value Types Predefined Types (Simple Types) 1. Integers int a = 99; 2. Real Numbers float b=99.9f; 3. Booleans bool c = true; 4. Characters char d = 'E'; User-defined Types 1. Enumerations enum fruits{ apple, orange, grapes} 2. Structure struct Coordinate { public int x; public int y; } 2 Reference Types Predefined Types 1. Objects public class Car{ public model { get; set; } public int year { get; set; } public string color{ get; set; } } 2. Strings string msg=”Happy”; munotes.in
Page 6
6 Windows Forms Application, Classes And Objects, Ui User-defined Types 1. Classes public class MyClass { } 2. Arrays var num = new int[]{ 1,2,3,4,5}; 3. Delegates public delegate void MyDelegate(string msg); 4. Interfaces interface IFile { void ReadFile(); void WriteFile(string text); } 3 Pointers (type *var-name; ) int x = 4000; int* y = &x;
Key words :
C# language is defined by its keywords which determine the features built
into the language.
In general there are two types of keywords: reserved and contextual.
The reserved keywords shown in Table 1.2 cannot be used as names for
variables, classes, or methods. abstract as base bool break byte case catch char checked class const continue decimal default delegate do double else enum event explicit extern false finally fixed float for foreach goto if implicit in int interface internal is lock long namespace new null object operator out override params private protected public readonly ref return sbyte sealed short sizeof stackalloc static string struct switch this throw true try typeof uint ulong unchecked unsafe ushort using virtual volatile void while Table 1.2 Reserved Keywords add dynamic from get global group into join let orderby partial remove select set value var where yield Table 1.3 Contextual keywords
C# has some contextual keywords, shown in Table 1.3. They act as
keywords in a special meaning in certain contexts. But they are not
technically reserved. Apart from those contexts, they can be used as names
for other program elements, such as variable n ames. It is a best practice to
avoid using contextual keywords for other purposes. munotes.in
Page 7
7 Advanced Web Technologies Decision Making Statements :
if Statement : If (condition) statement; else statement; if (10 Single statement target s
else clause is optional if(condition)
{
statement sequence
}
else
{
statement
sequence
} if (10{
Console.WriteLine("You are Correct");
}
else
{
Console.WriteLine("Check the value of
i");
}
if-else-if Ladder : If (condition) statement; else if (condition) statement; else if (condition) statement; ... else statement; if (10The for Loop :
The general form of the for loop for repeating a single statement is for (initialization; condition; iteration) { statement sequence } for(int n = 10; i < 25; i++) { Console.WriteLine("Value of n is:”, n); }
The while Loop
Another of C#‟s loops is the while. The general form of the while loop is munotes.in
Page 8
8 Windows Forms Application, Classes And Objects, Ui while(condition) statement while (n<=10){ Console.WriteLine("Value of n is :", n); n=n+2; } do { statements; } while (condition); do{ sum= sum+n; Console.WriteLine); n=n+2; } while (n <= 20);
1.3 WEB FORMS APPLICATION Design UI based applications using basic Windows forms Controls :
munotes.in
Page 9
9 Advanced Web Technologies PROGRAM TO ADD TWO NUMBERS :
using System;
using System.Collections.Generic;
using System.Co mponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
Initializ eComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int a, b, c;
a = Convert.ToInt32(textBox1.Text);
b = Convert.ToInt32(textBox2.Text);
c = a + b;
textBox3.Text = c.ToString();
}
private void label2_Click(object sender, EventArgs e)
{
}
}
}
munotes.in
Page 10
10 Windows Forms Application, Classes And Objects, Ui Output:
1.4 CLASSES AND OBJECTS General structure of Class :
To define a class, declare the data that it contains and the code that
operates on it. Simple classes contain only code or only data, most real -
world classes contain both.
Data is contained in data members defined by the class, and code is
contained in function members.
C# defines different kind of data and function mem bers. For example, data
members (also called fields) include instance variables and static variables
and function members.
Function members include methods, constructors, destructors, indexers,
events, operators, and properties.
A class is created by use of the keyword class.
General fo rm of a simple class definition :
class classname
{ munotes.in
Page 11
11 Advanced Web Technologies // declare instance variables
access type var1;
access type var2;
// declare methods
access ret -type method1(parameters)
{
// body of method
}
}
Defining a class :
Buildi ngs have the information about houses, stores, offices, and so on.
This class is named as Building, and it will store three items of
information about a building: the number of floors, the total area, and the
number of occupants.
Demo program 2: Design App lications using Classes and Object
using System;
namespace MCAClassObjectsDemo
{
class Program
{
static void Main(string[] args)
{
//Creating object
Calculator calObject = new Calculator();
Consol e.Write("Enter number1 : ");
int n1 = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter number2 : ");
int n2 = Convert.ToInt32(Console.ReadLine());
//Accessing Calculator class member using Calculator class object
int result1 = calObject.CalculateSum(n1, n2);
int result2 = calObject.CalculateMinus(n1, n2);
int result3 = calObject.CalculateMul(n1, n2); munotes.in
Page 12
12 Windows Forms Application, Classes And Objects, Ui Console.WriteLine("The Sum of Two numbers is : " + result1);
Cons ole.WriteLine("The Subtraction of Two numbers is : " + result2);
Console.WriteLine("The Multiplication of Two numbers is : " + result3);
Console.ReadKey();
}
}
1.5 UI CONTROLS Design a Web Application for an Organization with Reg istration
forms and advanced controls :
munotes.in
Page 13
13 Advanced Web Technologies
Coding:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Registr ation
{
public partial class Form1 : Form
{
public Form1()
{ munotes.in
Page 14
14 Windows Forms Application, Classes And Objects, Ui InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
private void Registration_Load(object sender , EventArgs e)
{
cn = new SqlConnection(@"Data
Source=(LocalDB) \MSSQLLocalDB;AttachDbFilename=H: \Website \Reg
istrationAndLogin \Database.mdf;Integrated Security=True");
cn.Open();
}
private void button1_Click( object sender, EventArgs e)
{
if (txtconfirmpassword.Text != string.Empty || txtpassword.Text !=
string.Empty || txtusername.Text != string.Empty)
{
if (txtpassword.Text == txtconfirmpassword.Text)
{
cmd = new Sq lCommand("select * from LoginTable where username='" +
txtusername.Text + "'", cn);
dr = cmd.ExecuteReader();
if (dr.Read())
{
dr.Close();
MessageBox.Show("Userna me Already exist please try another ", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
dr.Close();
cmd = new SqlCommand("insert into LoginTable
values(@username,@password)", cn);
cmd.Parameters.AddWithValue("username", txtusername.Text);
cmd.Parameters.AddWithValue("password", txtpassword.Text); munotes.in
Page 15
15 Advanced Web Technologies cmd.ExecuteNonQuery();
MessageBox.Show("Your Account is created . Please login now.",
"Done", Mess ageBoxButtons.OK, MessageBoxIcon.Information);
}
}
else
{
MessageBox.Show("Please enter both password same ", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else
{
MessageBox.Show("Please enter value in all field.", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
}
1.6 INHERITANCE 1.6.1 Inheritance Concept s and working principles :
C# supports inheritance by allowing one class to incorporate another class
into its declaration. This is done by specifying a base class when a derived
class is declared. munotes.in
Page 16
16 Windows Forms Application, Classes And Objects, Ui The following class called TwoDShape stores the width and height of a
twodimensional object, such as a square, rectangle, triangle, and so on.
TwoDShape can be used as a base class (that is, as a starting point) for
classes that describe specific types of two -dimensional objects. For
example, the following progra m uses TwoDShape to derive a class called
Triangle. Pay close attention to the way that Triangle is declared.
Design Applications using Inheritance and Abstract Classes :
// A simple class hierarchy.
using System;
// A class for two -dimensional objects.
class TwoDShape
{
public double Width;
public double Height;
public void ShowDim()
{
Console.WriteLine("Width and height are " + Width + " and " + Height);
}
}
// Triangle is derived from TwoDShape.
class Triangle : TwoDShape
{
public string Style; // styl e of triangle
// Return area of triangle.
public double Area()
{
return Width * Height / 2;
}
// Display a triangle's style.
public void ShowStyle()
{
Console.WriteLine("Triangle is " + Style); munotes.in
Page 17
17 Advanced Web Technologies }
}
class Shapes
{
static void Main()
{
Triangle t1 = new Triangle();
Triangle t2 = new Triangle();
t1.Width = 4.0;
t1.Height = 4.0;
t1.Style = "isosceles";
t2.Width = 8.0;
t2.Height = 12.0;
t2.Style = "right";
Console.WriteLine("Info for t1: ");
t1.ShowStyle();
t1.ShowDim();
Console.WriteLine("Area is " + t1.Are a());
Console.WriteLine();
Console.WriteLine("Info for t2: ");
t2.ShowStyle();
t2.ShowDim();
Console.WriteLine("Area is " + t2.Area());
}
}
The output from this program is shown here:
Info for t1:
Triangle is isosceles
Width and height are 4 and 4 munotes.in
Page 18
18 Windows Forms Application, Classes And Objects, Ui Area is 8
Info for t2:
Triangle is right
Width and height are 8 and 12
Area is 48
1.7 INTERFACES In object -oriented programming it is sometimes helpful to define what a
class must do, but not how it will do it. You have already seen an example
of this: the abstra ct method. An abstract method declares the return type
and signature for a method, but provides no implementation. A derived
class must provide its own implementation of each abstract method
defined by its base class. Thus, an abstract method specifies the interface
to the method, but not the implementation. Although abstract classes and
methods are useful, it is possible to take this concept a step further. In C#,
you can fully separate a class‟ interface from its implementation by using
the keyword interf ace. Interfaces are syntactically similar to abstract
classes. However, in an interface, no method can include a body. That is,
an interface provides no implementation whatsoever. It specifies what
must be done, but not how. Once an interface is defined, a ny number of
classes can implement it. Also, one class can implement any number of
interfaces.
To implement an interface, a class must provide bodies for the methods
described by the interface. Each class is free to determine the details of its
own impleme ntation. Thus, two classes might implement the same
interface in different ways, but each class still supports the same set of
methods. Therefore, code that has knowledge of the interface can use
objects of either class since the interface to those object s is the same. By
providing the interface, C# allows you to fully utilize the “one interface,
multiple methods” aspect of polymorphism. An interface offers an
alternative to an abstract class for creating contracts among classes and
their clients. These co ntracts are made manifest using the interface
keyword, which declares a reference type that encapsulates the contract.
An interface is like a class that has only abstract methods.
Interfaces are declared by using the interface keyword. Here is a
simplified form of an interface declaration:
interface interface -name
{
return -type method -name(list of parameters);
}
munotes.in
Page 19
19 Advanced Web Technologies The interface -name of the interface is specified by name. Methods are
declared using only their return type and signature. They are, essentially,
abstract methods.
// Interface
interface IAnimal
{
void animalSound(); // interface method (does not have a body)
}
// Cat "implements" the IAnimal interface
class Cat : IAnimal
{
public void animalSound()
{
// The body of animalSound() is pr ovided here
Console.WriteLine("The cat says: Miaw Miaw");
}
}
class Program
{
static void Main(string[] args)
{
Cat myCat = new Cat(); // Create a Cat object
myCat.animalSound();
}
}
munotes.in
Page 20
20 Windows Forms Application, Classes And Objects, Ui 1.8 ABSTRACT CLASSES In the hierarchical inh eritance applications, an application can have a
single base class and number of different derived classes. The base class
acts as base for all the other but only the required information is visible to
the derived class. The information to be hidden from t he users of the
derived classes can be implemented using Abstract classes. These classes
contain abstract methods that are inherited by other classes that provide
more functionality. The f eatures of Abstract Classes are :
The keyword abstract is used to cre ate abstract class .
Some of the methods of the abstract class can also contain the
keyword abstract.
No object can be created of the abstract class i.e.it cannot be
instantiated.
The abstract methods in the abstract class are implemented actually
only in t he derived classes.
Design Applications using Inheritance and Abstract Classes :
using System;
namespace AbstractionDemo
{
abstract class Shape
{
public abstract double area();
}
class Circle: Shape
{
private double radius;
public Circle( double r)
{
radius = r;
}
public override double area ()
{
return (3.14*radius*radius);
}
} munotes.in
Page 21
21 Advanced Web Technologies class Square: Shape
{
private double side;
public Square( double s)
{
side = s;
}
public override double area ()
{
return (side*side);
}
}
class Triangle: Shape
{
private double tbase;
private double theight;
public Triangle( double b, double h)
{
tbase = b;
theight = h;
}
public override double area ()
{
return (0.5*tbase*theight);
}
}
class Test
{
static void Main(string[] args)
{
Circle c = new Circle(5.0);
Console.WriteLine("Area of Circle = {0}", c.area());
Square s = new Square(2.5);
Console.WriteLine("Area of Square = {0}", s.area()); munotes.in
Page 22
22 Windows Forms Application, Classes And Objects, Ui Triangle t = new Triangle(2.0, 5.0);
Console.WriteLine("Area of Triangle = {0}", t.area());
}
}
}
The output of the above p rogram is as follows:
Area of Circle = 78.5
Area of Square = 6.25
Area of Triangle = 5
The abstract class is shape and it contains the abstract method area().
The class Circle is inherited from Shape. It has a private data member
radius. The parameterized constructor assigns a value to radius. The
function area() calculates the area of the circle and returns that value
The class Square inherits from Shape. It has a private data member
side. The parameterized constructor assigns a value to side. The
function area() calculates the area of the square and returns that value.
The class Square inherits from Shape. It has a private data member
side. The parameterized constructor assigns a value to side. The
function area() calculates the area of the square and retu rns that value.
The class Triangle inherits from Shape. It has private data members
tbase and theight. The parameterized constructor assigns a value to
tbase and theight. The function area() calculates the area of the
triangle and returns that value.
The f unction main() contains the objects c, s and t for classes Circle,
Square and Triangle respectively. Then the areas of the circle, square
and triangle are printed using the function area().
1.9 SUMMARY This chapter describes about the C# language which is one of the language
in the .NET framework family. This language supports CLS and CTS. It is
very simple object oriented language which supports interoperability.
C# consists of reserved keywords to use while writing the codes. To do
the decision making if, if.. else, if.. else…if ladder , for loop, while loop,
do—while loop are used with following the defined syntax.
Classes can be complex representations and abstractions of things in the
real world.The structure is of class contains data and function me mbers
The individual instances of class are known as objects. A class has both
properties and behaviors. munotes.in
Page 23
23 Advanced Web Technologies The different types of UI controls like textbox, buttons are useful to create
the GUI based environment.
Inheritance concept is used in C# to derive th e properties of the base class
to the another class called derived class.
An interface is a contract that guarantees to a client how a class or struct
will behave. When a class implements an interface, it supports the
methods, properties, events, and index ers of the named interface.
An abstract method has no implementation. It creates a method name and
signature that must be implemented in all derived classes.
1.10 UNIT END EXERCISES 1. State the features and applications of C#.
2. Write a program in C sharp to find odd and even numbers
3. Design a web form for arithmetic operations
4. Write an application to design employee details web form.
1.11 LIST OF REFERENCES 1. Spaanjaars, Imar. Beginning ASP. NET 4.5. 1: in C# and VB. John
Wiley & Sons, 2014 . ISBN: 1861009038
2. Schildt, Herbert. C# 4.0: the complete reference. Tata McGraw -Hill
Education, 2010
3. Balagurusamy E, Programming in C#, Tata McGraw -Hill Education
4. https://www.wideskills.com/csharp/overview -csharp
5. https://www.onlinegdb.com/onli ne_csharp_compiler
*****
munotes.in
Page 24
24
MODULE II
2
INTRODUCTION TO ASP.NET
Unit Structure
2.0 Objectives
2.1 Introduction
2.2 Summary
2.3 Unit End Exercises
2.4 List of References
2.0 OBJECTIVES .NET Framework is a technology that supports building and running
Windows apps and web servic es. .NET Framework is designed to fulfill
the following objectives:
Provide a consistent, object -oriented programming environment
whether object code is stored and executed locally, executed locally
but web -distributed, or executed remotely.
Provide a code -execution environment that:
o Minimizes software deployment and versioning conflicts.
o Promotes safe execution of code, including code created by an
unknown or semi -trusted third party.
o Eliminates the performance problems of scripted or interpreted
environme nts.
Make the developer experience consistent across widely varying types
of apps, such as Windows -based apps and Web -based apps.
Build all communication on industry standards to ensure that code
based on .NET Framework integrates with any other code.
2.1 INTRODUCTION .NET Framework consists of the common language runtime (CLR) and
the .NET Framework class library. The common language runtime is the
foundation of .NET Framework. Think of the runtime as an agent that
manages code at execution time, providing core services such as memory
management, thread management, and remoting, while also enforcing
strict type safety and other forms of code accuracy that promote security
and robustness. In fact, the concept of code management is a fundamental
principle of the runtime. Code that targets the runtime is known as
managed code, while code that doesn't target the runtime is known as
unmanaged code. The class library is a comprehensive, object -oriented munotes.in
Page 25
25 Advanced Web Technologies collection of reusable types that you use to develop apps rang ing from
traditional command -line or graphical user interface (GUI) apps to apps
based on the latest innovations provided by ASP.NET, such as Web Forms
and XML web services.
.NET Framework can be hosted by unmanaged components that load the
common language runtime into their processes and initiate the execution
of managed code, thereby creating a software environment that exploits
both managed and unmanaged features. .NET Framework not only
provides several runtime hosts but also supports the development of third -
party runtime hosts.
Creating a Web a pplication project and a Page :
In this part of the walkthrough, you will create a Web application project
and add a new page to it. You will also add HTML text and run the page
in your browser.
To create a Web ap plication project :
1. Open Microsoft Visual Studio.
2. On the File menu, select New Project .
The New Project dialog box appears.
3. Select the Templates -> Visual C# -> Web templates group on the
left.
4. Choose the ASP.NET Web Application template in th e center
column.
5. Name your project BasicWebApp and click the OK button.
munotes.in
Page 26
26 Introduction to Asp.Net 6. Next, select the Web Forms template and click the OK button to
create the project.
Visual Studio creates a new project that includes prebuilt functionality
based on the Web F orms template. It not only provides you with a
Home.aspx page, an About.aspx page, a Contact.aspx page, but also
includes membership functionality that registers users and saves their
credentials so that they can log in to your website. When a new page is
created, by default Visual Studio displays the page in Source view, where
you can see the page's HTML elements. The following illustration shows
what you would see in Source view if you created a new Web page named
BasicWebApp.aspx.
A Tour of the Visual Studio Web Development Environment :
Before you proceed by modifying the page, it is useful to familiarize
yourself with the Visual Studio development environment. The following
illustration shows you the windows and tools that are available in Visual
Studi o and Visual Studio Express for Web. munotes.in
Page 27
27 Advanced Web Technologies The Visual Studio environment :
Familiarize yourself with the Web designer :
Examine the above illustration and match the text to the following list,
which describes the most commonly used windows and tools. (Not all
windows and tools that you see are listed here, only those marked in the
preceding illustration.)
Toolbars. Provide commands for formatting text, finding text, and so
on. Some toolbars are available only when you are working in Design
view.
Solution Explorer window. Displays the files and folders in your
Web application.
Document window. Displays the documents you are working on in
tabbed windows. You can switch between documents by clicking
tabs.
Properties window. Allows you to change settings for the page,
HTML elements, controls, and other objects.
View tabs. Present you with different views of the same document.
Design view is a near -WYSIWYG editing surface. Source view is the
HTML editor for the page. Split view displays both the Design view
and the Sour ce view for the document. You will work with the
Design and Source views later in this walkthrough. If you prefer to
open Web pages in Design view, on the Tools menu, click Options ,
select the HTML Designer node, and change the Start Pages In
option.
ToolB ox. Provides controls and HTML elements that you can drag
onto your page. Toolbox elements are grouped by common function.
Server Explorer . Displays database connections. If Server Explorer
is not visible, on the View menu, click Server Explorer. munotes.in
Page 28
28 Introduction to Asp.Net 2.2 SUMMA RY Creating a new ASP.NET Web Forms Page :
When you create a new Web Forms application using the ASP.NET Web
Application project template, Visual Studio adds an ASP.NET page (Web
Forms page) named Default.aspx, as well as several other files and folders.
You can use the Default.aspx page as the home page for your Web
application. However, for this walkthrough, you will create and work with
a new page.
To add a page to the Web application :
1. Close the Default.aspx page. To do this, click the tab that display s the
file name and then click the close option.
2. In Solution Explorer , right -click the Web application name (in this
tutorial the application name is BasicWebSite ), and then click Add ->
New Item .
The Add New Item dialog box is displayed.
3. Select the Visual C# -> Web templates group on the left. Then, select
Web Form from the middle list and name it FirstWebPage.aspx.
4. Click Add to add the web page to your project.
Visual Studio creates the new page and opens it.
Adding HTML to the Page :
In this pa rt of the walkthrough, you will add some static text to the page.
To add text to the page :
1. At the bottom of the document window, click the Design tab to switch
to Design view.
Design view displays the current page in a WYSIWYG -like way. At
this point, y ou do not have any text or controls on the page, so the munotes.in
Page 29
29 Advanced Web Technologies page is blank except for a dashed line that outlines a rectangle. This
rectangle represents a div element on the page.
2. Click inside the rectangle that is outlined by a dashed line.
3. Type Welcome to Visual Web Developer and press ENTER twice.
The following illustration shows the text you typed in Design view.
4. Switch to Source view.
You can see the HTML in Source view that you created when you
typed in Design view.
Running the Page :
Before yo u proceed by adding controls to the page, you can first run it.
munotes.in
Page 30
30 Introduction to Asp.Net To run the page :
1. In Solution Explorer , right -click FirstWebPage.aspx and select Set
as Start Page .
2. Press CTRL+F5 to run the page.
The page is displayed in the browser. Although the page you created
has a file -name extension of .aspx, it currently runs like any HTML
page.
To display a page in the browser you can also right -click the page in
Solution Explorer and select View in Browser .
3. Close the browser to stop the Web application.
Adding and Programming Controls :
You will now add server controls to the page. Server controls, such as
buttons, labels, text boxes, and other familiar controls, provide typical
form -processing capabilities for your Web Forms pages. However, you
can program t he controls with code that runs on the server, rather than the
client.
You will add a Button control, a TextBox control, and a Label control to
the page and write code to handle the Click event for the Button control.
To add controls to the page :
1. Click the Design tab to switch to Design view.
2. Put the insertion point at the end of the Welcome to Visual Web
Developer text and press ENTER five or more times to make some
room in the div element box.
3. In the Toolbox , expand the Standard group if it is no t already
expanded.
Note that you may need to expand the Toolbox window on the left to
view it.
4. Drag a TextBox control onto the page and drop it in the middle of the
div element box that has Welcome to Visual Web Developer in the
first line.
5. Drag a B utton control onto the page and drop it to the right of the
TextBox control.
6. Drag a Label control onto the page and drop it on a separate line
below the Button control.
7. Put the insertion point above the TextBox control, and then type
Enter your name: munotes.in
Page 31
31 Advanced Web Technologies This static HTML text is the caption for the TextBox control. You can
mix static HTML and server controls on the same page. The following
illustration shows how the three controls appear in Design view.
Setting Control Properties :
Visual Studio offers y ou various ways to set the properties of controls on
the page. In this part of the walkthrough, you will set properties in both
Design view and Source view.
To set control properties :
1. First, display the Properties windows by selecting from the View
menu -> Other Windows -> Properties Window . You could
alternatively select F4 to display the Properties window.
2. Select the Button control, and then in the Properties window, set the
value of Text to Display Name . The text you entered appears on the
button i n the designer, as shown in the following illustration.
3. Switch to Source view.
Source view displays the HTML for the page, including the elements
that Visual Studio has created for the server controls. Controls are
declared using HTML -like syntax, exc ept that the tags use the prefix
asp: and include the attribute runat="server" .
Control properties are declared as attributes. For example, when you
set the Text property for the Button control, in step 1, you were
actually setting the Text attribute in th e control's markup.
Note: All the controls are inside a form element, which also has the
attribute runat="server" . The runat="server" attribute and the asp:
prefix for control tags mark the controls so that they are processed by munotes.in
Page 32
32 Introduction to Asp.Net ASP.NET on the server whe n the page runs. Code outside of
Page 55
56 Basic Server-Side Control
<%# Container.DataItem %>< br>
A Visual Basic .NET sample pa ge appears as follows:
ASP.NET (VB) Copy
<%@ Page Language ="vb" %>
<%# Container.DataItem %>< br>
The output appears as follows:
one
two
three
4.3 UNIT END EXERCISE Write a program containing the following controls:
• A ListBox
• A Button
• An Image
• A Label munotes.in
Page 56
57 Advanced Web Technologies The listbox is used to list items available in a store. When the user
clicks on an item in the listbox, its image is displayed in the image
control. When the user clicks the button, the cost of the selected item
is displayed in the control.
4.4 LIST OF REFERENCE 1] Practical ASP.NET Web API
2] ASP.NET Core in Action by Andrew Lock
3] Building RESTful Web Services with .NET Core by Gaurav Aroraa , Tadit
Dash
*****
munotes.in
Page 57
58
MODULE III
5
DATABASE PROGRAMMING IN ASP.NET
Unit Structure
5.0 Objectives
5.1 An Overview
5.2 Introduction to ADO.NET
5.3 Architecture of ADO.NET
5.3.1 Connected Architecture
5.3.2 Disconnected Architecture
5.4 Components of ADO.NET
5.4.1 Data Providers
5.4.2 Connection
5.4.2.1 Connection Pooling
5.4.3 Command
5.4.3.1 Working with Stored Procedures with command object
5.4.4 DataSet and Datatable
5.4.5 Data Readers
5.4.6 Data Adapters
5.5 LINQ with ASP.NET
5.5.1 LINQ Introduction
5.5.2 Mapping data model to an Object model
5.5.3 Introducing query syntax
5.5.4 Entity Framework
5.6 Let us Sum Up
5.7 Unit End Exercises
5.8 List of References
Self-Learning Topics: Charts and Data Pagers
5.0 OBJECTIVES What You Will Learn in This Chapter:
Learn the basic classes in ADO.NET and its architecture.
Learn the different ADO.NET Data Providers.
Learn about the Connection and Command components.
Learn about the Working with Stored Procedures.
Learn about the DataAdapter, DataReader and DataSet components. munotes.in
Page 58
59 Advanced Web Technologies Learn LINQ with ASP.NET.
Discuss about the query syntax in LINQ.
Learn the Entity Framework Architecture.
5.1 AN OVERVIEW ADO.NET is a set of classes that expose data acces s services to the
Microsoft .NET programmer. ADO.NET provides a rich set of
components for creating distributed, data -sharing applications.
ADO.NET is an integral part of the Microsoft .NET Framework,
providing access to relational, XML, and application da ta.
All ADO.NET classes are located at the System.Data namespace with
two files named System.Data.dll and System.Xml.dll. When
compiling code that uses the System.Data namespace, reference both
System.Data.dll and System.Xml.dll.
Basically speaking, ADO.N ET provides a set of classes to support
you to develop database applications and enable you to connect to a
data source to retrieve, manipulate and update data with your
database.
5.2 INTRODUCTION OF THE ADO.NET ADO.NET is a collection of managed librarie s used by .NET applications
for data source communication using a driver or provider:
Enterprise applications handle a large amount of data. This data is
primarily stored in relational databases, such as Oracle, SQL Server, and
Access and so on. These data bases use Structured Query Language (SQL)
for retrieval of data.
To access enterprise data from a .NET application, an interface was
needed. This interface acts as a bridge between an RDBMS system and a
.NET application. ADO.NET is such an interface that is created to connect
.NET applications to RDBMS systems.
In the .NET framework, Microsoft introduced a new version of Active X
Data Objects (ADO) called ADO.NET. Any .NET application, either
Windows based or web based, can interact with the database using a rich
set of classes of the ADO.NET library. Data can be accessed from any
database using connected or disconnected architecture.
ADO.NET provides mainly the following two types of architectures:
ConnectedArchitecture:
The ADO.NET Connected architecture considers mainly three types of
objects :
▪ Connection con munotes.in
Page 59
60 Database Programming In Asp.Net ▪ Command cmd
▪ DataReaderdr
DisconnectedArchitecture:
The ADO.NET Disconnected architecture considers primarily the
following types of objects:
▪ DataSet ds
▪ DataAdapter da
▪ Connection con
5.3 AR CHITECTURE OF ADO.NET Ado.net is a data access technology that allows interaction between
applications and databases.
Types of Architecture :
Connected Architecture
Disconnected Architecture
Ado.net is both connection -oriented as well as disconnection orie nted.
Depending upon the functionality of an application, we can make it
connection -oriented or disconnection oriented. We can even use both the
modes together in a single application.
5.3.1 Connected Architecture :
As the name suggests, connected architecture refers to the fact that the
connection is established for the full time between the database and
application. For e.g. we make a program in C# that is connected with
the database for the full time, so that will be connected architecture.
Conne cted architecture is forward only and read -only. This means the
connected mode will work only in one particular direction i.e. forward
and that too for read -only purpose. Application issues query then read
back results and process them.
For connected archi tecture, we mainly use the object of the
DataReader class.
DataReader is used to retrieve the data from the database and it also
ensures that the connection is maintained for the complete interval of
time.
In connected architecture, the application is dire ctly linked with the
Database.
munotes.in
Page 60
61 Advanced Web Technologies
Fig 5.1 Connected Architecture in ADO.NET
5.3.2 Disconnected Architecture :
Disconnected architecture refers to the mode of architecture in
Ado.net where the connectivity between the database and application
is not maintai ned for the full time. Connectivity within this mode is
established only to read the data from the database and finally to
update the data within the database.
This means during the processing of the application, we need data so
that data is fetched from t he database and kept in temporary tables.
After that whenever data is required, it is fetched from the temporary
tables. And finally, when the operations were completed, the
connection was established to update the data within the database
from the tempora ry tables.
In this mode, application issues query then retrieves and store results
for processing. For this purpose, we use objects of DataAdapter and
DataSet classes.
In disconnected architecture, a Dataset is used for retrieving data from
the database. T his way there is no need to establish a connection for
the full time because DataSet acts as temporary storage.
munotes.in
Page 61
62 Database Programming In Asp.Net
Fig 5.2 Disconnected Architecture in ADO.NET
Difference between Connected and Disconnected : Connected Disconnected It is Connection Oriented It is Dis-Connection Oriented Connected get high in speed and performance. Disconnected get low in speed and performance. Connected you need to use a read only forward only data reader Disconnected you cannot Data Reader can’t persist the data Data Set can persist the data It is Read only, we can’t update the data We can update data
5.4 COMPONENTS OF ADO.NET Components are designed for data manipulation and faster data access.
Connection, Command, DataReader, DataAdapter, DataSet, and
DataView are the components of ADO.NET that are used to perform
database operations. ADO.NET has two main components that are used
for accessing and manipulating data. They are as follows:
1. Data provider and
2. DataSet
munotes.in
Page 62
63 Advanced Web Technologies 5.4.1 Data Provider:
The Data Provider can also be called a data driver and it can be used as a
major component for your data -driven applications.The functionalities of
the Data Provider are to:
1. Connect to the Database
2. Prepare an SQL Command
3. Execute the Command
4. Retrieve the results and display them in the application
The Data Provider is physically composed of a binary library file and this
library is in the DLL file format. Sometimes this DLL file depends on
other DLL files, so in fact a Data Provider can be made up of several DLL
files. Based on the different kinds of databases, Data Provider can have
several versions and each version is matched to each kind of database.
There are following different types of data providers included in ADO.Net Data Provider Descr iption Data Provider for SQL Server (SQL Server.NET) It provides data access for Microsoft SQL Server. The System.Data.SqlClient namespace is used Data Provider for OLEDB (OLEDB.NET) It is used for data sources using OLE DB. The System.Data.OleDb namespace is used Data Provider for ODBC (ODBC.NET) It is used for data sources using ODBC. The System.Data.Odbc namespace is used Data Provider for Oracle (Oracle.NET) It is used Oracle data sources. The System.Data.OracleClient namespace is used
The different data providers are located at the different namespaces, and
these namespaces hold the various data classes that you must import into
your code in order to use those classes in your project.
Table contains the most popular namespaces used by the different data
providers and used by the DataSet.
DataProvider Properties and Methods : Objects Description Connection This component is used to set up a connection with a data source. Command A command is a SQL statement or a stored procedure used to retrieve, insert, delete or modify data in a data source. DataReader Data reader is used to retrieve data from a data source in a read-only and forward-only mode DataAdapter This is integral to the working of ADO.Net since data is transferred munotes.in
Page 63
64 Database Programming In Asp.Net Objects Description to and from a database through a data adapter. It retrieves data from a database into a dataset and updates the database. When changes are made to the dataset, the changes in the database are actually done by the data adapter.
Advantages of using Data Providers in ADO.NET :
1) It provides high performance of client -server access over RDBMS
2) It contains trigger providing powerful means for maintaining business
rules at database level
3) It provides referential integrity that supports primary/foreign key
definition
4) It provides data access through table or server side control
5) It is easy to convert the .NET framework to other database engines
6) It contains full server based transaction to elim inate database
corruption
7) It has database security functionality and encryption support
5.4.2 Connection :
Data Provider contains four sub -classes and the Connection component is
one of them. This class provides a connection between your applications
and the database you selected to connect to your project. To use this class
to setup a connection between your application and the desired database,
you need first to create an instance or an object based on this class.
The Connection object you want to use depends on the type of the data
source you selected. Data Provider provides four different Connection
classes and each one is matched to one different database.
These popular Connection classes used for the different data sources:
The Connection classes and databases Connection Class Associated Database OdbcConnection ODBC Data Source OleDbConnection OLE DB Database SqlConnection SQL Server Database OracleConnection Oracle Database
The connection string is a property of the Connection class and it
provides all necessary information to connect to your data source.
Regularly this connection string contains a quite few parameters to define
a connection, but only five of them are popularly utilized for most data -
driven applications:
munotes.in
Page 64
65 Advanced Web Technologies Provi der
Data Source
Database
User ID
Password
A typical data connection instance with a general connection string can be
expressed by the following codes:
Connection = New xxxConnection(“Provider = MyProvider ;” & _
“Data Source = MyServer ;” & _
“Database = MyDatabase ;” & _
“User ID = MyUserID ;” & _
“Password = MyPassWord ;”)
wherexxx should be replaced by the selected Data Provider in your real
application, such as OleDb, Sql or Oracle . You need to use the real
parameter values implemented in y our applications to replace those
nominal values such as MyServer, MyDatabase, MyUserID and
MyPassWord in your application.
Some typical Connection instances are listed below:
OLE DB Data Provider for Microsoft Access Database :
Connection = New
OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=C: \database \CSE_DEPT.mdb;" & _
"User ID=MyUserID;" & _
"Password=MyPassWord;")
SQL Server Data Provider for SQL Server Database :
Connection = New SqlConnection("Server=localhost ;" + _
"Data Source=Susan \SQLEXPRESS;" + _
"Database=CSE_DEPT;" + _
"Integrated Security=SSPI")
Oracle Data Provider for Oracle Database :
Connection = New OracleConnection("Data Source=XE;" + _
"User ID=system;" + _
"Password=reback")
Example for SQL Server Database :
using System;
using System.Data;
using System.Data.SqlClient; munotes.in
Page 65
66 Database Programming In Asp.Net public partial class _Defau lt : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
string conString = "Data Source=(local);Initial
Catalog=Employee;Integrated Security=True";
protected void Button1_Click(object sender, Ev entArgs e)
{
// Creating the object of SqlConnection class
SqlConnectionconObject = new SqlConnection(conString);
try
{
conObject.Open();
if (conObject.State == ConnectionState.Open)
Response.Write("Database Connection is Open");
}
catch(SqlExceptionsqlexception)
{
Response.Write("ERROR ::" + sqlexception.Message);
}
catch(Exception ex)
{
Response.Write("ERROR ::"+ex.Message);
}
finally
{
conObject.Close();
}
}
}
In connection string, we can write or Server or Address or Network
Address in place of Data Source attribute. To specify the database we can
use Database or the Initial Catalog attribute.
You can provide yes, no, true, SSPI and false value to Integrated Security
attribute of connectio n string. If Integrated Security = false then User ID,
and Password must be specified in the connection string and if true then
current Windows account credentials are used for authentication. SSPI is
equivalent to value True. Connection String Parameter Name Description Data Source Identify the server.Local Machine/Machine Domain Name/Ip Address Initial Catalog Database Name Integrated Security Set to SSIP to make Connection with user’s munotes.in
Page 66
67 Advanced Web Technologies Connection String Parameter Name Description Window Login UserId Name of user configured in SQL Server Password Password match Sql Server UserId
Some of the properties for the connection object are as shown below: Property Description CanRaiseEvents It gets a value indicating the component can raise an event ConnectionString It gets or sets string used to open the
connection ConnectionTimeout It gets the time to wait for establishing the
connection Database It gets the name of the current database after
the connection is opened DataSource It gets the name of the database server to
which the user can connect Site It gets or sets the ISite of the component ServerVersion It gets a string representing the version of the server State It gets a string that describes the state of the connection
Some of the methods for the DbConnection object are as shown below: Methods Description BeginDbTransaction It starts the database transaction ChangeDatabase It changes the current database for an open connection Close It closes the connection to the database CreateCommand It creates and returns the DbCommand object Dispose() It releases the resources used by the component GetHashCode It serves as a default hash function GetSchema() It returns the schema information for the data source munotes.in
Page 67
68 Database Programming In Asp.Net Open It opens the database connection with the settings specified by the ConnectionString object ToString It returns the string containing the name of the component
Open() and Close() are two important methods of Connection object.
Program:
using System;
using System.Data;
using System.Data.SqlClient;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string conString = "Data Source=(local);Initial
Catalog=Employee;Integra ted Security=True";
SqlConnectionconObject = new SqlConnection(conString);
conObject.Open();
Console.WriteLine("Connection String ::
"+conObject.ConnectionString);
Console.WriteLine(" DataBase :: "+conObject.Database);
Console.WriteLine("DataSource :: " + conObject.DataSource);
Console.WriteLine("ConnectionTimeout :: " +
conObject.ConnectionTimeout);
Console.WriteLine("Connection Sta te :: " + conObject.State);
Console.WriteLine("ServerVersion :: " +
conObject.ServerVersion);
Console.ReadLine();
}
}
}
Output:
Connection String :: Data Source=(local);Initial
Catalog=Employee;Integrat ed Security=True
DataBase :: Employee
DataSource :: (local)
ConnectionTimeout :: 15 munotes.in
Page 68
69 Advanced Web Technologies Connection State :: Open
ServerVersion :: 10.50.1600
Storing connection string in configuration file
If you did not write connection string in config file, then it may crea te
problem. Suppose that, after deploying the project, you have to change the
connection string, then you have to change the connection string in every
page.
It is a good practice to store the connection string for your application in a
config file rather than in every page.
In this scenario, if you have written the connection string in config file,
then the required change will be done in single place (config file) and the
change will be reflect automatically in every page.
Acceccing the connecting string from config file
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
protected void Button1_Click(object sender, EventArgs e)
{
string conn =
ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
// Creating the object of SqlConnection clas s
SqlConnection conObject = new SqlConnection(conn);
conObject.Open();
if (conObject.State == ConnectionState.Open)
Response.Write("Database Connection is Open");
}
By default, a connection string is enabled w ith connection pooling.
By default, the maximum number of pools is 100, minimum is 0.
Connection pooling is the ability of re -use your connection to the
Database. This means if you enable Connection pooling in the connection
object, actually you enable the re-use of the connection to more than one
user. munotes.in
Page 69
70 Database Programming In Asp.Net 5.4.2.1 Connection Pooling:
Fig. 5.3 Connection Pooling
Connection pooling enables you to re -use your connection to the
Database. It is an optimization technique that will increase the
performance of datab ase programming. By default connection pooling
feature is enabled with connection string. The maximum number of pools
is 100, and minimum is zero.
Connecting to database is time consuming and resource intensive task.
Whenever user wants to connect database , connection string is parsed and
it checks whether given credentials in connection stings are correct or not.
Therefore it takes lots of time to open and close the connection.
To reduce the cost of opening and closing the same connection repeatedly
and in creasing the performance ADO.NET uses connection pooling.
A Connection String in the Web.Config file with connection pooling
option:
SQL Server connection string pooling attributes :
Connection Lifetime:
o Length of time in seconds after creation after which a connection is
destroyed. The default is 0, indicating that connection will have the
maximum timeout.
munotes.in
Page 70
71 Advanced Web Technologies Connection Reset:
o Specifies whether the connection is reset when removed from the
pool. The default is true.
Enlist:
o Specifies whether the connection is automatically enlisted in the
current transaction context of the creation thread if that transaction
context exists. The default is true.
Load Balance Timeout:
o Length of time in seconds that a connection can remain idle in a
connection pool before being removed.
Max Pool Size:
o Maximum number of connections allowed in the pool. The default is
100.
Min Pool Size:
o Minimum number of connections maintained in the pool. The default
is 0.
Pooling:
o When true, the connection is drawn from the appropriate pool, or if
necessary, created and added to the appropriate pool. The default is
true.
5.4.3 Command :
The Command object works with the Connection object and used to
execute SQL queries or Stored Procedures against the data sourc e. You
can perform insert, update, delete, and select operations with this object. It
requires an instance of a Connection Object for executing the SQL
statements as example.
SqlCommandcmd = new SqlCommand("SQL query or stored
procedure", conn);
The SQL statements can be SELECT, INSERT, UPDATE, or DELETE. It
uses a connection object to perform these actions on the database.
SELECT
cmd =new SqlCommand("select * from Employee", con);
cmd =new OracleCommand("select * from Employee", con);
INSERT munotes.in
Page 71
72 Database Programming In Asp.Net cmd = new Sq lCommand("INSERT INTO
Employee(Emp_ID,Emp_Name)VALUES ('" + aa + "','" + bb +"')",con);
cmd = new OracleCommand("INSERT INTO Employee(Emp_ID ,
Emp_Name) VALUES('" + aa + "','" + bb + "' )",con);
UPDATE
cmd =new SqlCommand("UPDATE Employee SET Emp_ID ='" + aa + "'
, Emp_Name ='" + bb + "' WHERE Emp_ID ='" + aa + "'", con);
cmd =new OracleCommand("UPDATE Employee SET Emp_ID ='" + aa
+ "' , Emp_Name ='" + bb + "' WHERE Emp_ID ='" + aa + "'", con);
DELETE
cmd =new SqlCommand("DELETE FROM Employee where Emp_ID=' "
+ aa + "'", con);
cmd =new OracleCommand("DELETE FROM Employee where
Emp_ID='" + aa + "'", con);
Steps for executing SQL query with command object :
Create a Connection Object and initialize with connection string.
Create the command object and initialize with SQL query and
connection object.
Open the connection.
Execute query with the help of any one method of command object.
Store the result in DataReader object (In case of select SQL query)
Close the connection.
Some of the Command properties are as lis ted below: Property Description CommandTimeout Contains the length of the timeout of a query, in seconds CommandText It gets or sets the text command against the data source CommandType CommandType is an important property of Command class. This property is used to determine which type of command being executed. CommandType.StoredProcedure: It informs the Command object that the stored procedure munotes.in
Page 72
73 Advanced Web Technologies will be used in place of simple SQL statements. CommandType.Text: It informs the Command object that the CommandText value contains a SQL query. CommandType.TableDirect: It indicates that the CommandText property contains the name of a table Connection It gets or sets the DbConnection used by the DbCommand Parameters It gets the collection of DbParameter objects Site It gets or sets the ISite of the component Transaction It gets or sets the DbTransaction which the
DbCommand object executes UpdatedRowSource It gets or sets the command results applied to
the DataRow
Some of the methods for the Command objects are as shown below: Methods Description Cancel() It attempts to cancel the execution of the DbCommand CreateDbParameter It creates a new instance of DbParameter object Dispose() It releases all the resources used by the component ExecuteDbDataReader It executes the command text against the connection ExecuteNonQuery It executes SQL statement against the connection object If you are using Insert, Update or Delete SQL statement then use this method. Its return type is Integer (The number of affected records). munotes.in
Page 73
74 Database Programming In Asp.Net ExecuteReader() It executes the CommandText against the Connection object This method works on select SQL query. It returns the DataReader object. Use DataReader read () method to retrieve the rows. ExecuteScalar() Executes the CommandText property and
returns data in a DataReader object.
This method returns single value. Its return
type is Object. When you want single value
(First column of first row), then use
ExecuteScalar () method. Extra columns or
rows are ignored. ExecuteScalar method
gives better performance if SQL statements
have a ggregate function. GetService It returns an object representing a service
object for the instance ExecuteXMLReader ● It returns an instance of XmlReader class.
This method is used to return the result set in
the form of an XML document.
Let’s take one example that will use command object. The table structure
is as follows.
Program :
using System;
using System.Data;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
SqlDataReader reader;
SqlConnection con;
protected void Page_Load(object sender, EventArgs e)
{
con = new SqlConnection("Data Source=(local);Initial
Catalog=Employee;Integrated Security=True");
SqlCommandcmd = new SqlCommand();
cmd.Connection = con;
cmd.Command Text = "select * from tblemps";
cmd.CommandType = CommandType.Text;
try munotes.in
Page 74
75 Advanced Web Technologies {
con.Open();
reader = cmd.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataBind();
}
catch (Exception ex)
{
Label1.Text = "ERROR :: " + ex.Message;
}
finally
{
reader.Close();
con.Close();
}
}
}
5.4.3.1 Working With Stored Procedures With Command Object:
First we understand that what is stored procedure and then we will use the
stored procedure in our database program.
Stored Procedure :
A stored procedure in SQL Server is a group of one or more SQL
statements. Stored procedure are created and stored in the database.
When you execute the application, the SQL statements are parsed and
execution plan is created. This happened every time whenever you execute
the application.
It is not happened in case of stored procedure. Stored procedure compiles
only once and stores in database with its execution plan. If we use stored
procedure, then we can avoid recompilation of the query. It increases the
performance of application. Another advantage is that it can be tested
independent of the application. Stored procedures are easy to maintain. If
any changes occur, then just update the stored procedure. The change will
reflect in all pages automatically. It is a big advantage that rather than
change SQL queries in all the pages just we need to update a single stored
proced ure.
Creating Stored Procedure :
Open Microsoft SQL Server, select your database, right click and select
create new stored procedure tab.
Here we have created a simple stored procedure named
"GetAllEmployees ". It selects all the record from table tblEmps. munotes.in
Page 75
76 Database Programming In Asp.Net CREATE PROCEDURE [dbo].[GetAllEmployees]
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
SELECT * from tblEmps
END
Disp lay data using stored procedure :
Just change the previous code as follows and you will get the same result.
SqlConnection con = new SqlConnection("Data Source=(local);Initial
Catalog=Employee;Integrated Security=True");
SqlCommandcmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "GetAllEmployees";
Insert Record using stored procedure :
First create a simple input screen to insert the data into database as given
below.
Create a Stored Procedure with Input Parameter in the database.
CREATE PROCEDURE InsertEmployees
@EmpID integer,
@EmpNamevarchar(100),
@Gender varchar(50),
@Salary money,
@Address varchar(200),
@DepID integer
AS
BEGIN
-- Insert state ments for procedure here
insert into tblEmps values(@EmpID,@EmpName ,@Gender
,@Salary ,@Address ,@DepID )
END
GO
munotes.in
Page 76
77 Advanced Web Technologies
Write down your connection string in web.config file.
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
public partial class Default2 : System.Web.UI.Page
{
SqlConnectionconObject;
SqlCommandcmd;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnAdd_Click(object sender, EventArgs e)
{
string con
=ConfigurationManager.Connecti onStrings["conString"].ConnectionStrin
g;
conObject = new SqlConnection(con);
cmd = new SqlCommand();
cmd.Connection = conObject;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "InsertEmployees";
cmd.Parameters.Add("@EmpID",SqlDbType.Int).Value=txtEmpID.Text;
cmd.Parameters.Add("@EmpName",SqlDbType.VarChar).Value=txtNam
e.Text;
cmd.Parameters.Add("@Gender",
SqlDbType.VarChar).Value=txtGender.Text;
cmd.Parameters.Add("@Sa lary",
SqlDbType.Money).Value=txtSalary.Text;
cmd.Parameters.Add("@Address",
SqlDbType.VarChar).Value=txtAddress.Text; munotes.in
Page 77
78 Database Programming In Asp.Net cmd.Parameters.Add("@DepID",
SqlDbType.Int).Value=txtDepID.Text;
try
{
conObject.Open();
int i=cmd.ExecuteNonQuery();
if(i>0)
{
Label1.Text = "Record Added Successfully !!";
}
}
catch(Exception ex)
{
Label1.Text="ERROR ::"+ex.Message;
}
finally
{
conObject.Close();
}
}
}
5.4.4 Dataset :
The DataSet class is used for representing a subset of the database. It is
defined in the System.Data namespace. It is used for disconnected
representation of result s sets from the Data Source. It provides more
flexibility while dealing with the result sets.
DataSet object behaves like a small database. The DataSet contains rows,
columns, primary keys, constraints, and relation with Data Table objects.
It has a collec tion of DataTable objects and can be related to each other
with Data Relation objects.
It can contain more than one table and also create the relationship between
tables. Again DataTable is the collection of DataRow and DataColomn
objects.
One of the advan tages of dataset is that it can work with different types of
databases simultaneously. Suppose that one table is available within SQL
server and another table is available in Oracle. You can easily query each
database server and create a single DataSet wit h both the table.
munotes.in
Page 78
79 Advanced Web Technologies
The list of properties for DataSet are as shown below: Property Description Container It gets the container for the component CaseSensitive It gets or sets value indicating whether string comparisons with Data Table objects DataSetName It gets or sets the name of the current
DataSet DefaultViewManager It gets a custom view of the data contained
into the DataSet to allow filtering,
searching and navigating data using a
custom DataViewManager DesignMode It gets a value indicating the component is
currently in design mode Events It gets a list of event handlers that are attached to this component ExtendedProperties It gets a collection of customized user information associated with Data Set HasErrors It gets a value indicating the errors in any DataTable objects within the DataSet Tables It gets the collection of tables contained in the DataSet Relations It gets a collection of relation that links tables and allow navigation from parent tables to child tables IsInitialized It gets a value that indicates whether the DataSet is initialized
The list of methods of DataSet are as shown below: Methods Description AcceptChanges It commits all the changes made in the DataSet when it was loaded or when the last changes were accepted munotes.in
Page 79
80 Database Programming In Asp.Net BeginInit It begins the initialization of a DataSet used on a form or by other component Clear It clears the DataSet of any data by removing all rows in the table Clone It copies the structure of the DataSet including Data Table schemas, relations and constraints Copy It copies the structure and data from the DataSet CreateDataReader() It returns the DataTableReader with one
result set per Data Table Dispose() It release all the resources used by the
MarshalByValueComponent EndInit It ends the initialization od a DataSet that is
used on a form Finalize It allows the object to try to free resources
and perform cleanup operations before the
garbage collection GetChanges() It gets a copy of the DataSet containing all changes made in the last load GetDataSetSchema It gets a copy of XmlSchemaSet for the DataSet GetHashCode It serves as a default hash function HasChanges() It gets a value indicating whether DataSet has changes, including new, deleted or modified rows InferXmlSchema(String, String[]) It applies the XML Schema from the specified Stream into DataSer InferXmlSchema(TextReader, String[]) It applies the XML Schema from the specified XmlReader to the DataSet IsBinarySerialized It inspects the format of the serialized representation of the DataSet Load(IDataReader, LoadOption, String[]) It fills a DataSet with values from a data source using supplied IDataReader using array of strings MemberwiseClone It creates a shallow copy of the current Object munotes.in
Page 80
81 Advanced Web Technologies Merge(DataRow[]) It merges an array of DataRow objects into the current DataSet Merge(DataSet, Boolean) It merges a DataSet and its schema into current DataSet Merge(DataTable, Boolean, MissingSchemaAction) It merges a DataTable and its schema into current DataSet preserving or removing changes into the DataSet OnRemoveRelation It occurs when a DataRelation object is removed from the DataTable ReadXml(Stream) It reads XML Schema and data into DataSet using System.IO.Stream Reset It clears all tables and removes all relations, contraints, and tables from the DataSet ShouldSerializeRelations It gets a value indicating the Relations property should be persisted ToString It returns a string containing the name of the component WriteXml(Stream) It writes the current data for the DataSet using the System.IO.Stream WriteXml(TextWriter) It writes the current data for the DataSet using the TextWriter WriteXml(TextWriter, XmlWriteMode) It writes a current data and schema for the DataSet using the TextWriter and XmlWrite mode WriteXmlSchema(XmlWriter) It writes the DataSet structure as an XMl schema to the XmlWriter object
The DataSet can be used along with the Data Adapter in an application.
The syntax for the creation of DataSet and using in an application is as
shown below:
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(sql,connection);
da.Fill(ds) ;
Program :
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration; munotes.in
Page 81
82 Database Programming In Asp.Net public partial class Default : System.Web.UI.Page
{
SqlConnection conn;
SqlDataAdapter adapter;
DataSet ds;
protected void Page_Load (object sender, EventArgs e)
{
string cs =
ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
try
{
conn = new SqlConnection(cs);
adapter = new SqlDataAdapter("select * from tblEmps", c onn);
ds = new DataSet();
adapter.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
catch(Exception ex)
{
Label1.Text = "ERROR :: " + ex.Message;
}
finally
{
ds.Dispose();
conn.Dispose();
}
}
}
5.4.4.1 Datatableand Datarow :
The DataTable class is used when the tables of the database are to be
represented. The list of some DataTable properties is as shown below: Property Description CaseSensitive It indicates that the string comparisons are case – sensitive ChildRelations It gets the collection of child relations for this DataTable Columns It gets the collection of columns belonging to the table Constraints It gets the collection of constraints maintained by the table DataSet It gets the DataSet to the corresponding table munotes.in
Page 82
83 Advanced Web Technologies DisplayExpression It gets or sets the expression returning a value to represent the table Events It gets the event handlers list attached to the component Namespace It gets or sets the namespace for the XML representation of the data store PrimaryKey It gets or sets an array of columns functioning as primary key for the table Rows It gets the collection of rows belonging to the
table TableName It gets or sets the name of the DataTable
The list of some of methods of the DataTable are as shown below: Methods Description AcceptChanges It contains all the changes when the last
AcceptChanges was called Clear It clears the DataTable of all data Clone It clones the structure of the DataTable containing constraints and schemas Copy It copies the structure and data for the DataTable Dispose() It releases all the resources used by the MarshalByValueComponent EndLoadData It turns on notifications, constraints, indes maintenance after the data is loaded Finalize It allows an object to free resources and perform cleanup operations before garbage collection GetChanges() It gets a copy of DataTable where all the changes are made by the user ImportRow It copies the DataRow into DataTable Load(IDataReader) It fills a DataTable with values from a data source using IDataReader munotes.in
Page 83
84 Database Programming In Asp.Net Merge(DataTable) It merges the DataTable with the current DataTable NewRow It creates a new row with the schema similar to the DataTable Reset It resets the DataTable to the original state Select() It gets an array of all DataRow objects WriteXml(String) It writes the current contents of the DataTable as XML using the specified file
The syntax of creating DataTable in an application is as shown below: DataTabledt = newDataTable(); DataColumn dc = newDataColumn(); dc.ColumnName = “Srno”; dc.DataType = typeof(int); dt.Columns.Add(dc); DataColumn dc1 = newDataColumn(); dc.ColumnName = “Name”; dc.DataType = typeof(string); dt.Columns.Add(dc1); dt.Rows.Add(newobject [ ] { “1”, “John”});
Datarow :
The DataRow is used to represent rows in the DataTable. Some of the
properties of DataRow are as shown below: Property Description HasErrors It gets a value indicating that row has errors Item[DataColumn] It gets or sets the data stored in the specified DataColumn Item[String] It gets or sets the data stored in the column specified by the name ItemArray It gets or sets all the values for this row through an array RowError It gets or sets the custom error description for a row munotes.in
Page 84
85 Advanced Web Technologies Table It gets the DataTable for DataSet
The syntax for creating DataRow is as shown below:
DataRowdr =newdt.NewRow();
dr[“Name”]=”Mark”;
dr[“Course”]=”MBA”;
dt.Rows.Add(dr);
5.4.5 Datareader :
DataReader object works in connected mode. DataReader is used in
forward only, read only retrieval of data from data sources. They cann ot
be called directly in the code. It is fast compare to DataSet. DataReader
provides the easy way to access the data from database. It can increase the
performance of application because it reads records one by one. Use read()
method of DataReader to acce ss the record.
It is used in Connected architecture.
Provide better performance.
DataReader Object has Read -only access.
DataReader Object Supports a single table based on a single SQL
query of one database.
While DataReader Object is Bind to a single cont rol.
DataReader Object has Faster access to data.
DataReader Object Must be manually coded.
We can’t create relation in data reader.
Data reader communicates with the command object.
DataRea dercan not modify data
For initializing the DataReader object, cal l the ExecuteReader method of
the Command object. It returns an instance of the DataReader.
SqlCommandcmd = new SqlCommand("Your SQL query", conn);
SqlDataReaderreaderObj = cmd.ExecuteReader();
Once your task completed with the data reader, call the Close( ) method to
close the DataReader.
readerObj.Close(); munotes.in
Page 85
86 Database Programming In Asp.Net
DataReader Properties and Methods : Property Description Connection It gets the Connection associated with DataReader Depth Indicates the depth of nesting for row FieldCount Returns number of columns in a row HasRows It gets a value indicating the DataReader has one or
more rows IsClosed Indicates whether a data reader is closed RecordsAffected Number of row affected after a transaction Item Gets the value of a column in native format Methods Description Read() Reads next record in the data reader. NextResult() Advances the data reader to the next result during
batch transactions. Close() Closes a DataRaeder object.
You can also get the value of particular column of the table by using the
data reader object.
while(reader.Read())
{
string ID = reader["EmpID"].ToString();
string name = reader["Name"].ToString();
string gender = reader["Gender"].ToString();
string salary = reader["Salary"].ToString();
}
Difference b etween DataSet and DataReader : DataSet DataReader Works in connected mode. It provides connection oriented environment. Provides slow performance compare to DataReader. Provides the fast execution. In memory object. You can fetch the data in any order. It is a forward-only and read only object. Implicitly open the connection. It needs explicit open and close the connection. munotes.in
Page 86
87 Advanced Web Technologies It can contain more than one table. At a time, it works on single table. Dataset objects have XML Support. It does not fully support XML It uses fill() method of DataAdapter to populate the dataset. DataReader object provides the read() method for reading the records.
5.4.6 Dataadapter :
DataAdapter is used as a ADO.NET data provider. It is used in
disconnected architecture. It is used as communication between DataSet
and DataSource. i.e. It works as a bridge between DataSet and your
DataSource. It holds the SQL commands and connection object for
reading and writ ing data. DataSet does not open or close the connection
because this task is performed by DataAdapter object. It helps to manage
the data in disconnected mode.
DataAdapter performs the following tasks when using with DataSet
object:
1. Open connection
2. Fills the DataSet
3. Close connection
It can also perform Select, Insert, Update and Delete SQL operations with
the database.
The list of DataAdapter properties is as shown below: Property Description DeleteCommand It is used for deleting records from the data source InsertCommand It is used to insert records in a data source SelectCommand It is used to select records from a stored procedure UpdateCommand It is used to update records in the data source TableMappings It represents the collection of mappings between actual data source table
The list of methods for the DataAdapter is as shown below: munotes.in
Page 87
88 Database Programming In Asp.Net Methods Description Fill It is used to fill data into DataSet using DataAdapter Update It is used to update data to the data source FillSchema It adds a DataTable to the DataSet
5.5 LINQ WITH ASP.NET Language integrated query or LINQ enables you to write SQL like syntax
in programming language itself. LINQ contains different types of
operators, which is used in language itself. In LINQ, the sam e query can
be used in, an SQL database, a DataSet, an array of objects in memory and
so many other data types.
5.5.1 LINQ Introduction:
Architecture of LINQ :
In this chapter, we are going to study the Architecture of LINQ . The
term LINQ stands for Language Integrated Query and it is pronounced
as LINK . Nowadays the use of use LINQ increasing rapidly. So, as a
developer, you should understand the Linq and its architecture.
What is LINQ?
The LINQ (Language Integrated Query) is a part of a language bu t not a
complete language. It was introduced by Microsoft with .NET Framework
3.5 and C# 3.0 and is available in System.Linq namespace.
LINQ provides us common query syntax which allows us to query the data
from various data sources. That means using a sin gle query we can get or
set the data from various data sources such as SQL Server database, XML
documents, ADO.NET Datasets, and any other in -memory objects such as
Collections, Generics, etc. munotes.in
Page 88
89 Advanced Web Technologies
Fig. 5.4 LINQ Query on Different Data Sources
Why should we learn LINQ?
Let us understand why we should learn LINQ with an example.
Suppose we are developing a .NET Application and that application
requires data from different data sources. For example
1. The application needs data from SQL Server Database. So as a
developer in order to access the data from SQL Server Database, we
need to understand ADO.NET and SQL Server -specific syntaxes. If
the database is Oracle then we need to learn SQL Syntax specific to
Oracle Database.
2. The application also needs data from an XML Document. So as a
developer in order to work with XML Document, we need to
understand XPath and XSLT queries.
3. The application also needs to manipulate the data (objects) in memory
such as List, List , etc. So as a developer we
should also have to understand how to work with in -memory objects.
Fig. 5.5 Data from different data sources
munotes.in
Page 89
90 Database Programming In Asp.Net LINQ provides a uniform programming model (i.e. common query syntax)
which allows us to work with different data sources but using a standard
or you can say unified coding style. As a result, we don’t require learning
different syntaxes to query different data sources.
How LINQ works?
Fig. 5.6 Working of LINQ
As shown in the above diagram, you can write the LINQ queries using any
.NET supported p rogramming languages such as C#, VB.NET, J#, etc.
The LINQ provider is a software component that lies between the LINQ
queries and the actual data source. The Linq provider will convert the
LINQ queries into a format that can be understood by the underlying data
source. For example, LINQ to SQL provider will convert the LINQ
queries to SQL statements which can be understood by the SQL Server
database. Similarly, the LINQ to XML provider will convert the queries
into a format that can be understood by the XML document.
What are LINQ Providers?
A LINQ provider is software that implements the IQueryProvider and
IQueryable interface for a particular data source. In other words, it allows
us to write LINQ queries against that data source. If you want to create
your custom LINQ provider then it must implement IQueryProvider and
IQueryable interface. Without LINQ Provider we cannot execute our
LINQ Queries.
Let us discuss so me of the LINQ Providers and how they work internally.
LINQ to Objects:
The LINQ to Objects provider allows us to query an in -memory object
such as an array, collection, and generics types. It provides many built -in
functions that we can use to perform man y useful operations such as
filtering, ordering, and grouping with minimum code.
LINQ to SQL (DLINQ):
munotes.in
Page 90
91 Advanced Web Technologies The LINQ to SQL Provider is designed to work with only the SQL Server
database. You can consider this as an object -relational mapping (ORM)
framework whic h allows one to one mapping between the SQL Server
database and related .NET Classes. These .NET classes are going to be
created automatically by the wizard based on the database table.
LINQ to Datasets:
The LINQ to Datasets provider provides us the flexib ility to query data
cached in a Dataset in an easy and faster way. It also allows us to do
further data manipulation operations such as searching, filtering, sorting,
etc. on the Dataset using the LINQ Syntax.
LINQ to Entities:
The LINQ to Entities provide r looks like LINQ to SQL. It means it is also
an object -relational mapping (ORM) framework that allows one to one,
one to many, and many to many mapping between the database tables and
.NET Classes. The point that you need to remember is, it is used to que ry
any database such as SQL Server, Oracle, MySQL, DB2, etc. Now, it is
called ADO.NET Entity Framework.
LINQ to XML (XLINQ):
The LINQ to XML provider is basically designed to work with an XML
document. So, it allows us to perform different operations on X ML data
sources such as querying or reading, manipulating, modifying, and saving
the changes to XML documents. The System.Xml.Linq namespace
contains the required classes for LINQ to XML.
Parallel LINQ (PLINQ):
The Parallel LINQ or PLINQ was introduced wit h .NET Framework 4.0.
This provider provides the flexibility of parallel implementation of LINQ
to Objects. The PLINQ was designed in such a way that it uses the power
of parallel programming which targets the Task Parallel Library. So if you
want to execu te your LINQ query simultaneously or parallel on different
processors then you need to write the query using PLINQ.
Advantages of using LINQ?
1. We don’t need to learn new query language syntaxes for different data
sources as it provides common query synta x to query different data
sources.
2. Less code as compared to the traditional approach. That means using
LINQ we can minimize our code.
3. It provides Compile time error checking as well as intelligence
support in Visual Studio. This powerful feature help s us to avoid run -
time errors. munotes.in
Page 91
92 Database Programming In Asp.Net 4. LINQ provides a lot of inbuilt methods that we can use to perform
different operations such as filtering, ordering, grouping, etc. which
makes our work easy.
5. Its query can be reused.
Disadvantages of using LINQ?
The dis advantages of using LINQ are as follows:
1. Using LINQ it’s very difficult to write complex queries like SQL.
2. LINQ doesn’t take the full advantage of SQL features like cached
execution plan for the stored procedure.
3. We will get the worst performance if we don’t write the queries
properly.
4. If we do some changes to our queries, then we need to recompile the
application and need to redeploy the dll to the server.
5.5.2 Mapping Data Model To An Object Model :
The LINQ to SQL Object Model
In LINQ to SQL, an object model expressed in the programming language
of the developer is mapped to the data model of a relational database.
Operations on the data are then conducted according to the object model.
In this scenario, you do not issue database commands (for example,
INSERT) to the database. Instead, you change values and execute methods
within your object model. When you want to query the database or send it
changes, LINQ to SQL translates your requests into the correct SQL
commands and sends those commands to the database.
Fig. 5.7 The LINQ to SQL Object Model
The most fundamental elements in the LINQ to SQL object model and
their relationship to elements in the relational data model are summarized
in the following table: LINQ to SQL Object Model Relational Data Model Entity class Table Class member Column Association Foreign-key relationship Method Stored Procedure or Function
munotes.in
Page 92
93 Advanced Web Technologies 5.5.3 Introducing Query Syntax :
LinqTo SQL
Link to SQL is Object Relation Mapping (ORM) framework. It creates the
strongly typed dot net classes based on database tables. LINQ to SQL
enables you to write Select, Insert, Update, Delete query after after
strongly typed dot net classes generated. Behi nd the seen Link to SQL
provider converts LINQ query to normal SQL query, which is understands
by SQL server database. LINQ to SQL type only supports SQL server
database. It also supports Views, StoredProcedures, and Transactions.
First we will create the database table, name tblEmps in SQL server
as:
You can create the table according to your need and provide the table
name.
Now Right click on the project (or project folder) and select the option
Add New Item.
Select LINQ to SQL Classes Template and Give Name as Emp.dbml. You
can provide the name according to application requirement. Emp.dbml file
will be added under App_Code folder.
Click on Server Explorer and Right click on the Data Connections and
select t he option Add Connection.
Add Connection Pop up window will be opened, provide the SQL Server
details and click on OK button.
Database will be added under Data Connections as shown below.
munotes.in
Page 93
94 Database Programming In Asp.Net
Drag the table in the left pane. If primary key & foreign key rel ations are
there then it will automatically displayed. I have not created the foreign
key explicitly. Therefore the relation is not shown.
This process generates the Emp.dbml.layout and Emp.designer.cs file
under the Emp.dbml
It will also create the conn ection string automatically in web.config file.
providerName="System.Data.SqlClient" />
Click on Emp.designer.cs file, you will see EmpDataContext class that is
inherited from DataContext class. Remember that we have created the
Emp.dbml file and it will generate the EmpDataContext class. Whatever
munotes.in
Page 94
95 Advanced Web Technologies file name you will provide, it generates the class with class name
appended with DataContext as suffix.
using System;
using System.Collections.Generic;
using System.Linq;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object s ender, EventArgs e)
{
if(! IsPostBack)
{
LoadData();
}
}
protected void LoadData()
{
EmpDataContextdbContext = new EmpDataContext();
GridView1.DataSource= from emp in dbContext.tblEmps
select emp;
GridView1.DataBind();
}
}
Output:
LINQ have rich set of operators. It provides the operator for Filtering,
Sorting, Grouping, Aggregation, Projection, Partitioning, Concatenation
etc.
You ca n use any operators with the LINQ to get the result.
You can create a projection that matches the employee object structure. In
the above query it selects all the records. If you want that few column
should be display, then you can use linq query as
fromem p in dbContext.tblEmps
select new{emp.EmpID , emp.Name};
munotes.in
Page 95
96 Database Programming In Asp.Net Controlling column ordering and column name using LINQ :
LINQ enables you to change the order of column for display. You can also
provide the custom name for column.
fromemp in dbContext.tblEmps
select new {
DepartmentID=emp.DEPID,EmployeeID=emp.EmpID,EmpName=emp.N
ame };
Query filters :
LINQ provides the where clause to filter the query.
Suppose that you want the record of those employees whose name is starts
with letter “R” and salary greater than 20000.
fromemp in dbContext.tblEmps
where emp.Name.StartsWith("D") &&emp.Salary>20000
select emp;
Insert record using LINQ :
For inserting the record into the database using LINQ, first create the
object of EmpDataContext class.
EmpDataContextdbContext = n ew EmpDataContext();
In our example the table name is tblEmps. LINQ automatically generates
the tblEmps as a class and the table column as properties.
Now create the object of tblEmps class, so you can access the properties of
this class.
InsertOnSubmit() method is used to insert the record. SubmitChanges()
method commits all the changes into the database.
Please refer the previous code for populate the Gridview using LINQ. In
above example we have used LoadData() method for this purpose.
protected void btn Insert_Click(object sender, EventArgs e)
{
using(EmpDataContextdbContext =new EmpDataContext())
{
tblEmpempObj = new tblEmp
{
EmpID=Convert.ToInt32( txtEmpID.Text),
Name=txtName.Te xt,
Gender=txtGender.Text,
Salary=Convert.ToDouble( txtSalary.Text),
Address=txtAddress.Text,
DEPID = txtDepID.Text
}; munotes.in
Page 96
97 Advanced Web Technologies dbContext.tblEmps.InsertOnSubmit(empObj);
dbContext.SubmitChanges();
}
GetData();
}
Update record using LINQ :
For updating the record, first we need a unique ID of employee whose
record we want to update. For getting single record, SingleOrDefault is
used in LINQ. A fter that SubmitChanges() method is used to commit the
updated record in database.
In the given below code, you can easily see that, the table is converted into
the class and the column name is converted into the properties of tblEmps
class.
protected void btnUpdate_Click(object sender, EventArgs e)
{
using (EmpDataContextdbContext = new EmpDataContext())
{
tblEmpobj=dbContext.tblEmps.SingleOrDefault(em =>em.EmpID
== Convert.ToInt32(txtEmpID.Text));
obj.Name=t xtName.Text;
obj.Gender=txtGender.Text;
obj.Salary=Convert.ToDouble( txtSalary.Text);
obj.Address=txtAddress.Text;
obj.DEPID = txtDepID.Text;
dbContext.SubmitChanges ();
}
GetData();
}
Delete record using LINQ :
For deleting the record, we also need a single record according to unique
ID of employee. Here for deletion DeleteOnSubmit() method is used.
protected void btnDelete_Click(object sender, Even tArgs e)
{
using (EmpDataContextdbContext = new EmpDataContext())
{
tblEmpobj = dbContext.tblEmps.SingleOrDefault(em
=>em.EmpID == Convert.ToInt32(txtEmpID.Text));
dbContext.tblEmps.DeleteOnSubmit(obj );
dbContext.SubmitChanges();
}
GetData();
}
In this given example only seven records are available. Here we have
entered an eighth record, when you click on AddRecord button, munotes.in
Page 97
98 Database Programming In Asp.Net btnInsert_Click method will be executed and reco rd is added in the
database.
Getting the actual sql query generated by LINQ :
As you know that SQL server can understand only standard SQL queries
and objects. Therefore LINQ to SQL convert LINQ queries into standard
SQL query format.
You can easily see t he sql query, which is generated by LINQ to SQL.
There are several methods to achieve for the same.
EmpDataContextdbContext = new EmpDataContext();
varselectQuery = from emp in dbContext.tblEmps
select emp;
First Method:
You can use the l og property of DataContest class. It writes the generated
sql query at provided I/O.
dbContext.Log = Response.Output;
Second Method:
You can directly use the ToString() method as:
Response.Write(selectQuery.ToString());
munotes.in
Page 98
99 Advanced Web Technologies Third Method:
GetCommand method of DataContext class provides the information
about sql command generated by LINQ to SQL.
stringsqlQuery=dbContext.GetCommand(selectQuery).CommandText;
Response.Write(sqlQuery);
5.5.4 Entity Framework :
What is Entity Framework in .NET Framework?
Entity Framework is an open -source object -relational mapper framework
for .NET applications supported by Microsoft. It increases the developer’s
productivity as it enables developers to work with data using objects of
domain -specific classes without focusing on the underlying database
tables and columns where this data is stored. It eliminates the need for
most of the data -access code which is used to interact with the database
that developers usually need to write. It provides an abstract level to the
develo pers to work with a relational table and columns by using the
domain -specific object. It also reduces the code size of the data specific
applications and also the readability of the code increases by using it. This
is a new technology for accessing the dat a for Microsoft application. The
latest version for Entity Framework is 6.0.
The following figure describes where the Entity Framework presents in
your application.
Fig. 5.8 Entity Framework
The above figure represents how an entity framework interacts with the
domain class and database. It provides a connection between the business
entity and data tables in the database. It saves data stored in the properties
of business entities and also ret rieves data from the database and converts
it to business entities objects automatically. Entity Framework will
munotes.in
Page 99
100 Database Programming In Asp.Net execute the relevant query in the database and then materialize results into
instances of your domain objects for you to work within your app.
Fig. 5.9 Conceptual Model
When defining the class and features of entity framework first and then
entity framework convert it into the conceptual model first and it creates
database and objects in the database from the conceptual model this
method is cal led Code First. Now your object directly works with the
database to retrieve or make changes.
Features of Entity Framework :
It is platform independent.
It uses LinQ queries to manipulate the data in the database instead of
SQL queries.
It keeps the track o f values that have been changed of the properties
of entities.
It also save changes which are done insert, delete or update
operations.
It also handles concurrency so the data override by a user and will
reflect when another use fetches it.
It also handles transaction management automatically and also
provides the customize options for transaction management.
It provides caching which means it stores the result of the frequently
used queries.
It also follows certain conventions for programming so it by defa ult
configure the EF Model.
munotes.in
Page 100
101 Advanced Web Technologies It also allows configuring the EF Model by a fluent API to override
the default convention.
If you made any changes in database schema then you can reflect
those changes in EF model by writing migration command in CLI
(Command L ine Interface).
It also supports stored procedure.
It also supports parameterized queries.
5.6 LET US SUM UP This chapter covered features of ADO.NET. These features are designed
to give you the flexibility to handle database processing in a manner never
before possible with either of the previous versions of ADO. We studied
the components of ADO.NET that is Provider, Connection, Command,
Dataset, Datareader and Dataadapter.
The LINQ with ASP.NET,In LINQ to SQL, and an object model
expressed in the program ming language of the developer is mapped to the
data model of a relational database and Query syntax. Entity Framework is
an open -source object -relational mapper framework for .NET applications
supported by Microsoft.
5.7 UNIT END EXERCISES 1) What is ADO. NET?
2) Explain the advantages of ADO.NET.
3) Explain ADO.NET data architecture.
4) Explain different data provider.
5) Explain connection and command with example
6) Explain data adapter and dataset.
7) Explain data grid with example.
8) Explain data reader with example.
9) Explain the architecture of LINQ.
10) What is The LINQ to SQL Object Model?
11) Explain the working of LINQ.
12) Explain the features of Entity Framework.
munotes.in
Page 101
102 Database Programming In Asp.Net 5.8 LIST OF REFERENCES Reference No Reference Name 1 https://www.tutorialspoint.com/asp.net/asp.net_database_access.htm 2 https://www.guru99.com/insert-update-delete-asp-net.html 3 http://asp.net-informations.com/dbpro/asp-dbpro.htm 4 https://www.w3schools.com/asp/webpages_database.asp 5 https://www.geeksforgeeks.org/what -is-entity -
framework -in-net-framework/ 6 https://www.tutorialride.com/asp -net/linq -in-asp-
net.htm
*****
munotes.in
Page 102
103
6
DATABOUND CONTROLS IN ASP.NET
Unit Structure
6.0 Objectives
6.1 An Overview
6.2 SqlDataSource control
6.3 Databound Controls
6.3.1 DataList
6.3.2 DetailsView
6.3.3 FormView
6.3.4 GridView
6.3.5 ListView
6.3.6 Repeater
6.4 Let us Sum Up
6.5 Unit End Exercises
6.6 List of References
Self-Learning Topics: Charts and Data Pagers
6.0 OBJECTIVES What You Will Learn in This Chapter:
Learn about how to bind data to data bind control
- DataList
- DetailsView
- FormView
- GridView
- ListView
- Repeater
6.1 AN OVERVIEW Databound controls are used to display data to the end -user within the web
applications and using databound controls allows you to manipulate the
data within the web applications very easily.
Databound controls a re bound to the DataSource property. Databound
controls are composite controls that combine other ASP.NET Controls like
Text boxes, Radio buttons, Buttons and so on.
munotes.in
Page 103
104 Databound Controls In Asp.Net 6.2 SQLDATASOURCE CONTROL The SqlDataSource control is used to access data located in the relational
database. It uses the ADO.NET classes to interact with any databases that
are supported by ADO.NET. The providers that can be used are oracle,
SQL server, ODBC and OleDb. Using the control user can access and
manipulate data in the ASP.NET page .
To use the SqlDataSource control, set the ProviderName and
ConnectionString property. The ProviderName is used for the type of
the database used and ConnectionString for the connection to the
database.
The data of the SqlDataSource control can be cached and retrieved in the
application. The caching can be enabled by setting the EnableCaching
property to true. The filter of the SqlDataSource control supports a
FilterExpression property. User can add the selection criteria for filtering
of data.
The SqlData Source control code sample is as shown below:
DataSourceMode=”DataReader”
ConnectionString=”<%ConnectionStrings:EmployeeData%>”
SelectCommand=”Select name from Employee” >
6.3 DA TABOUND CONTROLS Every ASP.NET web form control inherits the DataBind method from its
parent Control class, which gives it an inherent capability to bind data to at
least one of its properties. This is known as simple data binding or inline
data binding .
Simple data binding involves attaching any collection (item collection)
which implements the IEnumerable interface, or the DataSet and
DataTable classes to the DataSource property of the control.
On the other hand, some controls can bind records, lists, or columns of
data into their structure through a DataSource control. These controls
derive from the BaseDataBoundControl class. This is called declarative
data binding .
The data source controls help the data -bound controls implement
functionalities such as, sorting, paging, and editing data collections.
The controls capable of simple data binding are derived from the
ListControl abstract class and these controls are:
● BulletedList munotes.in
Page 104
105 Advanced Web Technologies ● CheckBoxList
● DropDownList
● ListBox
● RadioButtonList
The controls capable of declarative data binding (a more complex data
binding) are derived from the abstract class CompositeDataBoundControl.
These controls are:
● DetailsView
● FormV iew
● GridView
● RecordList
6.3.1 Data List Control :
The DataList control is used to display a repeated list of items that are
bound to the control. There are different templates using which user can
design the layout of the control. The template property are mentioned
below: Template Property Description ItemTemplate It contains the HTML elements and controls to render for each row in the data source AlternatingItemTemplate It contains the HTML elements and controls to render once for every other row in the data source SelectedItemTemplate It contains the elements to render when the user selects an item in the DataList control EditItemTemplate It specifies the layout of an item when the edit mode is working HeaderTemplate It contains all the text and controls to be rendered at the beginning of the list FooterTemplate It contains all the text and controls to be rendered at the end of the list SeperatorTemplate It contains all elements to render between each item
A sample code to demonstrate the DataL ist control is as shown below: <%@Page Language=”C#” %> munotes.in
Page 105
106 Databound Controls In Asp.Net
Output is:
6.3.2 Details View Control:
Details view control is used as a data bound control. It is used to render
one record at a time. User can insert, update and delete the record from the
control. Some of the properties of the Detail sView control is as shown
below:
munotes.in
Page 106
107 Advanced Web Technologies Property Description AllowPaging It is a Boolean value to indicate the control supports navigation DataSource It is used to populate the control with the data source object DataSourceID It indicates the bound data source control with corresponding adapters AutoGenerateEditButton It is a Boolean value to indicate the column can be edited by the user AutoGenerateDeleteButton It is a Boolean value to indicate the records can be deleted DefaultMode It is used to indicate the default display mode of the control AutoGenerateRows It is a Boolean value to indicate the rows are automatically created for each field in the data source
The sample code for the Details View control is as shown below:
<%@ Page Language=”C#” %>
asp.net DetailsView example: how to use DetailsView The output is:
6.3.3 Formview Control:
The FormView control is data bound control but it uses templates version
of the DetailsView control. T he templates are used inside the control for
rendering it on the server. Some of the properties of the FormView control
are as shown below: Property Description EditItemTemplate It is used when the record is being edited by the user InsertItemTemplate It is used when a record is being created by the user ItemTemplate It is the template used to render the record to display only in an application
Methods of FormView control Methods Description InsertItem It is used to insert record in the database UpdateItem It is used to update record in the database DeleteItem It is used to delete the record in the database ChangeMode It is used to change the working state of the control
The sample code for the FormView control is as shown below: <%@ Page Languag”C#” AutoEventWireup=”true” CodeFile=”FormView.aspx.cs” Inherits=”FormView” %> munotes.in
Page 108
109 Advanced Web Technologies
asp.net FormView: how to use The code behind file for the control is as shown below:
public partial class FormView: System.Web.UI.Page
{
protected void Page_Load( object sender, EventArgs e)
{
if(!this.IsPostBack)
{
FormView1.HeaderStyle.BackColor=System.Drawing.Color.SeaGreen;
FormView1.HeaderStyle.ForeColor=System.Drawing.Color.Snow;
FormView1.HeaderStyle.Font.Bold=true;
FormView1.PagerStyle.BackColor=S ystem.Drawing.Color.ForestGreen;
FormView1.PagerStyle.ForeColor=System.Drawing.Color.AliceBlue;
FormView1.RowStyle.BackColor=System.Drawing.Color.Green;
FormView1.RowStyle.ForeColor=System.Drawing.Color.White;
}
}
}
munotes.in
Page 109
110 Databound Controls In Asp.Net Output is:
6.3.4 Gridveiw Cont rol:
The GridView control is used to provide flexibility in working and display
data from the database. The data in the GridView control is displayed in
the tabular format. It has several properties assigned to the control. Some
of the properties are as me ntioned below: Property Description AllowPaging It is a Boolean value indicating the
control supports paging AllowSorting It is a Boolean value indicating the
control supports sorting SortExpression It accepts the current expression
determining the orde r of the row Datasource It is used to get or set the data source object containing the data to populate the control AutoGenerateEditButton It is a Boolean value indicating that the user can edit the record in the control DataSourceID It indicates the data source control to be used AutoGenerateDeleteButton It is a Boolean value indicating that the user can delete the record in the control AutoGenerateColumns It is a Boolean value to indicate the columns are automatically created for each field of the data source AutoGenerateSelectButton It is a Boolean value to indicate the column should be added to select the particular record SortDirection It gets the sorting direction of the column for the control EmptyDataText It indicates the text to appear when there is no record in the data source
munotes.in
Page 110
111 Advanced Web Technologies The code sample of the GridView control is as shown below:
1) Add a new connection object to the ASP.NET web application as
shown below:
2) Next, add a new table for the connection object created above. T he
snippet for adding the table is as shown below:
3) Add the fields Sno, Name, Address in the table. Add values to the
respective fields in the table
4) Add the GridView and SqlDataSource control to the design view of
the web page.
munotes.in
Page 111
112 Databound Controls In Asp.Net 5) The source co de for the GridView control is as shown below:
<%@Page Language=”C#” AutoEventWireup=”true”
CodeFile=”binding.aspx.cs” Inherits=”binding” %>
Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1 -transitio nal.dtd”>
6) The code behind file contains the following code
protected void Button1_Click(object sender, EventArgs e)
{
SqlConn ection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings
[ “ConnectionString” ].ToString();
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = “Select * from deltable”;
cmd.Connection = c on;
DataSet ds = new DataSet();
da.Fill( ds, “deltable”);
GridView1.DataSource= ds;
GridView1.DataBind();
}
The output is:
munotes.in
Page 112
113 Advanced Web Technologies 6.3.5 Listview Control :
The ListView control is used to bind to data items returned to the data
source and display them. Th e control displays data in a format defined by
using templates and styles. The list of templates supported by the control
are as shown below: Templates Description ItemTemplate It identifies the data bound content to display for single items ItemSeperatorTemplate It identifies the content to be rendered between the items LayoutTemplate It identifies the root template that defines the main layout GroupTemplate It identifies the content of the group layout GroupSeperatorTemplate It identifies the content to be rendered between the group of items EmptyItemTemplate It identifies the control to render for an empty item when the GroupTemplate is used EmptyDataTemplate It identifies the content to render if the data source returns no data SelectedItemTemplate It identifies the content to render for the selected data item to differentiate the selected item from the other displayed items EditItemTemplate It identifies the content to render when the item is lost InsertItemTemplate It identifies the content to render when an item is being inserted
A sample code for the list control is as shown below:
ListViewControl – how to use ListView control in asp.net Output is:
6.3.6 Repeater Control :
The Repeater control is a data bound control created by using the
templates to display items. The control does not support editing, paging or
sorting of data rendered through the control. The list of templates
supported by the Repeater control are as mentioned below: Templates Description HeaderTemplate It contains all the text and controls to be rendered at the beginning of the list FooterTemplate It contains all the text and controls to be rendered at the end of the list AlternatingItemTemplate It contains the HTML elements and controls to render once for every other row in the data source SeperatorTemplate It contains all elements to render between each item ItemTemplate It contains the HTML elements and controls to render for each row in the data source munotes.in
Page 115
116 Databound Controls In Asp.Net The sample code for the Repeate r control is as shown below:
The code behind file is as shown below:
public part ial class _Default: System.Web.UI.Page
{
SqlConnection con;
SqlCommand cmd = new SqlCommand();
protected void Page_Load( object sender, EventArgs e)
{
con=new SqlConnection(
ConfigurationManager.ConnectionStrings[“constr”].ConnectionString);
cmd.Connection=con;
com.Open();
RepeatInformation.DataSource = cmd.ExecuteReader();
RepeatInformation.DataBind();
con.Close();
}
}
Output is :
6.4 LET US SUM UP This chapter covered the concept of data -binding and its different
classif ications in ASP.NET. Data Binding is a necessity while developing
any application and ASP.NET reduces the workload of programmers and
makes it necessary for them to explore more about it.
6.5 UNIT END EXERCISES 1. What is data binding and its types? Explai n with example? munotes.in
Page 117
118 Databound Controls In Asp.Net 2. Define:
a. DataList
b. DetailsView
c. FormView
d. GridView
e. ListView
f. Repeater
3. Explain DataList in detail?
4. Explain DetailView in detail?
5. Explain FormView in detail?
6. Explain GridView with example?
7. Explain ListView with example?
8. Explain Repeater in detail?
6.6 LIST OF REFERENCES Reference No Reference Name 1 https://www.tutorialspoint.com/asp.net/asp.net_database_access.htm 2 https://www.guru99.com/insert-update-delete-asp-net.html 3 http://asp.net-informations.com/dbpro/asp-dbpro.htm 4 https://www.w3schools.com/asp/webpages_database.asp
*****
munotes.in
Page 118
119
MODULE IV
7
SESSION MANAGEMENT
Unit Structure
7.0 Objective
7.1 Introduction
7.2 State Management
7.2.1.Client -Side state management
7.2.1.1. View state
7.2.1.2. QueryString
7.2.1.3. Coockie
7.2.1.4. Hidden Field
7.2.2 Server -Side state management
7.2.2.1. Session state
7.2.2.2 Application State
7.2.2.3 Cache
7.2.2.4 Profiles
7.3 Summary
7.4 Unit End Exercises
7.5 List of References
7.0 OBJECTIVE In this chapter we learned sate managemen t and its types i.e client side
state management and server -side state management.
We learned also View state,querystring Cookie, how to be hidden field in
the Client -Side state management .
7.1 INTRODUCTION Microsoft frameworks are strongly taken into consideration for their
security capabilities. Some of the surprising functions include
authentication -authorization control, HTTPS enforcement, error
management with Global Exception Handling support in ASP.NET Core,
COR S control, etc.
Talking about HTTP, that is this kind of protocol that doesn't have a
status. Therefore, if we want to transfer statistics from one page to some
other page or even after numerous visits to the identical page, we have to munotes.in
Page 119
120 Session Management use country control techniques. Today, we're going to research kingdom
control techniques the usage of ASP.NET.
State Management is the procedure in which developers can keep repute
and web page data on more than one requests for the identical or
extraordinary pages in the ne t application.
7.2 STATE MANAGEMENT 1. Meaning of State management method is to preserve state of
control, webpage, Item/data and consumer/user within the application.
2. In the state management, a new example of the web page class is
created on every occasion or every time the page is posted to the
server.
3. It approach that everyone information related to the web page and the
controls on the web page would be misplaced with every spherical
ride.
4. It is nothing but the current value of the page or d ata
5. Data want be hold in such styles of situations:
A. While navigating through internet web page
B. web page performs the round trip
Why we need state management? :
We need state management because when the user visit to his/her,
application browse r does the communication with the respective server
which is depending upon their requested functionality.
Using HTTP protocol, the application browser or internet browser
communicates with the server. When the response returns to client then it
is just cl ean up the resources such as data/Object, Allocated Memory,
Session Ids, URL Information.
What are the types of state Management?
State management has two types.
7.2.1 Client -side state management
7.2.2 Server -side state management
7.2.1 CLient-side state management :
In the client -side Management of user or client pages, during the end to
end interaction the information is stored in the user or client system. munotes.in
Page 120
121 Advanced Web Technologies The main benefit of getting this form of state management is that it saves a
tremendous amo unt of server reminiscence. We reduce the load on the
server to preserve state information.
Due to the increased bandwidth, it reduced speed of loading and creating
security issue for confidential data such as credit card number, password.
In the web appli cation .NET is support following types of methods in the
client -side state management:
7.2.1.1 View State
7.2.1.2 Query String
7.2.1.3 Cookie
7.2.1.4 Hidden field
7.2.1.1 View State:
View State is the method to hold the Value of the Page and Controls
among round trips.
It is a Page -Level State Management technique. View State is grown to
become on through default and typically serializes the facts in every
manipulate at the web webpage irrespective of whether in reality used
during the put up returned.
View state is property of every webpage which preserve or save value at
the post back time. For the same pages, it is built -in structure for
automatically saving the values between multiple requests. It stored the
page control value as string which is enc oding some hashing technology.
To store the information or data view state use Hidden field in the hashing
and encoding format. View state is not difficult to implement. There are
no server resources are required. It is providing the security which can be
compress.
Steps for view state:
1. Open New Project
2. Click on the web on the left side
3. select the ASP.NET EMPTY WEB Application
4. Now, Click on solution explorer, right click on ADD>New Item>
Web Form>Name it> click on ADD button, after this you will see
following code:
1. <%@ page language= "C#" autoeventwireup= "true" codebehind= "WebForm6.aspx.cs" inherits= "view_state.WebForm6" %> 2. munotes.in
Page 121
122 Session Management 3. 4. 5.
6.
7. 8. 9.
19. 20.
Now right the code like
1. //Declaration of x and y 2. public string x, y; 3. protected void Button1_Click(object sender, EventArgs e) 4. { 5. //TextBox1 and TextBox2 Value is Assigning on the variable a and b 6. x = TextBox1.Text; 7. y = TextBox2.Text; 8. //after clicking on Button TextBox value Will be Cleared 9. TextBox1.Text = TextBox2.Text = string.Empty; munotes.in
Page 122
123 Advanced Web Technologies 10. } 11. 12. protected void Button3_Click(object sender, EventArgs e) 13. { 14. //value of variable a and b is assingning on TextBox1 and Textbox2 15. TextBox1.Text = x; 16. TextBox2.Text =y; 17. } 18.
And execute this code.
You will get, output.
To save the variable in view state:
ViewState[“Subject”]=”Advanced Web Application”;
To retrieve the information in View State:
String value=ViewState[“Subject”];
7.2.1.2. Query string:
Query string is part of the URL, which is passing data or value one to
another or next page
The size of URL is 255 character long for example user entered welcome
page it will display on next page.
Query string is a easy way to bypass some information from one page to
another. The facts cab be without problems pass to 1 web page to ever y
other or to same web page. With query string technique the statistics
exceeded in URL of page request.
For send data to different web page Response.Redirect() approach used
and for retrieve facts from URL use Request.QueryString() approach used.
In Query String method we can despatched price to only desired web
page, and fee will be quickly. So Query string increase the general overall
performance of internet application.
Syntax of the query string:
Response.Redirect(“nextpage.aspx?name=value”);
Retrieve information from other page
Request.QueryString[“name”].ToString();
munotes.in
Page 123
124 Session Management 7.2.1.3. Cookie:
It provides in web application to store the user particular information.
Whenever user or client visit to websites cookies to storing the
preferences.
Cookie is small piece of text information which store the information and
request and pages as they go between the web server and browser.
Cookies are associated with a web site not with specific page hence the
application browser and server will exchang e cookie information.
There two types of Cookies 1. Persistent Cookie and 2. Non -Persistent
Cookie
1. Persistent cookie:
The persistent cookie permanently stored on hard drive of user.
Persistent cookie has expiry date time. This type of cookie permanentl y
stored user hard drive till date time we set.
For example: Response.Cookies[“Name”].Value=”IDOL”;
Response.Cookies[“IDOL”].Expires=DateTime.Now.AddM
inutes(30);
Using following syntax, we create Cookie:
HttpCookie strname= new HttpCookie(“name”);
Strname. Value=”IDOL”;
Strname.Expires=DateTime.Naow. AddMinutes(30);
Here, Response.Cookies is use to create the Cookie and 30 minutes is
expiry time after 30 Minutes cookies will expire.
2. Non persistent cookie:
This type of cookie does not store permanently on user’s hard drive. It
store whenever user accessing up information the same browser, once the
browser will closed the information will delete automatically.
To read cookie information:
If (Request.Cookie[“Name”]!=null)
{Lable1.Test=Request.Cookies[“Name”]. Value;
}
7.2.1.4. Hidden Field:
It’s not anything new, as all of us understand from HTML programming.
The hidden field is used to hide your client side records. It is not directly munotes.in
Page 124
125 Advanced Web Technologies seen to the client on the client interface; however, we may additionally se e
the value at the source page. So, it is not really helpful if you want to save
sensitive information. It is simply used to shop a small amount of
information that is often altered.
The Hidden fields are Html input control with hidden type that store in t he
Html hidden data
In their value property the hidden field can store one value only. The value
is stored as string and there fore for some types you need use casting.
The following code statistics the employee variety and has a value of
1001.
7.2.2 Server -Side State Management :
In this type of cookie information is store in the memory. About the user
this type of management stores the confidential and sensitive information
and disadvantage is that it uses more storage from the server.
7.2.2.1 Session’s state
7.2.2.2 Application State
7.2.2.3 Cache
7.2.2.4 Profile
7.2.2. 1 Session Sate:
Session state is a time period of time to visit an internet site or website for
a particular person. Session can save the user or client information on a
server . Session is a quality country control features to shop the patron data
on server separately for each consumer.
Session is a best state management features to store the client data on
server separately for each user.
Each and every session has their unique ID. Using cookie this ID is being
stored in the client machine.
By using session ID the server maintains the state of user information.
Without session ID when user makes a request, the ASP is creating
session ID and sends it with every request and respon se to same user.
Syntax of session:
Session[“session_name”]=”Session value”;
Declare session:
Session[“name”]=”IDOL”;
Response.Redirect(“nextpage.aspx”);
munotes.in
Page 125
126 Session Management To retrive the session value:
String myvalue=session[“name”].Tostring();
Response.Write(“Name=”+myval ue);
Mechanism of session Managements are :
1. In Proc mode
2. Out Proc mode
A. Sql Server
B. State Server
7.2.2.2 Application state:
Application state information is global storage mechanism which is used
to store data on server and shared for all clients or users that means data
stored in application state is common for all. In that data can be accessible
from anywhere in the application.
It is stored in memory on server and in the database it faster to storing and
retrieving information. It is cal led application -level state management.
Data member can be declared and defined in global.asax
To save application data
void Session_Start(object sender,EventArgs e)
{
Application.Lock();
Application[“PageCounter”]=(int)Applicatio n[“PageCounter”]+1;
Application.UnLock();
}
To read application data
void Page_Load(object sender, EventArgs e)
{
int Visitors=(int)Application[“PageCounter”];
}
Following events are of Applic ations State Management:
1. Application_Start()
2. Session_Start()
3. Application_Error
4. Session_End munotes.in
Page 126
127 Advanced Web Technologies 5. Application_End
6. Application_Disposed()
7.2.2.3 Cache:
To enhanced website performance caching features does helps. The cache
can store any data object, pages they can store in the memory, when first
time requested. User can store or cache data object, pages on the other
software or web server in the request stream for example browser or proxy
server. By allowing commonly requested content to be temporarily stored
faster way it is improving server performance.
Types of Caching are as following:
1. Output Caching
2. Data Caching
3. Object Caching
4. Class Caching
5. Configuration Caching
7.2.2.4 Profile :
As the applications must have to man age the users’ unique details or
information such as last date of visited, require query or enquiry. The
ASP.NET features helps to find or recognised users based unique identy.
Its profile features associate’s information with an individual user and
stores the information in a persistent format.
Syntax :
7.3 SUMMARY In this chapter we learned some state management mechanism using
ASP.NET MVC. It will help us to understand various method used for
enhancing it and provide an idea about state management.
7.4 UNIT END EXERCISES 1. Explain the types of state management. munotes.in
Page 127
128 Session Management 2. What is Cache explain it with an example.
3. How does Cookie works?
4. What is client -side state management?
5. What is server -side state management?
7.5 LIST OF REFERENCES Freeman, Adam. "Pro asp. netmvc 5 platform." Pro ASP.
NET MVC 5 Platform. Apress, Berkeley, CA, 2014. ISBN:
1430265418
Allen, K. Scott, et al. Professional ASP. NET MVC 5. Wrox Press,
2014. ISBN: 1118794753
MVC Framework - First Application (tutorialspoint.com)
Application State in ASP.Net (meeraacademy.com)
*****
munotes.in
Page 128
129
8
AJAX
Unit structure
8.0 Objective
8.1 What is Ajax?
8.2 Application with Ajax.
8.3 AJAX Controls
8.4 Testing an ASP.NET Ajax application
8.5 Global.asax and Web Config
8.6 Summary
8.7 Unit End Exercises
8.8 List of References
8.0 OBJECTIVE In this chapter we will learned :
1. What is AJAX? Why we need AJAX.
2. How we can create AJAX application.
3. Controls of the AJAX
4. Testing an ASP.NET Ajax application
5. Global.asax and Web Config
8.1 WHAT IS AJAX? In a simple word ajax means asynchronous JavaScript and XML which
used to create communication between client and server without require
postback . The benefit of this faster response to user It is client -side script.
The MVC Framework contai ns built -in support for unobtrusive Ajax. We
can use helper methods to define features. The features are based on
JQuery features.
The desktop and web application have difference i.e. stateless behaviour
of web application.
To enable the unobtrusive AJAX s upport in the MVC application, open
the Web.Config file and set the UnobtrusiveJavaScriptEnabled property
inside the appSettings section using the following code. If the key is
already present in your application, you can ignore this step.
After this, just open common layout file _Layout.cshtml. we will add
JQuery. munotes.in
Page 129
130 Ajax
< script src=”~/Scripts/jquery.unobtrusive -ajax.min. js”
type=”text/javascript”>
8.2 AP PLICATION WITH UNOBTRUSIVE AJAX 1. First create model file:
using System;
namespace MVCAjaxSupportExample.Models
{
Public class User
{
Public int UserId{ get;set;}
Public string firstName{get;set}
Public string LastName{get;set}
Public D ateTime Birthdate{ get; set}
Pubic Role Role { get, set}
}
Public enum Role {
Admin
Employee
Guest
}
}
Component of Ajax are following :
1. Ajax Control toolkit
2. XMLHHTTPRequest object in JavaScript
3. Using Jquery AJAX
4. Microsoft Ajax Library
5. Ajax server Control
munotes.in
Page 130
131 Advanced Web Technologies How the Ajax works? : Client Server Request(.aspx) Html and CSS .NET CODE Send page Scripting language Web services XMLHttpRequest ASP.NET AJAX Framwork ASP.NET AJAX Framework Send XML 8.3 AJAX CONTROLS 1. Update Panel Control
2. ScriptManager Control
3. ScriptManagerProxy Control
4. UpdateProgress Control
5. Timer
1. UpdatePanel:
The UpdatePanel control specifies a part of a Web page which can be
updated or refreshed partially based on the update condition. Refreshing a
specific part of a Web page is referred as partial -page update. You can
also add one or more UpdatePanel control in the Web page . The
UpdatePanel control uses the AJAX library to support the partial -page
rendering.
It is a container control that contain the all controls and that control define
the region or branch which is capable of making page updates.
For example:
. munotes.in
Page 131
132 Ajax 2. ScriptManager Control:
The ScriptManager manages all ASP.NET AJAX assets on an internet
web page. It renders the AJAX library to the browser and helps partial
page rendering. It additionally manages partial page uploads and provide
get right of entry to internet service method. Without script su pervisor we
can't use AJAX controls at the web page.
Syntax:
3. ScriptManagerProxy control:
A web page will have handiest one ScriptManager control. If your
software has a Master -Content page state of affairs and the MasterPage
has a ScriptManager control, then you may use the ScriptManagerProxy
control to feature distinctive scripts to the content material pages.
Sometimes, there can be the case when you aren't required to apply AJAX
on every and each net page by way of using the ScriptManagerProxy
control then you can add AJAX functionalities to precise net pages. Since,
ScriptManager at the Master Page will load the AJAX library on every
web page that derives from the MasterPage, although they're now not
wished, which would lead to a waste of resources.
4. Update Progress control:
This is used to display the progress of partial -page updates. You can use
one UpdateProgress control to represent the progress of partial -page
updates for the entire page. A lso, you can include an UpdateProgress
control for every UpdatePanel control. You can customize the default
layout and content of the UpdateProgress control to make it more
attractive.
It used during the server asynchronous processing. During the partial -page
update to complete the use of this is to provide information in the graphics
or Text that is displayed. Content inside this element can be an image.text
or similar HTML content.
Example :
Processing…..
munotes.in
Page 132
133 Advanced Web Technologies
5. Timer:
Timer Control is used to perform postbacks at defined time intervals. You
can also use the Timer control with an UpdatePanel control to enable
partial -page updates at a defined interval. You can also use the Timer
control to post the en tire page.
Timer is an Ajax control that can be used to update portion of page on
periodic, time basis. You can use if you want to update an image such as
on webpage advertisement or stock ticker/news ticker. It is add the code a
timer control directly to an UpdatePanel control.
Example:
ImageUrl=”~/images/contoso.png”/>
ontick=”timer1_Tick”>
8.4 TESTING AN ASP.NET AJAX APPLICATION After you install the Module for ASP.NET Testing on a pc running WAPT
or WAPT Pro Workplace, you may be in a position to test ASP.NET web
sites containing, especially, AS P.NET AJAX UpdatePanel Controls.
ASP requests normally incorporate __VIEWSTATE and
__EVENTVALIDATION parameters which need to be parameterized.
There are 2 approaches to switch these parameters in server response:
1. In the hidden field of the html code of response, or in the following
way:
munotes.in
Page 133
134 Ajax Reference: Testing of ASP.NET Applications (loadtestingtool.com)
It is just the case of ASP.NET AJAX UpdatePanel Controls usage. In both
cases, the Module for ASP.NET Testing will extract __VIEWSTATE and
__EVENTVALIDATION parameters from responses and correctly
parameterize them. This is done automatically by the module, so you will
not need to do any additional wor k and parameterize ASP requests
manually.
When the module finds a new occurrence of __VIEWSTATE
(__EVENTVALIDATION) during recording, it automatically creates
AspViewState (AspEventValidation) variable calculated
using $ViewState ($EventValidation) functi on, for example:
Reference: Testing of ASP.NET Applications (loadtestingtool.com)
The module detects from which response the current __VIEWSTATE
(__EVENTVALIDATION) was extracted, and substitutes the necessary
variable to the corresponding request which uses that __VIEWSTATE
(__EVENTVALIDATION). So, the Module for ASP.NET Testing
automatically finds __VIEWSTATE and __EVENTVALIDATION
parameters in server responses and parameterizes them, so that correct
__VIEWSTATEs (__EVENTVALIDATIONs) are extracted from the
necessary responses and transferred to the corresponding requests.
If this module is not installed and you record ASP requests, then at the end
of recording process you may receive a warning message. It notifies you
that some of requests contain ASP, s o they will not be parameterized
because the module is not installed.
munotes.in
Page 134
135 Advanced Web Technologies Note that the Module for ASP.NET Testing is optional. It facilitates the
design of your profiles and reduces the amount of manual work required to
test an ASP.NET site. If you are not su re about the necessity to use it in
your case, you can try the following steps.
1. After recording a virtual user profile, verify it using the "Verify Test"
button on the toolbar.
2. Take a look at the created logs. You can find them in the "Logs"
folder in the left view. If you see errors occurred during the
verification, especially 500 (internal server error), 501 or similar ones,
it means that profiles have been parameterized incorrectly. In this case
you can either install the Module for ASP.NET Testin g, or try to
parameterize your profiles manually using regular WAPT functions
available without the module.
8.5 GLOBAL ASAX AND WEB CONFIGU The Global.asax, also known as the ASP.NET application file, is located
in the root directory of an ASP.NET applicat ion. This file contains code
that is executed in response to application -level and session -level events
raised by ASP.NET or by HTTP modules.
8.6 SUMMARY From this chapter we have learned Ajax features in MVC. The key to
success with Ajax in ASP.NET MVC 5 is in understanding jQuery and
making jQuery work for you in your application. Not only is jQuery
flexible and powerful, but it also allows you to separate your script code
from your markup and write unobtrusive JavaScript. The separation means
you can fo cus on writing better JavaScript code and embracing all the
power jQuery has to offer.
8.7 UNIT END EXERCISES 1. Why we need Ajax in MVC?
2. What are the benefits in Ajax?
3. How does the work Ajax?
4. What are the controllers of Ajax?
5. Create one appli cation in Ajax with JQuery.
8.8 LIST OF REFERENCES Freeman, Adam. Pro asp. netmvc 5 platform." Pro ASP. NET
MVC 5 Platform. Apress, Berkeley, CA, 2014. ISBN: 1430265418 munotes.in
Page 135
136 Ajax Allen, K. Scott, et al. Professional ASP. NET MVC 5. Wrox Press,
2014. ISBN: 1118794753
MVC Framework - First Application (tutorialspoint.com)
Application State in ASP.Net (meeraacademy.com)
Testing of ASP.NET Applications (loadtestingtool.com)
*****
munotes.in
Page 136
137
MODULE V
9
WEB SERVICES AND WCF
Unit Structure
9.0 Objectives
9.1 Introduction
9.2 Web Service
9.2.1 Advantages of Web Services
9.2.2 Disadvantage of Web Services
9.2.3. Examples of web services
9.2.4 Creating and Consuming an XML WCF Service -Simple and
Database
9.2.5 WCF Features
9.2.6 Advantages of WCF
9.2.7 Examples of WCF Service
9.3 Summary
9.4 Unit End Exercises
9.5 List of References
9.0 OBJECTIVE From this chapter you under:
● What is mean by Web Service.
● What web service can do and cannot do .
● Identity the key components or technologies involved in web services.
● Identify who manages the web services specification.
● Examine the examples of the web services.
● Impart understanding of Web Techniques and Design Web Services .
9.1 INTRODUCTION Web services developed by Microsoft in June 2000, Web services as a key
component of its .Net initiative, a broad vision for embracing the Internet
in the development, engineeri ng, and use of software. Web Services is
nothing but software program by using this you can communicating your
web application. Web services are web application components. Web
Service means to interact with the objects over the internet. It is
functionali ty use in different platforms using protocols. munotes.in
Page 137
138 Web Services And Wcf ● It does not dependants on any language you can we can write web
services in any language and access the same using any other
language.
● It is protocol independent.
● It is platform independent.
● It is self -contained and self -describing.
● It is stateless architecture.
● HTTP and XML open and text -based are the basis for web services.
9.2 WEB SERVICE Where we can use web service :
● In XML (Extensible Markup Language) web service specifies only
the data understanding the application regarding programming
language.
● By using SOAP (Simple Object Access Protocol) communication
between the Services and the application done.
● In WSDL (Web Services Description Languages) a unique method
that is helpful to specify the web services to the other programs.
● With the help of UDDI (University Description, Discovery, and
Integration) can search web service registries.
1. XML stands for extensible Markup Language.
2. It was design ed to store and transferred the data.
3. It was designed for machine as well as human readable.
4. It was self -descriptive.
5. It stores data in plain text format.
6. It also useful to expand and upgrade to new operating system.
XML webservices are registe red so that potential users can find them
easily. We can do with the Universal Discovery Description and
Integration (UDDI).
XML Declaration
Syntax:
1. It is case sensitive.
2. first statement must be XML document munotes.in
Page 138
139 Advanced Web Technologies 3. HTTP protocol is used for overriding the value of encoding.
Whenever we use web services there are two ways to use web services :
1. Reusable application components.
2. Connect the existing software.
9.2.1 Advantages of Web Services :
1. It always uses the open, textual content -based totally preferred. net
service makes use of all the ones components even they are written in
diverse languages for extraordinary platforms.
2. It provides promotes the modular technique of the programming in
order that the more than one organization can talk with the identical
net service.
3. Internet offerings are clean to put in force however high -priced
because they use the existing infrastructure, and we will repackage
most of the packages because the w eb service.
4. It reduces the price of business enterprise application integration and
Business to business communications.
5. Web offerings are the interoperable enterprise that carries the 100
carriers and sell them interoperability.
9.2.2 Disadvantage of Web Services :
1. One of the limitations of Web Services is that SOAP, WSDL, UDDI
needs to be upgraded.
2. Support for collaboration is the limit of Web Service.
3. Web service limit is also a fee.
4. If we want to use web services in a high -performance environment, in
that case, the web service will slow down.
5. Use of the web service increases traffic to the network.
6. The level of security of Web Services is low.
7. We use a standard procedure to describe the quality of certain web
services.
8. The Web Service level is in draft form.
9. Maintaining intellectual property is a vendor and is the limit of web
service.
munotes.in
Page 139
140 Web Services And Wcf 9.2.3 Examples of web services :
Step 1: Open visual studio (version -2017) in menu create new project.
Step 2: New windows appears then you have to select web in left part and
in the right parts you have to select ASP .Net Web Application (.Net
Framework)
munotes.in
Page 140
141 Advanced Web Technologies Step 3: Select Web Application as Empty and web form.
Step 4: Right side windows you can see the name of Web applications
select add the new items.
munotes.in
Page 141
142 Web Services And Wcf Step 5: We have created one method that is add ()
Step 6: Run the method add () by clicking IIS Express.
munotes.in
Page 142
143 Advanced Web Technologies Step 7: You can see method add ()
Step 8: When you click on add () method, you have to put the values of
parameters.
Step 9: You can see output.
munotes.in
Page 143
144 Web Services And Wcf 9.2.4 Creating and Consuming an XML WCF Service -Simple and
Database :
WCF means Windows Communication Foundation. It is a framework for
building, configuring, and deploying network -distributed services. Firstly,
its Indigo, which enables hosting services in any type of operating system
process. WCF is a service -oriented appl ication. Using WCF we can build
connected secure, reliable, transacted solutions that integrate across
platforms.
It is a framework for building service -oriented applications. Data can be
sent as asynchronous messages from one service to another.
A client is an application which uses WCF client to communicate with
services or other clients.
To create client application :
● Get the service contract, bindings, and address information for
service endpoint: -this can be done by service Model Metadata Utility.
● Create a WCF client using that information: -WCF runtime converts
methods into messages send it to service, collect reply from service
for that message return value to that client.
● Call operations by using try and catch block
● Close the WCF objects.so t hat new client object gets a chance to
connect
The mainly reasons to use WCF are Distributed Application and
Interoperable
Distributed Application means do not run -on single system but multiple
systems which are connected over networks.
Interoperable means that an application can consume or connect with
another application, but it does not matter in which platform it is
developed.
Which consist of three parts
● WCF Service: What it is providing.
● WCF Service host: Where is it.
● Service Client: Who is the client of the Service.
WCF Hosting :
Web services that was hosted inside web server such as IIS using http or
Https protocols.
1. IIS munotes.in
Page 144
145 Advanced Web Technologies 2. WAS (Windows process activation services)
3. Self-hosting
4. Windows service
9.2.5 WCF Features :
1. Service Orientat ion: It uses Service -oriented architecture (SOA) on
which web services uses send and receive data.
2. Interoperability: It uses more industry stands for it.
3. Multiple Message Patterns: Different patterns are used like
request/replay pattern, one way mess age, duplex exchange pattern
4. Service Metadata: It is used to automatically generate and configure
clients for accessing WCF services. And published over HTTP and
HTTPS.
5. Security: Message can be encrypted to protect privacy.
6. Multiple Transports a nd Encodings: whenever Messages can be
sent on uses in transport protocols and encodings like HTTP.
7. Reliable and Queued Messages and Durable: Reliable message
uses reliable session and durable message pattern always saved to the
database.
8. Transaction s: WS-Atomic Transactions, Microsoft Distributed
Transaction coordinator and API Transaction
9. AJAX and REST Support: supported XML formats
10. Extensibility: to customize the behaviour of a service
9.2.6 Advantages of WCF:
1. It is interoperable with other services when compared to .Net
Remoting where the client and service must be .Net.
2. It services provide security and reliability in compared to ASMX web
services.
3. In WCF, there is no need to make much change in code fo r
implementing the security model and changing the binding. Instead, it
requires small changes in the configuration.
4. WCF has integrated logging mechanism with this changing the
configuration file settings will provide this functionality. In other
techn ology developer must write the code.
munotes.in
Page 145
146 Web Services And Wcf 9.2.7 Examples of WCF Service :
Step 1: For WCF service while creating new project under visual C#
select WCF (Window -1) and choose WCF service application as we must
apply WCF service (Window -2) then press ok with you r WCF service
name.
munotes.in
Page 146
147 Advanced Web Technologies Step 2: Check interface in solution Explorer that is (IService.cs). Here we
have GetData() Method so we have to make entry in interface service after
that execute your program by clicking on IIS Express (Internet Explorer)
Step 3: After Execution we get new window where we have to double
click on our methods that is GetData () and give the values to the
parameter which is right side of the window and press the button invoke. It
shows the information of sender and receiver.
munotes.in
Page 147
148 Web Services And Wcf
Step 4: We have created add() method
munotes.in
Page 148
149 Advanced Web Technologies
Step 5: Execute the program and put the values of a and b and press the
button invoke. It display addition of two numbers.
9.3 SUMMARY Web Services is nothing but software program by using this you can
communicating your web application. Web services are web application
components. Web service types of Reusable application components XML
(Extensible Markup Language), SOAP (Simple Object Access Protocol),
WSDL (Web Services Description Languages) and UDDI (University
Description, Discovery, and Integration) WCF means Windows
Communication Foundation. It is a framework for building, configuring,
and deploying network -distributed services. We can apply web service and
WCF services.
Self-Learning Topics:
Caching Web service responses
munotes.in
Page 149
150 Web Services And Wcf 9.4 UNIT END EXERCISES 1. What is web service. Explain Example of web service.
2. Explain WCF in details.
3. Explain Advantages of Web Service.
4. Explain Features of WCF.
5. Explain how to start WCF with example.
6. Design Web Application to produce and Consume a WCF Service.
7. Design Web Application to produce and consume a web Service.
9.5 LIST OF REFERENCES 1) https://www.javatpoint.com/web -services -in-c-sharp
2) https://www.aspsnippets.com/Articles/Simple -database -Web -Service -
Tutorial -in-ASPNet -with-Example.aspx
3) Spaanjaars, Imar. Beginning ASP. NET 4.5. 1: in C# and VB. John
Wiley & Sons, 2014. ISBN: 1861009038
4) MacDonald, Matthew. ASP. NET: The Complete Refe rence.
McGraw -Hill, Inc., 2002. ISBN:
5) https://www.w3schools.com/asp/default.ASP0072125764
6) Spaanjaars, Imar. Beginning ASP. NET 4.5. 1: in C# and VB. John
Wiley & Sons, 2014. ISBN: 1861009038
7) Allen, K. Scott, et al. Professional ASP. NET MVC 5. Wr ox Press,
2014. ISBN: 1118794753
8) Schildt, Herbert. C# 4.0: the complete reference. Tata McGraw -Hill
Education, 2010
*****
munotes.in
Page 150
151
MODULE VI
10
DESIGNING MVC APPLICATION
Unit Structure
10.0 Objective
10.1 Introduction
10.2 Designing MVC application
10.2.1 First application of MVC:
10.2.2 Creating new ASP.NET MVC Project
10.3 Creating a Simple Data -Entry Application with validations
10.3.1 Designing a Data Model
10.3.2 Linking action Method
10.3.3 Creating Action Method
10.4 Using Automatically Implemented Properties
10.5 Using Object and Collection Initializers
10.6 Using Extension Methods
10.7 Using Lambda Expressions
10.8 Programs based on MVC Pattern
10.9 Forms a nd HTML Helpers
10.10 Define and access the model type
10.11 Summary
10.12 Unit End Exercises
10.13 List of References
10.0 OBJECTIVE In this chapter we will learn how to create and design MVC application
using multiple patterns , methods and expressions.
Why we need it?
10.1 INTRODUCTION In the ultimate couple of years, I was simply randomly going via a
questionnaire section and located out there are numerous questions on
MVC, especially on the novice stage, or beginner degree to ASP.NET you
can say. There are many queries approximately wh ich is first -rate,
webforms or MVC, and if MVC, which version. As there are a few great
articles which are associated with MVC on C# Corner, this newsletter will
brief you about MVC, variations, a pattern software, and solution the
question: Why MVC? munotes.in
Page 151
152 Designing Mvc Application Toda y in case you do marketplace research the decision for for MVC is
massive and it's far growing in numbers. Each and each company these
days desires a MVC developer due to the fact every time a modern -day
mission for development comes, they certainly need t o broaden their
product in MVC. MVC Version 5 has been launched with new abilities
and the popularity of MVC is developing each day.
If your present -day assignment is in webforms and you find it flawlessly
every day, you could say why MVC?
It is important distinguished between the MVC architecture pattern and the
ASP.net MVC framework. The MVC.NET is old. It dates again to 1978
and the Smalltalk task at Xerox PARC —however it has won enormous
reputation today as a pattern for Web programs, for the following reason:
1. User interaction with an MVC application follows a natural cycle: the
user takes an action, and in response the application changes its data
model and delivers an updated view to the user. And then the cycle
repeats. This is a convenient fit fo r Web applications delivered as a
series of HTTP requests and responses.
2. Web applications necessitate combining several technologies
(databases, HTML, and executable code, for example), usually split
into a set of tiers or layers. The patterns that ari se from these
combinations map naturally onto the concepts in MVC.
The ASP.NET MVC Framework implements the MVC pattern and, in
doing so, provides greatly improved separation of concerns. In fact,
ASP.NET MVC implements a modern variant of the MVC pattern that is
especially suitable for Web applications.
MVC works as per following way of the diagram:
Figure 1
USER Controller View Model Communication Updates Presentation Modification Presentationnn munotes.in
Page 152
153 Advanced Web Technologies 10.2 DESIGNING MVC APPLICATION 10.2.1 First application of MVC:
Visual Studio Express contains all of the features we need to create, test
and deploy an MVC Framework application, but some of those features
are hidden away until we ask for them. To enable all of the features, select
Expert Settings from the Visual Studio Tools ------ > Settings menu.
10.2.2 Creating New Asp.Net Mvc Project:
By creating new MVC framework project in Visual studio.
Select New Proje ct from File menu then Open New Project dialog.
You can see in the following diagram, if we select the web templates in
Visual C# section, we will see the Web Application Project template.
Select this Project type.
Figure 2 (ref. Pro ASP.NET MVC 5 Adam Freeman)
Give or set the Name of new project for example PartyInvites and click on
Ok Button to continue.
which will ask us to set the initial content for the ASP.NET project