You are on page 1of 248

C# and .

NET Framework - Introduction

Syllabus : Window Based Applications.

Section No. Topic Name Page No.


20.1 .NET Environment 20 - 2
20.2 C# Language Editor and Integrated Environment 20 - 3
20.3 Understanding the Design and Code Views 20 - 12
20.4 User Interface Elements and Control
Class Hierarchy in C# 20 - 16
20.5 Programming with the Windows Controls 20 - 21
20.6 C# MDI Form 20 - 59
20.7 Dialog Box 20 - 66
20.8 Event Handling Basics 20 - 68
Two Marks Questions with Answers 20 - 78
Long Answered Questions 20 - 81

20 - 1 C# and .NET Programming


Window Based Applications

20.1 .NET Environment

Concept

1. Visual Studio is the Integrated Development Environment in which developers can work
while creating programs in one of many languages, including C#, for the .NET
Framework.
2. IDE can be used to create console as well as Graphical User Interface (GUI) applications
along with Windows Forms or WPF (Windows Presentation Foundation) applications,
web applications, and web services in both native code together with managed code for all
platforms supported by Microsoft Windows, Windows Mobile, Windows CE, .NET
Framework, .NET Compact Framework and Microsoft Silverlight.
Explanation

3. IDE offers a set of tools that help to write and modify the code, and detect and correct
errors in the programs.
4. Visual Studio supports various programming languages by means of language services,
which allow the code editor and debugger to support most of the modern day
programming languages, provided a language-specific service exists.
5. IDE includes a code editor that supports syntax highlighting and code completion using
IntelliSense for variables, functions and methods, language constructs like loops and
queries.
6. Microsoft Visual Studio IDE supports application development throughout the entire
application lifecycle, from design to deployment. IDE has tools for writing code,
designing interfaces, and also for getting a general overview of files or classes in the
application.
7. Microsoft Visual Studio provides tools for development of various types of applications.
These tool set includes Windows Forms Designer, WPF (Windows Presentation
Foundation) Designer, Web development, Class designer, Data designer and Mapping
designer.
8. Microsoft Visual Studio is available in the following editions
1. Visual Studio Express - Visual Studio Express is a free edition with this edition one
can build the app for Windows 8, Windows Phone, and the web. The languages
available as part of the Express editions are :
Visual Basic Express
Visual C++ Express

20 - 2 C# and .NET Programming


Window Based Applications

Visual C# Express
Visual Web Developer Express
Express for Windows Phone
2. Visual Studio Professional
3. Visual Studio Premium
4. Visual Studio Tools for Office
5. Visual Studio Ultimate
6. Visual Studio Team System and Test Professional
9. Brief history of Visual studio product

Product name Codename Internal Supported .NET Release


version Framework versions date

Visual Studio N/A 4.0 N/A 1995-04

Visual Studio 97 Boston 5.0 N/A 1997-02

Visual Studio 6.0 Aspen 6.0 N/A 1998-06

Visual Studio .NET (2002) Rainier 7.0 1.0 2002-02-13

Visual Studio .NET 2003 Everett 7.1 1.1 2003-04-24

Visual Studio 2005 Whidbey 8.0 2.0, 3.0 2005-11-07

Visual Studio 2008 Orcas 9.0 2.0, 3.0, 3.5 2007-11-19

Visual Studio 2010 Dev10/Rosario 10.0 2.0, 3.0, 3.5, 4.0 2010-04-12

Visual Studio 2012 Dev11 11.0 2.0, 3.0, 3.5, 4.0, 4.5 2012-09-12

Visual Studio 2013 Dev12 12.0 2.0, 3.0, 3.5, 4.0, 4.5, Upcoming
4.5.1

20.2 C# Language Editor and Integrated Environment

1. Using .NET Framework coupled with C# enables the creation of Windows applications,
Web services, database tools, components, controls.

20 - 3 C# and .NET Programming


Window Based Applications

2. Development environment and programming tools in the Visual Studio IDE

1. Menu Bar 2. Standard Toolbar


3. ToolBox 4. Forms Designer

5. Output Window 6. Solution Explorer

7. Properties Window

Fig. 20.2.1 Visual studio IDE

3. Visual Studio organizes development work in projects and solutions. A solution can
contain more than one project, such as a DLL and an executable that references that DLL.
4. Creating Windows Applications,
Windows Applications make use of screen area called a Form. Initially, the Form is
blank. Later controls (like buttons, text boxes, menus, check boxes, radio buttons, etc) can
be added as per the requirement of application.
5. To get a Windows Form, do the following.
To create Windows form project, click the File menu. Select New Project from the menu.
Click Visual C#, under Templates on the left.

20 - 4 C# and .NET Programming


Window Based Applications

Fig. 20.2.2 Project window

Select Windows Forms Application from the available templates.


Keep the Name on the default of WindowsFormsApplication1 or type in as per
application task and then click OK. After this new Windows Application project is
created.

Fig. 20.2.3 Tool box

20 - 5 C# and .NET Programming


Window Based Applications

The blank Form in the main window comes up with default name Form1 along with the
Toolbox, on the left hand side. From the Toolbox, controls can be added to that blank
Form1. (If Toolbox is not seen, its Tab is seen by clicking on it Toolbox would appear).

Fig. 20.2.4 New form

Solution Explorer is on the right side of the screen as shown below. (If not seen, click
on Solution Explorer entry on the View menu at the top of Visual Studio Express.)

Fig. 20.2.6 Solution explorer


Fig. 20.2.5 Solution explorer

20 - 6 C# and .NET Programming


Window Based Applications

Both projects (Console application as well as WindowsFormsApplication) have sections


for Properties, References, and a Program.cs file.
Double click the Program.cs file to open it and following code is seen.

Application code has using lines, a namespace, a class called Program, and a Main
Method.
The Main Method is the entry point of the program. The code between the curly
brackets of Main will get executed when the program first starts. The last line in the
WindowsApplication1 code above is the one that Runs Form1 when the Application
starts. A Main method starts program and Program.cs in the Solution Explorer
contains the code for Main method.

Fig. 20.2.7 Application files

20 - 7 C# and .NET Programming


Window Based Applications

Fig. 20.2.8 Form properties

6. Adding code and controls to the application


The menu has options for View Code and View Designer.

20 - 8 C# and .NET Programming


Window Based Applications

Fig. 20.2.9 Form code view

Fig. 20.2.10 Form design view

20 - 9 C# and .NET Programming


Window Based Applications

The code has partial class Form1. It's partial because some code is hidden from
developer.

Fig. 20.2.11 Form files

20 - 10 C# and .NET Programming


Window Based Applications

InitializeComponent is code (a Method) that is automatically generated when a new


Windows Application project created. As new controls are added the additional code is
added here.
Click back on the Form1.cs tab at the top to see form again. If the tab is not there, right
click Form1.cs in the Solution Explorer on the right. From the menu, select View
Designer.

Fig. 20.2.12 Form design view

It's in Designer view that controls like buttons and text boxes are added to form.

20 - 11 C# and .NET Programming


Window Based Applications

7. Running the program


When Start Debugging is clicked, Visual C# will Build the program first, and then run
it, if it can. If it can't run the program it shows error messages.
For running the program, either press F5, or click Debug > Start Debugging.

Fig. 20.2.13 Code debug menu

20.3 Understanding the Design and Code Views

1. There are two views in the Visual Studio IDE, the Design View and the Code View.
When Visual Studio IDE is opened, by default it displays the Design View as seen below.
2. The Design View allows to drag controls and drop them onto the form.
3. The Properties window is used to set the properties of objects and forms or other files
shown in the Solution Explorer.
4. The Solution Explorer allows to rename the project, forms, or even other files included
in the project.
5. The Design View gives a visual way to work with the controls, objects, project files etc.
6. The Code View is used, while implementing the functionality behind the visual controls
present on the form.
7. To switch between the Design View to the Code View, click "View" -> "Code" or right-
click the Windows Forms form in the Design View and select "View Code". Either
method will open the Code View.

20 - 12 C# and .NET Programming


Window Based Applications

Fig. 20.3.1 The Code View

8. The Code View displays all the code functionality.


9. In the above Figure, the Form1.cs tab is the one in which Code View is seen and the
Form1.cs (Design) tab, that is actually the Design mode of the Windows form Form1;
these tabs allows to switch among all the GUI elements of the Design View and the
related code in the Code View that is used to provide the functionality. It should be noted
that in the Design View only the Toolbox is fully loaded with the controls and not in the
code view.
10. Solution Explorer can be used to switch among the Design and Code Views by selecting
desired Windows Forms form (in case of multiple Windows Forms forms open), right-
clicking, and choosing either View Code or View Designer. This will open either the
Code or Design View of the selected Windows Forms form.
Sorting Properties in the Properties Window
Various objects and controls have many properties through which one may need to
navigate which is easy when properties are sorted. Property sorting can be done in either
categorically or alphabetically.

20 - 13 C# and .NET Programming


Window Based Applications

Categorized View
The Categorized View organizes properties in the form of sets of properties, and each set
has a name to describe that collection of properties; for example, there are categories named
Appearance, Behavior, Data, Design, Focus, and so on. One can switch to the Categorized
View by clicking the icon on the very left of the toolbar shown at the top of the Properties
window.

Fig. 20.3.2 Categorized View of properties

Alphabetical View
The Alphabetical View organizes properties in ascending order by name from a to z. One
can switch to the Alphabetical View by clicking the icon second from the left on the toolbar
shown in the top of the Properties window.

20 - 14 C# and .NET Programming


Window Based Applications

Fig. 20.3.3 Alphabetical View of properties

Setting the Properties of Solutions, Projects, and Windows Forms


1. Select the "WindowsFormsApplication1" solution, go to the Properties window, and set
its Name property value to "WindowsFormApp".
2. To view the solution file (.sln) in Visual Studio, click "Tools" -> "Options", go to the
Project and Solutions tab, choose General, check the "Always show solution" option, and
click "OK".
3. Select the "WindowsFormsApplication1" project in Solution Explorer, go to the
Properties window, and modify the Project File property value, that defines the file name
of the project, to appear as "WinApp.csproj". From here the project name can be altered.
4. Click "Form1", in the Solution Explorer window to set list of properties in the Properties
window.

20 - 15 C# and .NET Programming


Window Based Applications

Fig. 20.3.4 IDE with setting the properties for the solution, project, and Windows Forms form

20.4 User Interface Elements and Control Class Hierarchy in C#

Fig. 20.4.1 C# control class hierarchy

20 - 16 C# and .NET Programming


Window Based Applications

20.4.1 Controls in Windows Forms


Concept

This section explores the various controls available for the programmer in the .NET
framework that could be used in Windows Forms applications. Controls are components that
allow a user to interact with the application in various ways – for example a commonly used
control is the push button.
Explanation

The .NET control types can be broadly classified into the following types,
1. Command Controls :
Button, LinkLabel, NotifyIcon and ToolBar
2. Text Controls :
TextBox, RichTextBox, Label and StatusBar
3. Option Controls :
Checkbox, RadioButton, CheckedListBox, ComboBox, DomainUpDown,
NumericUpDown, ListBox, ListView and TreeView
4. Container Controls:
Panel, GroupBox, and TabControl
5. Graphic Controls :
PictureBox and ImageList
6. Menu Controls :
MainMenu and ContextMenu
7. Dialog Controls :
OpenFileDialog, SaveFileDialog, ColorDialog, FontDialog, PrintDialog,
PrintPreviewDialog and PageSetupDialog
8. Other Useful Controls :
DateTimePicker and MonthCalendar
DataGrid
Splitter
HscrollBar and VscrollBar
TrackBar and ProgressBar
Tooltip and ErrorProvider
Timer

20 - 17 C# and .NET Programming


Window Based Applications

20.4.2 Commonly used Windows Forms Controls

Fig. 20.4.2 Windows forms control

20 - 18 C# and .NET Programming


Window Based Applications

Sr. Control Use Description


No. picture

1. Button Fires a command/event when a It represents a button on a form. Its text


mouse click occurs or the Enter or property determines the caption
Esc key is pressed. displayed on the button's surface that
indicates the expected event or
command to occur.

2. CheckBox Allows user to select one or more It consists of a check box with text or
options. an image beside it. The check box can
also be represented as a button by
setting: checkBox1.Appearance =
Appearance.Button.

3. CheckedListBox Displays list of items. ListBox with checkbox preceding each


item in list.

4. ComboBox Provides TextBox and ListBox Hybrid control that consists of a


functionality. textbox and a drop-down list. It
combines properties from both the
TextBox and the ListBox.

5. DataGridView Manipulates data in a grid format. The DataGridView is the foremost


control to represent relational data. It
supports binding to a database. The
DataGridView was introduced in .NET
2.0 and supersedes the DataGrid.

6. GroupBox Groups controls. Use primarily to group radio buttons; it


places a border around the controls it
contains.

7. ImageList Manages a collection of images. Container control that holds a


collection of images used by other
controls such as the ToolStrip,
ListView, and TreeView.

20 - 19 C# and .NET Programming


Window Based Applications

8. Label Adds descriptive information to a Text that describes the contents of a


form. control or instructions for using a
control or form.

9. ListBox Displays a list of items—one or May contain simple text or objects. Its
more of which may be selected. methods, properties, and events allow
items to be selected, modified, added,
and sorted.

10. ListView Displays items and subitems. May take a grid format where each row
represents a different item and sub-
items. It also permits items to be
displayed as icons.

11. MenuStrip Adds a menu to a form. Provides a menu and submenu system
for a form. It supersedes the MainMenu
control.

12. Panel Groups controls. A visible or invisible container that


FlowPanelLayout groups controls. Can be made
scrollable.

TablePanelLayout FlowPanelLayout automatically aligns


controls vertically or horizontally.

TablePanelLayout aligns controls in a


grid.

13. PictureBox Contains a graphic. Used to hold images in a variety of


standard formats. Properties enable
images to be positioned and sized
within control's borders.

14. ProgressBar Depicts an application's progress. Displays the familiar progress bar that
gives a user feedback regarding the
progress of some event such as file
copying.

20 - 20 C# and .NET Programming


Window Based Applications

15. RadioButton Permits user to make one choice Represents a Windows radio button.
among a group of options.

16. StatusStrip Provides a set of panels that indicate Provides a status bar that is used to
program status. provide contextual status information
about current form activities.

17. TextBox Accepts user input. Can be designed to accept single- or


multi-line input. Properties allow it to
mask input for passwords, scroll, set
letter casing automatically, and limit
contents to read-only.

18. TreeView Displays data as nodes in a tree. Features include the ability to collapse
or expand, add, remove, and copy
nodes in a tree.

20.5 Programming with the Windows Controls AU : Dec.-17, 19, May-18, 19

20.5.1 Button Control

For adding a control to a form, use the Toolbox on the left of Visual Studio.
Move mouse over to the Toolbox, and click the arrow symbol next to Common
Controls.
Following list of things is seen that can be added to the form.
- Click the Button item under the Common Controls heading.
- This will select it. Now click once anywhere on form.
- A button will be drawn on form which look like this,

20 - 21 C# and .NET Programming


Window Based Applications

Fig. 20.5.1

(Hold down left mouse button and drag out a button to the size as per needed.)
A button is a control, which is an interactive component that enables users to
communicate with an application. A button is something where user clicks to generate
the command. When button is clicked , the code written for button gets executed. The
text on the button, which defaults to "button1", can be changed. Anything suitable can
be added here.
The Button class inherits directly from the ButtonBase class. A Button can be clicked by
using the mouse, ENTER key, or SPACEBAR if the button has focus.
Commonly used Button Properties

AutoEllipsis Gets or sets a value indicating whether the


ellipsis character (...) appears at the right edge
of the control, denoting that the control text
extends beyond the specified length of the
control. (Inherited from ButtonBase.)

AutoSize Gets or sets a value that indicates whether the


control resizes based on its contents. (Inherited
from ButtonBase.)

AutoSizeMode Gets or sets the mode by which the Button


automatically resizes itself.

20 - 22 C# and .NET Programming


Window Based Applications

BackColor Gets or sets the background color of the


control. (Inherited from ButtonBase.)

DefaultSize (Inherited from ButtonBase.)

Image Gets or sets the image that is displayed on a


button control. (Inherited from ButtonBase.)

ImageList Gets or sets the ImageList that contains the


Image displayed on a button control. (Inherited
from ButtonBase.)

IsDefault Gets or sets a value indicating whether the


button control is the default button. (Inherited
from ButtonBase.)

Text (Inherited from ButtonBase.)

TextAlign Gets or sets the alignment of the text on the


button control. (Inherited from ButtonBase.)

TextImageRelation Gets or sets the position of text and image


relative to each other. (Inherited from
ButtonBase.)

UseCompatibleTextRendering Gets or sets a value that determines whether to


use the compatible text rendering engine
(GDI+) or not (GDI). (Inherited from
ButtonBase.)

Important Button Methods


CreateAccessibilityInstance (Inherited from ButtonBase.)

Dispose Overloaded. Releases the resources used by the


ButtonBase. (Inherited from ButtonBase.)

GetPreferredSize Retrieves the size of a rectangular area into which


a control can be fitted. (Inherited from
ButtonBase.)

20 - 23 C# and .NET Programming


Window Based Applications

NotifyDefault Notifies the Button whether it is the default button


so that it can adjust its appearance accordingly.

PerformClick Generates a Click event for a button.

ToString Overridden.

Important button events

Click This is the events will work when the component or control is clicked. This is
the most widely using event.

Mouse Down This event will occur when the mouse pointer is over the component and a
mouse button is pressed.

Mouse Up Occurs when the mouse pointer is over the component and a mouse button is
released.
This will occurs when the control is clicked by the mouse.

Mouse Click Mouse click = Mouse Down + Mouse Up

Mouse Hover This events will occurs when the mouse remains stationary inside of the
control for an amount of time.

Mouse Leave Occurs when the mouse leaves the visible part of the control.

Key Down This event will occur when a key is first pressed.

Key Up Event will occurs when a key is released

Key Press Occurs when the control has focus and the user presses and releases a key.
Key Press = Key Down + Key Up

AutoSizeChanged Occurs when the value of the AutoSize property changes. (Inherited from
ButtonBase.)

DoubleClick Occurs when the user double-clicks the Button control.

MouseDoubleClick Occurs when the user double-clicks the Button control with the mouse.

20 - 24 C# and .NET Programming


Window Based Applications

Example
using System;
using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)


{
button1.Text = "Show Message";
}

private void button1_Click(object sender, EventArgs e)


{
MessageBox.Show("Technical Book Services – C# Programming");
}
}
}

20.5.2 TextBox

Allows to display text and to allow the user to enter information.


A multilane textbox has a practical limit 32kB of text.
If required any more text then RichTextBox is used.
A TextBox control is used to display, or accept as input, a single line of text. This
control has additional functionality that is not found in the standard Windows text box
control, including multiline editing and password character masking.
Commonly used Properties

AcceptsReturn Gets or sets a value indicating whether pressing ENTER in a multiline


TextBox control creates a new line of text in the control or activates
the default button for the form.

20 - 25 C# and .NET Programming


Window Based Applications

AcceptsTab Gets or sets a value indicating whether pressing the TAB key in a
multiline text box control types a TAB character in the control instead
of moving the focus to the next control in the tab order. (Inherited
from TextBoxBase.)

AutoSize Gets or sets a value indicating whether the height of the control
automatically adjusts when the font assigned to the control is changed.
This property is not relevant for this class. (Inherited from
TextBoxBase.)

BackColor Gets or sets the background color of the control. (Inherited from
TextBoxBase.)

BorderStyle Gets or sets the border type of the text box control. (Inherited from
TextBoxBase.)

CanUndo Gets a value indicating whether the user can undo the previous
operation in a text box control. (Inherited from TextBoxBase.)

CharacterCasing Gets or sets whether the TextBox control modifies the case of
characters as they are typed.

DefaultCursor Gets or sets the default cursor for the control. (Inherited from
TextBoxBase.)

DefaultSize (Inherited from TextBoxBase.)

ForeColor Gets or sets the foreground color of the control. (Inherited from
TextBoxBase.)

HideSelection Gets or sets a value indicating whether the selected text in the text box
control remains highlighted when the control loses focus. (Inherited
from TextBoxBase.)

Lines Gets or sets the lines of text in a text box control. (Inherited from
TextBoxBase.)

MaxLength Gets or sets the maximum number of characters the user can type or
paste into the text box control. (Inherited from TextBoxBase.)

20 - 26 C# and .NET Programming


Window Based Applications

Modified Gets or sets a value that indicates that the text box control has been
modified by the user since the control was created or its contents were
last set. (Inherited from TextBoxBase.)

MultiLine Overridden. Gets or sets a value indicating whether this is a multiline


TextBox control.

PasswordChar Gets or sets the character used to mask characters of a password in a


single-line TextBox control.

PreferredHeight Gets the preferred height for a text box. (Inherited from
TextBoxBase.)

ReadOnly Gets or sets a value indicating whether text in the text box is read-
only. (Inherited from TextBoxBase.)

ScrollBars Gets or sets which scroll bars should appear in a multiline TextBox
control.

SelectedText Returns or sets the string containing the currently selected text;
consists of a zero-length string ("") if no characters are selected.

SelectionLength Gets or sets the number of characters selected in the text box.
(Inherited from TextBoxBase.)

SelectionStart Returns or sets the starting point of text selected, indicates the position
of the insertion point if no text is selected Gets or sets the starting
point of text selected in the text box. (Inherited from TextBoxBase.)

ShortcutsEnabled Gets or sets a value indicating whether the defined shortcuts are
enabled. (Inherited from TextBoxBase.)

Text Overridden. Gets or sets the current text in the TextBox.

TextAlign Gets or sets how text is aligned in a TextBox control.

TextLength Gets the length of text in the control. (Inherited from TextBoxBase.)

UseSystemPasswordChar Gets or sets a value indicating whether the text in the TextBox control
should appear as the default password character.

WordWrap Indicates whether a multiline text box control automatically wraps


words to the beginning of the next line when necessary. (Inherited
from TextBoxBase.)

20 - 27 C# and .NET Programming


Window Based Applications

Commonly Used Methods

AppendText Appends text to the current text of a text box. (Inherited from
TextBoxBase.)

Clear Clears all text from the text box control. (Inherited from
TextBoxBase.)

ClearUndo Clears information about the most recent operation from the
undo buffer of the text box. (Inherited from TextBoxBase.)

Copy Copies the current selection in the text box to the Clipboard.
(Inherited from TextBoxBase.)

DeselectAll Specifies that the value of the SelectionLength property is


zero so that no characters are selected in the control.
(Inherited from TextBoxBase.)

Dispose Overloaded. Releases the resources used by the TextBox.

GetCharFromPosition Retrieves the character that is closest to the specified location


within the control. (Inherited from TextBoxBase.)

GetCharIndexFromPosition Retrieves the index of the character nearest to the specified


location. (Inherited from TextBoxBase.)

GetFirstCharIndexFromLine Retrieves the index of the first character of a given line.


(Inherited from TextBoxBase.)

GetFirstCharIndexOfCurrentLine Retrieves the index of the first character of the current line.
(Inherited from TextBoxBase.)

GetLineFromCharIndex Retrieves the line number from the specified character


position within the text of the control. (Inherited from
TextBoxBase.)

GetPositionFromCharIndex Retrieves the location within the control at the specified


character index. (Inherited from TextBoxBase.)

Paste Overloaded. Replaces the current selection in the text box


with the contents of the Clipboard.

20 - 28 C# and .NET Programming


Window Based Applications

ScrollToCaret Scrolls the contents of the control to the current caret position.
(Inherited from TextBoxBase.)

Select Overloaded. Selects text within the control. (Inherited from


TextBoxBase.)

SelectAll Selects all text in the text box. (Inherited from TextBoxBase.)

Important Events

AcceptsTabChanged Occurs when the value of the AcceptsTab property has changed.
(Inherited from TextBoxBase.)

BorderStyleChanged Occurs when the value of the BorderStyle property has changed.
(Inherited from TextBoxBase.)

Click Occurs when the text box is clicked. (Inherited from TextBoxBase.)

HideSelectionChanged Occurs when the value of the HideSelection property has changed.
(Inherited from TextBoxBase.)

ModifiedChanged Occurs when the value of the Modified property has changed.
(Inherited from TextBoxBase.)

MouseClick Occurs when the control is clicked by the mouse. (Inherited from
TextBoxBase.)

MultilineChanged Occurs when the value of the Multiline property has changed.
(Inherited from TextBoxBase.)

TextAlignChanged Occurs when the value of the TextAlign property has changed.

TextChanged Occurs when the value of the TextAlign property has changed.

Example
using System;
using System.Drawing;
using System.Windows.Forms;

public class addnum : Form {

Button BtnAdd = new Button();

20 - 29 C# and .NET Programming


Window Based Applications

TextBox txtBox1 = new TextBox();


TextBox txtBox2 = new TextBox();
TextBox txtBox3 = new TextBox();

public addnum() {
BtnAdd.Text = "Add";

BtnAdd.Click += new System.EventHandler(this.BtnAdd_Click);

this.Controls.Add(bsum);

textBox1.Location = new Point(15, 25);


textBox1.Size = new Size(80, 10);
textBox1.Text = "1int";
this.Controls.Add(textBox1);

textBox2.Location = new Point(15, 70);


textBox2.Size = new Size(80, 10);
textBox2.Text = "2int";
this.Controls.Add(textBox2);

textBox3.Location = new Point(15, 170);


textBox3.Size = new Size(80, 10);
textBox3.Text = "outputint";
this.Controls.Add(textBox3);

private void bsum_Click(object sender, System.EventArgs e) {


int a = Convert.ToInt32(textBox1.Text);
int b = Convert.ToInt32(textBox2.Text);
int c = a + b;
textBox3.Text = c.ToString();
}

public static void Main(string[] args) {


Application.Run(new addnum());
}
}

20 - 30 C# and .NET Programming


Window Based Applications

20.5.3 Label

Allows to display text to the user.


Labels are one of the most frequently used C# control. One can use the Label control to
display text in a set location on the page.
Label controls can also be used to add descriptive text to a Form to provide the user
with helpful information.
The Label class is defined in the System.Windows.Forms namespace.
Commonly used Properties

AutoEllipsis Gets or sets a value indicating whether the ellipsis character (...)
appears at the right edge of the Label, denoting that the Label text
extends beyond the specified length of the Label.

AutoSize Overridden. Gets or sets a value indicating whether the control is


automatically resized to display its entire contents.

BorderStyle Gets or sets the border style for the control.

DefaultSize Overridden.

FlatStyle Gets or sets the flat style appearance of the label control.

Image Gets or sets the image that is displayed on a Label.

ImageList Gets or sets the ImageList that contains the images to display in the
Label control.

PreferredHeight Gets the preferred height of the control.

PreferredWidth Gets the preferred width of the control.

RenderTransparent Indicates whether the container control background is rendered on the


Label.

Text Overridden.

TextAlign Gets or sets the alignment of text in the label.

20 - 31 C# and .NET Programming


Window Based Applications

Commonly used Methods

Dispose Overloaded. Releases the resources used by the Label.

GetPreferredSize Overridden.

CalcImageRenderBounds Determines the size and location of an image drawn within


the Label control based on the alignment of the control.

DrawImage Draws an Image within the specified bounds.

Important Events

AutoSizeChanged Occurs when the value of the AutoSize property changes.

BackgroundImageChanged Occurs when the BackgroundImage property changes.

BackgroundImageLayoutChanged Occurs when the BackgroundImageLayout property


changes.

Example
using System;
using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)


{
lbl1.Text = "This is a Lable";
lbl1.BorderStyle = BorderStyle.FixedSingle;
lbl1.TextAlign = ContentAlignment.MiddleCenter;
}
}
}

20 - 32 C# and .NET Programming


Window Based Applications

20.5.4 CheckBox

Allows the user to select or deselect an option from multiple options.


CheckBoxes allow the user to make multiple selections from a number of options.
CheckBox gives the user an option, such as true/false or yes/no. On clicking the check
box it can be selected and again clicking it would deselect it.
The CheckBox control can display an image or text or both. Usually CheckBox comes
with a caption, which can be set in the Text property.
checkBox1.Text = "Net-informations.com";
One can use the CheckBox control ThreeState property to direct the control to return the
Checked, Unchecked, and Indeterminate values. For this set the check box’s ThreeState
property to True to indicate that it support three states.
checkBox1.ThreeState = true;
The radio button and the check box are used for different functions. Use a radio button
when application needs that the user choose only one option. When user can choose all
appropriate options, then the a check box is used.
Commonly used Properties

Appearance Gets or sets the value that determines the appearance of a CheckBox
control.

AutoCheck Gets or set a value indicating whether the Checked or CheckState


values and the CheckBox's appearance are automatically changed
when the CheckBox is clicked.

AutoEllipsis Gets or sets a value indicating whether the ellipsis character (...)
appears at the right edge of the control, denoting that the control text
extends beyond the specified length of the control. (Inherited from
ButtonBase.)

AutoSize Gets or sets a value that indicates whether the control resizes based
on its contents. (Inherited from ButtonBase.)

BackColor Gets or sets the background color of the control. (Inherited from
ButtonBase.)

CheckAlign Gets or sets the horizontal and vertical alignment of the check mark
on a CheckBox control.

20 - 33 C# and .NET Programming


Window Based Applications

Checked Gets or set a value indicating whether the CheckBox is in the


checked state.

CheckState Gets or sets the state of the CheckBox.

DefaultImeMode Gets the default Input Method Editor (IME) mode supported by this
control. (Inherited from ButtonBase.)

FlatAppearance Gets the appearance of the border and the colors used to indicate
check state and mouse state. (Inherited from ButtonBase.)

FlatStyle Gets or sets the flat style appearance of the button control. (Inherited
from ButtonBase.)

Image Gets or sets the image that is displayed on a button control. (Inherited
from ButtonBase.)

ImageAlign Gets or sets the alignment of the image on the button control.
(Inherited from ButtonBase.)

ImageList Gets or sets the ImageList that contains the Image displayed on a
button control. (Inherited from ButtonBase.)

IsDefault Gets or sets a value indicating whether the button control is the
default button. (Inherited from ButtonBase.)

Text (Inherited from ButtonBase.)

TextAlign Overridden. Gets or sets the alignment of the text on the CheckBox
control.

ThreeState Gets or sets a value indicating whether the CheckBox will allow
three check states rather than two.

UseVisualStyleBackColor Gets or sets a value that determines if the background is drawn using
visual styles, if supported. (Inherited from ButtonBase.)

Methods
CreateAccessibilityInstance Overridden. Creates a new accessibility object for the
CheckBox control.

Dispose Overloaded. Releases the resources used by the


ButtonBase. (Inherited from ButtonBase.)

20 - 34 C# and .NET Programming


Window Based Applications

GetPreferredSize Retrieves the size of a rectangular area into which a control


can be fitted. (Inherited from ButtonBase.)

OnClick Overridden. Raises the Click event.

ToString Overridden. Returns a string that represents the current


CheckBox control.

Events

AutoSizeChanged Occurs when the value of the AutoSize property changes. (Inherited
from ButtonBase.)

CheckedChanged Occurs when the value of the Checked property changes.

CheckStateChanged Occurs when the value of the CheckState property changes.

DoubleClick Occurs when the user double-clicks the CheckBox control.

ImeModeChanged Occurs when the ImeMode property is changed. This event is not
relevant for this class. (Inherited from ButtonBase.)

MouseDoubleClick Occurs when the user double-clicks the CheckBox control.

Example
using System;
using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void btn1_Click(object sender, EventArgs e)


{
string msg = "";

if (chb1.Checked == true)
{

20 - 35 C# and .NET Programming


Window Based Applications

msg = "Technical Publication C#";


}

if (chb2.Checked == true)
{
msg = msg + "Technical Publication C++";
}

if (chb3.Checked == true)
{
msg = msg + " Technical Publication VB";
}

if (msg.Length > 0)
{
MessageBox.Show (msg + " selected ");
}
else
{
MessageBox.Show ("No checkbox selected");
}

checkBox1.ThreeState = true;
}
}
}

20.5.5 RadioButton

Allows the user to select from a list of possible distinct options.


Radio buttons are also called Option Buttons. These are similar to checkboxes because
the user can select and deselect them.
Checkboxes work independently, but radiobuttons are intented to work in a group.
When one radio button in a group is selected, the others are automatically deselected.
When a user clicks on a radio button, it becomes checked, and all other radio buttons
with same group become unchecked.
Radiobuttons allow the user to select one choice out of the set of options. All
radiobuttons in a given container such as a form make a group. Radiobuttons can
display text an image or both.

20 - 36 C# and .NET Programming


Window Based Applications

Commonly used Properties

Appearance Gets or sets a value determining the appearance of the


RadioButton.

AutoCheck Gets or sets a value indicating whether the Checked value and the
appearance of the control automatically change when the control
is clicked.

AutoEllipsis Gets or sets a value indicating whether the ellipsis character (...)
appears at the right edge of the control, denoting that the control
text extends beyond the specified length of the control. (Inherited
from ButtonBase.)

AutoSize Gets or sets a value that indicates whether the control resizes
based on its contents. (Inherited from ButtonBase.)

BackColor Gets or sets the background color of the control. (Inherited from
ButtonBase.)

BackgroundImage Gets or sets the background image displayed in the control.


(Inherited from Control.)

BackgroundImageLayout Gets or sets the background image layout as defined in the


ImageLayout enumeration. (Inherited from Control.)

CheckAlign Gets or sets the location of the check box portion of the
RadioButton.

Checked Gets or sets a value indicating whether the control is checked.

DefaultSize Overridden.

FlatAppearance Gets the appearance of the border and the colors used to indicate
check state and mouse state. (Inherited from ButtonBase.)

FlatStyle Gets or sets the flat style appearance of the button control.
(Inherited from ButtonBase.)

20 - 37 C# and .NET Programming


Window Based Applications

ForeColor Gets or sets the foreground color of the control. (Inherited from
Control.)

Image Gets or sets the image that is displayed on a button control.


(Inherited from ButtonBase.)

ImageAlign Gets or sets the alignment of the image on the button control.
(Inherited from ButtonBase.)

IsDefault Gets or sets a value indicating whether the button control is the
default button. (Inherited from ButtonBase.)

Text (Inherited from ButtonBase.)

TextAlign Overridden. Gets or sets the alignment of the text on the


RadioButton control.

UseVisualStyleBackColor Gets or sets a value that determines if the background is drawn


using visual styles, if supported. (Inherited from ButtonBase.)

Methods

CreateAccessibilityInstance Overridden. Creates a new accessibility object for the


RadioButton control.

Dispose Overloaded. Releases the resources used by the ButtonBase.


(Inherited from ButtonBase.)

GetPreferredSize Retrieves the size of a rectangular area into which a control


can be fitted. (Inherited from ButtonBase.)

ToString Overridden. Overrides the ToString method.

Events

AppearanceChanged Occurs when the Appearance property value changes.

AutoSizeChanged Occurs when the value of the AutoSize property changes.


(Inherited from ButtonBase.)

CheckedChanged Occurs when the value of the Checked property changes.

20 - 38 C# and .NET Programming


Window Based Applications

Click Occurs when the control is clicked. (Inherited from Control.)

DoubleClick Occurs when the user double-clicks the RadioButton control.

MouseDoubleClick Occurs when the user double-clicks the RadioButton control with
the mouse.

using System;
using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)


{
radButton1.Checked = true;
}

private void button1_Click(object sender, EventArgs e)


{
if (radButton1.Checked == true)
{
MessageBox.Show ("Window Seat Taken");
return;
}
else if (radButton2.Checked == true)
{
MessageBox.Show("Center Seat Taken ");
return;
}
else
{
MessageBox.Show("Corner Seat Taken");
return;
}
}
}
}

20 - 39 C# and .NET Programming


Window Based Applications

20.5.6 ComboBox

Allows the user to either select an item from a drop-down box or enter a different item.
Both the ComboBox and ListBox controls are derived from the ListControl class.
A ComboBox displays a text box combined with a ListBox, which enables the user to
select items from the list or enter a new value .
Commonly Properties

AllowSelection Gets a value indicating whether the list enables selection of list items.
(Inherited from ListControl.)

DataSource Gets or sets the data source for this ComboBox.

DisplayMember Gets or sets the property to display for this ListControl. (Inherited
from ListControl.)

DropDownHeight Gets or sets the height in pixels of the drop-down portion of the
ComboBox.

DropDownStyle Gets or sets a value specifying the style of the combo box.

DropDownWidth Gets or sets the width of the of the drop-down portion of a combo
box.

DroppedDown Gets or sets a value indicating whether the combo box is displaying
its drop-down portion.

FlatStyle Gets or sets the appearance of the ComboBox.

Focused Overridden. Gets a value indicating whether the ComboBox has


focus.

FormatString Gets or sets the format-specifier characters that indicate how a value
is to be displayed. (Inherited from ListControl.)

FormattingEnabled Gets or sets a value indicating whether formatting is applied to the


DisplayMember property of the ListControl. (Inherited from
ListControl.)

20 - 40 C# and .NET Programming


Window Based Applications

IntegralHeight Gets or sets a value indicating whether the control should resize to
avoid showing partial items.

ItemHeight Gets or sets the height of an item in the combo box.

Items Gets an object representing the collection of the items contained in


this ComboBox.

MaxDropDownItems Gets or sets the maximum number of items to be shown in the drop-
down portion of the ComboBox.

MaxLength Gets or sets the number of characters a user can type into the
ComboBox.

PreferredHeight Gets the preferred height of the ComboBox.

SelectedIndex Problems when populating before control is displayed. Overridden.


Gets or sets the index specifying the currently selected item.

SelectedItem Gets or sets currently selected item in the ComboBox.

SelectedText Gets or sets the text that is selected in the editable portion of a
ComboBox.

SelectedValue Problems when populating before control is displayed. Gets or sets


the value of the member property specified by the ValueMember
property. (Inherited from ListControl.)

SelectionLength Gets or sets the number of characters selected in the editable portion
of the combo box.

SelectionStart Gets or sets the starting index of text selected in the combo box.

Sorted Gets or sets a value indicating whether the items in the combo box are
sorted.

Text Overridden. Gets or sets the text associated with this control.

ValueMember Gets or sets the property to use as the actual value for the items in the
ListControl. (Inherited from ListControl.)

20 - 41 C# and .NET Programming


Window Based Applications

Methods

Add Adds an item to the list of items

AddRange Adds an array of items to the list of items

AddItemsCore Adds the specified items to the combo box.

BeginUpdate Maintains performance when items are added to the ComboBox one at
a time.

Dispose Overloaded. Releases the resources used by the ComboBox.

EndUpdate Resumes painting the ComboBox control after painting is suspended


by the BeginUpdate method.

FilterItemOnProperty Overloaded. Returns the current value of the ListControl item, if the
item is a property of an instance of the ListControl class. (Inherited
from ListControl.)

FindString Overloaded. Finds the first item in the ComboBox that starts with the
specified string.

FindStringExact Overloaded. Finds the item that exactly matches the specified string.

GetItemHeight Returns the height of an item in the ComboBox.

GetItemText Returns the text representation of the specified item. (Inherited from
ListControl.)

OnClick Raises the Click event. (Inherited from Control.)

RefreshItem Overridden. Refreshes the item contained at the specified location.

RefreshItems Overridden. Refreshes all ComboBox items.

ResetText Overridden.

Select Overloaded.

SelectAll Selects all the text in the editable portion of the ComboBox.

SetBoundsCore Overridden. Sets the size and location of the ComboBox.

ToString Overridden. Returns a string that represents the ComboBox control.

20 - 42 C# and .NET Programming


Window Based Applications

Events
BackgroundImageChanged Occurs when the value of the BackgroundImage property
changes.

BackgroundImageLayoutChanged Occurs when the BackgroundImageLayout property


changes.

DrawItem Occurs when a visual aspect of an owner-drawn ComboBox


changes.

DropDown Occurs when the drop-down portion of a ComboBox is


shown.

DropDownClosed Occurs when the drop-down portion of the ComboBox is no


longer visible.

DropDownStyleChanged Occurs when the DropDownStyle property has changed.

Format Occurs when the control is bound to a data value. (Inherited


from ListControl.)

FormatInfoChanged Occurs when the value of the FormatInfo property changes.


(Inherited from ListControl.)

FormatStringChanged Occurs when value of the FormatString property changes


(Inherited from ListControl.)

FormattingEnabledChanged Occurs when the value of the FormattingEnabled property


changes. (Inherited from ListControl.)

MeasureItem Occurs each time an owner-drawn ComboBox item needs to


be drawn and when the sizes of the list items are determined.

SelectedIndexChanged Occurs when the SelectedIndex property has changed.

SelectedValueChanged Occurs when the SelectedValue property changes. (Inherited


from ListControl.)

SelectionChangeCommitted Occurs when the selected item has changed and that change
is displayed in the ComboBox.

20 - 43 C# and .NET Programming


Window Based Applications

TextUpdate Occurs when the control has formatted the text, but before
the text is displayed.

ValueMemberChanged Occurs when the ValueMember property changes. (Inherited


from ListControl.)

Example
using System;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {
cboBox1.Items.Add("Seats");
cboBox1.Items.Add("Total");
}
private void cboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
cbo2.Items.Clear();
if (cbobox1.SelectedItem == "Seats")
{
cboBox2.Items.Add("Front");
cboBox2.Items.Add("Rear");
cboBox2.Items.Add("Centre");
}
else if (cboBox1.SelectedItem == "Total")
{
cboBox2.Items.Add("2");
cboBox2.Items.Add("4");
cboBox2.Items.Add("8");
}
}
}
}

20.5.7 ListBox

Allows the user to select an item from a list of items.

20 - 44 C# and .NET Programming


Window Based Applications

The ListBox control enables to display a list of items to the user that the user can select
by clicking.
In addition to display and selection functionality, the ListBox also provides features that
enable to efficiently add items to the ListBox and to find text within the items of the list.
Properties
AllowSelection Overridden. Gets a value indicating whether the ListBox currently enables
selection of list items.

BackColor Overridden.
BorderStyle Gets or sets the type of border that is drawn around the ListBox.

ColumnWidth Gets or sets the width of columns in a multicolumn ListBox.

DataSource Gets or sets the data source for this ListControl. (Inherited from
ListControl.)

DisplayMember Gets or sets the property to display for this ListControl. (Inherited from
ListControl.)

FilterItemOnProperty Overloaded. Returns the current value of the ListControl item, if the item is
a property of an instance of the ListControl class. (Inherited from
ListControl.)

FormatString Gets or sets the format-specifier characters that indicate how a value is to be
displayed. (Inherited from ListControl.)

FormattingEnabled Gets or sets a value indicating whether formatting is applied to the


DisplayMember property of the ListControl. (Inherited from ListControl.)

ForeColor Overridden.

HorizontalScrollbar Gets or sets a value indicating whether a horizontal scroll bar is displayed in
the control.

IntegralHeight Gets or sets a value indicating whether the control should resize to avoid
showing partial items.

ItemHeight Gets or sets the height of an item in the ListBox.

Items Gets the items of the ListBox.

MultiColumn Gets or sets a value indicating whether the ListBox supports multiple
columns.

PreferredHeight Gets the combined height of all items in the ListBox.

20 - 45 C# and .NET Programming


Window Based Applications

ScrollAlwaysVisible Gets or sets a value indicating whether the vertical scroll bar is shown at all
times.

SelectedValue Gets or sets the value of the member property specified by the
ValueMember property. (Inherited from ListControl.)

SelectionMode Specifies the selection behaviour of a list box. MultiExtended, MultiSimple,


One, None. Gets or sets the method in which items are selected in the
ListBox.

Sorted Gets or sets a value indicating whether the items in the ListBox are sorted
alphabetically.

Text Overridden. Gets or searches for the text of the currently selected item in
the ListBox.

TopIndex Gets or sets the index of the first visible item in the ListBox.

UseTabStops Gets or sets a value indicating whether the ListBox can recognize and
expand tab characters when drawing its strings.

ValueMember Gets or sets the property to use as the actual value for the items in the
ListControl. (Inherited from ListControl.)

Methods
BeginUpdate Maintains performance while items are added to the ListBox one at a time by
preventing the control from drawing until the EndUpdate method is called.

ClearSelected Unselects all items in the ListBox.

DefaultItemHeight Specifies the default item height for an owner-drawn listbox.

EndUpdate Resumes painting the ListBox control after painting is suspended by the
BeginUpdate method.

FindString Finds the first item in the ListBox that starts with the specified string

FindStringExact Finds the first item in the ListBox that matches the specified string exactly.

GetItemHeight Returns the text representation of the specified item. (Inherited from
ListControl.)

GetItemRectangle Returns the bounding rectangle for an item in the ListBox.

20 - 46 C# and .NET Programming


Window Based Applications

IndexFromPoint Overloaded. Returns the zero-based index of the item at the specified
coordinates.

Refresh Overridden. Forces the control to invalidate its client area and immediately
redraw itself and any child controls.

RefreshItem Overridden. Refreshes the item contained at the specified index.

RefreshItems Overridden. Refreshes all ListBox items and retrieves new strings for them.

Sort Sorts the items in the ListBox.

ToString Overridden. Returns a string representation of the ListBox.

Methods - Single Selection

SelectedIndex Gets or sets the zero-based index of the currently selected item in the
listbox. Nothing is returned if no element is currently selected. Overridden.
Gets or sets the zero-based index of the currently selected item in a ListBox.
This is the first selected item when there is multiple selection
(SelectionMode = MultiSimple)

SelectedItem Gets or sets the currently selected item in a the listbox.

Methods - Multiple Selection

GetSelected Determines if a particular zero-based item is


currently selected.

SelectedIndex Gets the zero-based index of the first selected


item in the listbox.

SelectedItem Gets the first selected item in the listbox. Gets or


sets the currently selected item in the ListBox.

SelectedIndices Represents a collection of all the index positions


of all the selected items. Read Only. Gets a
collection that contains the zero-based indexes of
all currently selected items in the ListBox.

20 - 47 C# and .NET Programming


Window Based Applications

SelectedItems Represents a collection of all the selected items.


Read Only.

SetSelected Selects or clears the selection for a particular


zero-based item.

Events

MeasureItem Occurs when an owner-drawn ListBox is created and the sizes of the list
items are determined.

MouseClick Occurs when the user clicks the ListBox control with the mouse pointer.

SelectedIndexChanged Occurs when the SelectedIndex property has changed. Fires for both
single, multiple and extended selections. If using extended selection this
fires after they are all selected.

SelectedValueChanged Occurs when the SelectedValue property changes. (Inherited from


ListControl.)

ValueMemberChanged Occurs when the ValueMember property changes. (Inherited from


ListControl.)

20.5.8 PictureBox

Allows to display a graphic or picture.


The Windows Forms PictureBox control is used to display images in bitmap, GIF, icon,
or JPEG formats.
Image property can be set to the Image which is to be shown and can be displayed,
either at design time or at run time. It can be programmatically changed as well, which
is particularly useful when single form is used to display different pieces of
information.
pictureBox1.Image = Image.FromFile("c:\\testImage.jpg");
The SizeMode property, which is set to values in the PictureBoxSizeMode enumeration,
controls the clipping and positioning of the image in the display area.
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;

20 - 48 C# and .NET Programming


Window Based Applications

There are five different PictureBoxSizeMode available to PictureBox control.


AutoSize - Sizes the picture box to the image.
CenterImage - Centers the image in the picture box.
Normal - Places the upper-left corner of the image at upper
left in the picture box
StretchImage - Allows to stretch the image in code
The PictureBox is not a selectable control, which means that it cannot receive input
focus. The following C# program shows how to load a picture from a file and display it
in streach mode.
Properties

BorderStyle Indicates the border style for the control.

ErrorImage Gets or sets the image to display when an error occurs during the image-
loading process or if the image load is canceled.

Image Gets or sets the image that is displayed by PictureBox.

ImageLocation Gets or sets the path or URL for the image to display in the PictureBox.

InitialImage Gets or sets the image displayed in the PictureBox control when the
main image is loading.

SizeMode Indicates how the image is displayed.

Text Overridden. Gets or sets the text of the PictureBox.

WaitOnLoad Gets or sets a value indicating whether an image is loaded


synchronously.

Methods

CancelAsync Cancels an asynchronous image load.

Dispose Overloaded. Releases all resources used by the PictureBox.

Load Overloaded. Displays an image in the PictureBox.

LoadAsync Overloaded. Loads the image asynchronously.

ToString Overridden. Returns a string that represents the current PictureBox


control.

20 - 49 C# and .NET Programming


Window Based Applications

Events

Leave Occurs when input focus leaves the PictureBox.

LoadCompleted Occurs when the asynchronous image-load operation is completed,


been canceled, or raised an exception.

LoadProgressChanged Occurs when the progress of an asynchronous image-loading operation


has changed.

SizeModeChanged Occurs when SizeMode changes.

Example
using System;
using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)


{
pictureBox1.Image = Image.FromFile("c:\\testImage.jpg");
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
}

}
}

20.5.9 ImageList (img)

Imaging Box is an advanced image control for Windows Form applications, like the
Picture Box control but with more features that allows to show images with advanced
zoom options like stretch with aspect ratio, custom zoom ratio and zoom point.

20 - 50 C# and .NET Programming


Window Based Applications

Properties

ColorDepth Gets the color depth of the image list.

Images Gets the ImageList.ImageCollection for this image list.

ImageSize Gets or sets the size of the images in the image list.

ImageStream Gets the ImageListStreamer associated with this image list.

Tag Gets or sets an object that contains additional data about the ImageList.

TransparentColor Gets or sets the color to treat as transparent.

Methods

Draw Overloaded. Draws the indicated image.

ToString Overridden. Returns a string that represents the current ImageList.

Difference between Image box and Picture Box control.

Image Box Picture Box

1) It does not act as container control 1) It acts as container control


2) Not use of memory to store the picture 2) Use of memory to store the picture
3) Editing of picture is not possible in 3) Editing of picture is possible in
image box picture box
4) Not having auto size property 4) Having auto size property
5) Having stretch property 5) Not having stretch property
6) An image box uses the form's device 6) A picture box has a device context.
context.

20.5.10 MenuStrip

1. The menus and toolbars in .NET 2.0 are known as "strip" controls.
2. A menu is located on the menu bar and contains a list of related commands.
3. The MainMenu control allows to add menus to the programs. Special effects can be added
to menus such as access keys, check marks and keyboard shortcuts.
4. General Menu convention
Every menu title and menu command should have an initial capital letter
Caption should be short, specific and easy to understand the purpose of menu.

20 - 51 C# and .NET Programming


Window Based Applications

Assign each menu item an access key and use its first letter for shortcut key.
If required place an ellipsis after a menu command that displays a dialog box
5. A Menu on a Windows Form is created with a MainMenu object, which is a collection of
MenuItem objects. MainMenu is the container for the Menu structure of the form and
menus are made of MenuItem objects that represent individual parts of a menu.
6. Menus can be added to Windows Forms at design time by adding the MainMenu
component and then appending menu items to it using the Menu Designer.
7. Following figure depicts the main parts of the menu

Separator

Fig. 20.5.2 Parts of menu

8. Events on menu item


The main purpose of a menu item is to invoke action when clicked on it. Therefore, a
click event handler should be added to on the menu item and the code is written for the
same.

20 - 52 C# and .NET Programming


Window Based Applications

9. Creating menus
Examples
Menu example

1. Create a new Windows form project.

Fig. 20.5.3 Form menu design view

Fig. 20.5.4 Form menu files

20 - 53 C# and .NET Programming


Window Based Applications

2. Add MenuStrip from the toolbox to the form.

Fig. 20.5.5 Menu strip toolbox

20 - 54 C# and .NET Programming


Window Based Applications

3. The menu strip is inserted on the form. Appropriately name the menu . The form looks as
follows.

Fig. 20.5.6 Form design

4. Add the menuitems by typing the menu options in the menu strip. Menuitems can be
directly created by typing a value into the "Type Here" box on the menubar part of the
form.

Fig. 20.5.7 Form design

20 - 55 C# and .NET Programming


Window Based Applications

5. To add seperator bar , right click on menu then go to insert->Seperator.

Fig. 20.5.8 Adding separator in menu

20 - 56 C# and .NET Programming


Window Based Applications

6. After adding the separator the menu looks as follows. Here, 2 separators are added.

Fig. 20.5.9 Form menu view

7. Also note that, To add an access key, insert an ampersand character (&).
3 menu separator can be inserted by typing a dash and pressing Enter.
8. After creating the Menu on the form , double click on each menu item and write the action
part that is code behind the menu, as per application requirements. In this example,
message boxes are added on respective menu item click event. Double click the menu
items to create event procedures for them. Following is the code added for this
example.
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;

20 - 57 C# and .NET Programming


Window Based Applications

namespace WindowsFormsApplicationMenus
{
public partial class FrmMenu : Form
{
public FrmMenu()
{
InitializeComponent();
}

private void lineToolStripMenuItem_Click(object sender, EventArgs e)


{
MessageBox.Show("Insert Line Menu is selected");
}

private void circleToolStripMenuItem_Click(object sender, EventArgs e)


{
MessageBox.Show("Insert Circle Menu is selected");
}

private void cubeToolStripMenuItem_Click(object sender, EventArgs e)


{
MessageBox.Show("Insert Cube Menu is selected");
}

}
}
Output

Fig. 20.5.10 Form menu view

20 - 58 C# and .NET Programming


Window Based Applications

Fig. 20.5.11 Menu click output

20.6 C# MDI Form


20.6.1 The MDI and SDI Concept
Concept

1. The Multiple-Document Interface (MDI) is a specification that defines a user interface for
applications that enable the user to work with more than one document at the same time
under one parent form (window).
Explanation

2. A C# Multiple Document Interface (MDI) programs can display multiple child windows
inside them. This is in contrast to Single Document Interface (SDI) applications, which
can manipulate only one document at a time.
3. A Multiple Document Interface (MDI) programs can display multiple child windows
inside them. This is in contrast to single document interface (SDI) applications, which can
manipulate only one document at a time.

20 - 59 C# and .NET Programming


Window Based Applications

4. Visual Studio Environment is an example of Multiple Document Interface (MDI) whereas


notepad is an example of an SDI application. MDI applications often have a Window
menu item with submenus for switching between windows or documents.
5. Any windows can be made MDI parent, by setting the IsMdiContainer property to True.

6. The following C# program shows a MDI form with two child forms. Create a new C#
project, to get a default form Form1. Then add two more forms in the project (Form2,
Form3). Create a Menu on the form and call these two forms on menu click event. If one
want the MDI parent to auto-size the child form one can code as follows

Fig. 20.6.1 MDI form

20 - 60 C# and .NET Programming


Window Based Applications

20.6.2 Modal and Modeless Forms


20.6.2.1 Modal Form
Concept

1. A Modal form is one where one has to deal with it before continuing the further
processing in the application.
Explanation

2. Example
1. Create a C# windows form type application called “ModalModeless” in VS.NET.
2. Add a button in the main form (Form1) with a name of “btnShowLogin” and a text
property of “Show Login Dialog”. By right clicking on the project, add another form
to the project (Add->Add New Item..).
3. Name this form “LoginDlg.cs”. Put two labels, two text boxes and two buttons in
this Login dialog, as shown below.

Fig. 20.6.2 Modal form

4. Name the textboxes as “txtUsername” and “txtPassword” respectively. Set the


password character to * for the password text box.
5. Name the first button as “btnLogin”, the second button as “btnCancel”.
6. Since the parent form will need to know the user name and the password entered in
the login dialog, there is need to add two properties in the LoginDlg class
(LoginDlg.cs file) as shown below. It should be noted that the get method is just for
the properties as the parent form will be only reading the data entered by the user.
7. Loging Dlg. class file
public class LoginDlg : System.Windows.Forms.Form
{
private string usrname;
public string Usrname
{
get { return usrname; }

20 - 61 C# and .NET Programming


Window Based Applications

}
private string pword;
public string PWord
{
get { return pword; }
}
private System.Windows.Forms.TextBox txtUsername;
….
8. The code for the “Login” and “Cancel” button handlers in the LoginDlg
private void btnLogin_Click(object sender, System.EventArgs e)
{
this.usrname = txtUsername.Text;
this.pword = txtPawword.text;
this.DialogResult = DialogResult.OK; // also closes the dialog
}

private void btnCancel_Click(object sender, System.EventArgs e)


{
this.DialogResult = DialogResult.Cancel; // also closes the dialog
}
9. For Form1 - following handler for the “Show Login Dialog” button is added
private void btnShowLogin_Click(object sender, System.EventArgs e)
{
LoginDlg ldg = new LoginDlg();
if (ldg.ShowDialog() == DialogResult.OK)
{
string unm = ldg.Usrname;
string pw = ldg.PWord;
if ((unm == "India") && (pw == "1234"))
MessageBox.Show("Correct login");
else
MessageBox.Show("Incorrect login");
}

20.6.2.2 Modeless Forms


Concept

1. Modeless forms coexist with the parent application. The call to display a modeless form is
Show( ). When the user makes a change to the modeless form by some action say,
clicking a button, then an event handler in the parent form is invoked. This can be easily
handled by passing a delegate (that points to a member function in the parent form) to the
constructor in the child form. The constructor’s code can then set it for a local button.

20 - 62 C# and .NET Programming


Window Based Applications

Explanation

2. Example
1. Add form in the project (Name this form “MsgDlg.cs”).
2. Design the user interface in this dialog as shown below.

Fig. 20.6.3

3. Name the textbox as “txtMsg”. The two buttons are named as “btnSendMsg” and
btnClose”.
4. Add a property called msg in the MsgDlg.
public string Msg
{
get { return txtMsg.Text; }
}

5. Add another constructor to the MsgDlg.cs class.


public MsgDlg(System.EventHandler del)
{
InitializeComponent();
this.btnSendMsg.Click += del;
// set the delegate to a func. in parent form
}
6. Add following code for the “Close” button handler in the MsgDlg class.
private void btnClose_Click(object sender, System.EventArgs e)
{
this.Close();
}
The above function sets the click event handler for the “send Message” button to a
function in the parent form. What happens here is , whenever the user clicks on this
button, it can invoke a function in the parent form which can then read the Msg property
to find out what message is being sent by the child form.

20 - 63 C# and .NET Programming


Window Based Applications

7. Now add the “Send Message” button handler in the parent form by adding
following code in the Form1 class.
private void GetChildMessage(object sender, System.EventArgs e)
{
MessageBox.Show(mdlg.Msg);
}
8. Add the declaration in the beginning of the Form1 class.
private MsgDlg mdlg; // child modeless dialog
9. Add a button to the Form1 class. Name the button “btnShowMsgDlg”. Give it a text
property of “Show Message Dialog”. Type the following code in the “Show Message
Dialog” handler.
private void btnShowMsgDlg_Click(object sender, System.EventArgs e)
{
System.EventHandler pDel = new system.EventHandler
(this.GetChildMessage);
// delegate to GetChildMessage
mdlg = new MsgDlg(pDel);
mdlg.Show();
}

Fig. 20.6.4 Dialog box window

20 - 64 C# and .NET Programming


Window Based Applications

20.6.2.3 Passing Parent Form to the Child Form

Another way to design the modeless form is to pass the entire parent form (Form1 in above
example) to the constructor in the child form (MsgDlg).
The constructor of the child form will then set the delegate to its “Send Message” button to
one of the functions in the parent form by using the following code.
public MsgDlg(Form1 fm)
{
InitializeComponent();
this.btnSendMsg.Click +=
new System.EventHandler(fm.GetChildMessage);
// set the delegate to a func. in parent form
}
To accomplish the above, one need to change the private attribute of “GetChildMessage”
function in Form1 to public.
The code in the parent form that invokes the child form in a modeless manner (“Show
Message Dialog” handler) will now look as :
private void btnShowMsgDlg_Click(object sender, System.EventArgs e)
{
mdlg = new MsgDlg(this); // sending parent form to child
mdlg.Show();
}

20.6.2.4 MessageBox as a Modal Dialog and Closing Event

1. In addition to displaying messages to the user in a modal manner, a MessageBox is used


to collect small piece of information from the user.
2. It is capable of displaying several buttons to the user defined by the MessageBoxButtons
enumeration along with the different kinds of icons. These icons are defined by the
MessageBoxIcon enumeration. (Warning message box)
3. When the main form of an application is closed, it can be asked to the user if he really like
to close the application.
4. The solution is to write the Form_Closing event handler and ask the user via a
MessageBox. If the user cancels the closing of the the main application, then set the
Cancel property of the form to true to avoid termination of the application.
Example : Add a closing event handler to the Form1 in the above application. Write the
following code in it.
private void Form1_Closing(object sender,System.ComponentModel.CancelEventArgs e)
{
DialogResult d1 = MessageBox.Show("OK to quit",

20 - 65 C# and .NET Programming


Window Based Applications

Terminate?",MessageBoxButtons.OKCancel,MessageBoxIcon.Question);
if (d1 == DialogResult.Cancel)
e.Cancel = true;
}

Now, at the time when application is being closed , above confirmation dialog is popped
up. If it is cancelled, the program will not terminate.
20.7 Dialog Box
Concept
1. Dialogs are created as forms in .NET.
Explanation
2. Once the user interface of the added dialog box form has been designed properly, one can
display this form, from a parent form in a “modal” or “modeless” manner.
3. If a form is displayed in a modal manner, the parent program cannot continue beyond the
statement that displays the modal form unless the modal form is terminated.
4. The modal form can communicate the actual reason for termination to the parent form
through the DialogResult property which can take on one of the values from the
DialogResult enumeration.
5. Any additional information that needs to be communicated to the parent form of the
modal form can be done by setting the data members or properties of the modal form prior
to its termination. The parent form can then examine these data members or properties
after the modal dialog has been terminated.
6. Dialogue boxes in C# can be added by using an inbuilt object. In the Toolbox, there is a
category called Dialogs which looks as follows,

Fig. 20.7.1 Dialog box menu

20 - 66 C# and .NET Programming


Window Based Applications

7. Creating OpenFileDialog dialogbox.


Double click OpenFileDialog in toolbox which would add a menuStrip1 object to the
from.

Fig. 20.7.2 Open file dialog design view

Nothing else appears on the form, because the Dialog controls are hidden from view.
The dialogbox can be renamed through Properties Window by Changing the Name of
openFlDlg. The control on the form would change also.

Fig. 20.7.3 Open file dialog design view

20 - 67 C# and .NET Programming


Window Based Applications

Open File Dialog box does not actually open the file but it helps to open the file by
getting its name, and the same is true for the other Dialog controls. Separate code is
written to open the files.
8. Modal and Modeless dialog box
1. Modal dialog box is the dialog box in which user response is required before
continuing with the program. The Paragraph dialog box of WordPad is a good
example of it when it is displaying, the user cannot use any other part of WordPad
unless he or she closes this object first.
2. Modeless dialog box is the dialog box in which the screen remain stable and available
to all the user for use at any time but it doesn’t stop their and allow other user work
to be carried out without any interference. For example The Find dialog box or Find
and Replace dialog box of MSWord.
3. The major difference between Modal and modeless dialog box :
i) Modal dialog box captures the message loop and doesn’t move on to other
objects until the current object is closed but modeless dialog box doesn’t
capture it.
ii) Modal dialog box doesn’t allow its parents window to be accessed until all
other windows are closed but it is allowed in modeless dialog box.
Example of Modal dialog box is Save and Save As in MS word until they are
opened one can not do anything until the window is closed whereas Find and
Replace can simultaneously be executed together.

20.8 Event Handling Basics

Concept
1. Events
Actions and events serve an important part in every GUI-based application. These are the
actions that instruct the program what to do when something happens.
For example, when a user performs a mouse click or a keyboard operation, some kind of
event is taking place. If the user does not perform that operation, nothing will happen.
2. Delegate

A delegate is a C# language element that allows to refer a method. A delegate is basically a


function pointer.

20 - 68 C# and .NET Programming


Window Based Applications

Explanation
3. C# Event handling

1. An event is a mechanism via which a class can notify its clients when something happens.
2. A C# event is a class member that is activated whenever the event it was designed
for is fired. When the event is fired respective already registered method will be
invoked.
3. C# event model
The C# event model is based on a "publish-subscribe" pattern in which a class
(publisher) triggers an event, while another class (subscriber) receives that event. An
event handler is the subscriber that contains the code to handle specific events.
For example, an event handler can be used to handle an event that occurs during the
click of a command button in the UI.

Fig. 20.8.1 C# Event model

4. Event Source
It is responsible to inform other objects that something has changed.
5. Event handler is a routine/method which is invoked upon the firing of event.
Event Handlers in the .NET Framework return void and take two parameters.

20 - 69 C# and .NET Programming


Window Based Applications

The first paramter is the source of the event; that is the publishing object.
The second parameter is an object derived from EventArgs.
Events are properties of the class publishing the event.
The keyword event controls how the event property is accessed by the subscribing
classes.
6. Handling an event in C# involves two steps :
Step1 : Implement the event handler method
The event handler method like, btn_Click. It has the required signature (two parameters :
sender of type object and e of type EventArgs), and, as required, it returns void.
The code in the body of the event handler method performs whatever programming task is
required to respond to the event.
Step 2 : Assign the event handler method to the event
This is done by instantiating an EventHandler delegate, which encapsulates the btn_Click
method, then using the += operator to add that delegate to the button's Click event.
btn.Click += new System.EventHandler(btn_Click);
7. Declaring Events :
First declare one delegate and then events as
//delegate
public delegate void TimeToSleep();
//Associate event
private event TimeToSleep PowerOff;
Handle/Subscribe the events :
Let’s assume my PG class has one method “plssleep” which fires when the power goes off
as
myPG obj = new myPG();
PowerOff = new TimeToSleep(obj.plsSleep);

public class myPG


{
public void plsSleep()
{
//code
}
}

20 - 70 C# and .NET Programming


Window Based Applications

8. Events and delegates work hand-in-hand to provide a program’s functionality.

First a class is created that declares an event. Any class, including that same class which
had the event declared in it, can register one of its methods for the event. This is done through
a delegate, which specifies the signature of the method that is registered for the event. The
delegate may be one of the pre-defined .NET delegates or it can be programmer declared
delegate. The delegate is assigned to the event, which effectively registers the method that will
be called when the event fires.
9. Creating Event handlers in C#

1. An event handler in C# is a delegate with a special signature, given below.


public delegate void MyEventHandler(object sender, MyEventArgs e);
1. The first parameter (sender) in the above declaration specifies the object that fired the
event. The second parameter (e) of the above declaration holds data that can be used
in the event handler.
2. The class MyEventArgs is derived from the class EventArgs. EventArgs is the base
class of more specialized classes, like MouseEventArgs, ListChangedEventArgs, etc.
3. For GUI event, one can use objects of these specialized EventArgs classes without
creating own specialized EventArgs classes. However, for non GUI event, one needs
to create own specialized EventArgs class to hold data that is needed to pass to the
delegate object.
4. Specialized EventArgs class is created by deriving from EventArgs class.
public class MyEventArgs EventArgs{
public string m_myEventArgumentdata;
}
5. In case of event handler, the delegate object is referenced using the key word event as
follows ,
public event MyEventHandler MyEvent;
10. Event Arguments
Concept

Conventionally, event handlers in the .NET Framework, in C# need to return void, and
take two parameters. The first parameter is the "source" of the event : the publishing
object. The second parameter is an object derived from EventArgs.

20 - 71 C# and .NET Programming


Window Based Applications

Explanation

EventArgs is the base class for all event data. Other than its constructor, the EventArgs
class inherits all its methods only from Object, though it does add a public static field
empty, which represents an event with no state (to allow for the efficient use of events
with no state).
In case an event has no data to pass, then the passed event argument will be of type
EventArgs, which has no public properties, being essentially a placeholder. If there is
data to pass, say the location of a mouseclick or which key was pressed, then the event
argument will be of a type derived from EventArgs, and it will have properties for the
data being passed.
The general signature for an event handler is as follows,
private void Handler (object sender, EventArgs e)

Private Sub Handler (ByVal sender As Object, ByVal e As EventArgs)


Some events use the base class EventArgs, but EventArgs objects contain no useful
additional information about the event. The controls that do require their event handlers
to know additional information about the event will pass in an object of a type derived
from EventArgs.
For example, the TreeView AfterCollapse event handler receives an argument of type
TreeViewEventArgs, derived from EventArgs. TreeViewEventArgs has the properties
Action and Node, each of which has values specific to the actual event.
11. Mouse Events
1. Common Control Events

Event
Event Description
argument

Click EventArgs Raised when a control is clicked by the mouse.

Raised when a new control is added to


ControlAdded ControlEventArgs
Control.ControlCollection.

Raised when a control is removed from


ControlRemoved ControlEventArgs
Control.ControlCollection.

Raised if the Dock property— i.e., which edge of the parent


DockChanged EventArgs container the control is docked to—is changed, either by user
interaction or program control.

20 - 72 C# and .NET Programming


Window Based Applications

Raised when a control is double-clicked. If a control has both


DoubleClick EventArgs a Click and DoubleClick event handler, the DoubleClick will
be preempted by the Click event.

Raised when a control receives focus. Suppressed for Form


Enter EventArgs objects. For nested controls, cascades up and down the
container hierarchy.

Raised when any change occurs that affects the layout of the
Layout LayoutEventArgs control (e.g., the control is resized or child controls are added
or removed).
Leave EventArgs Raised when focus leaves the control.
Move EventArgs Raised when a control is moved.
Paint PaintEventArgs Raised when a control is redrawn.
ParentChanged EventArgs Raised when the parent container of a control changes.

Raised when a control is resized. Generally preferable to use


Resize EventArgs
the Layout event.

Raised when the Size property is changed, either by user


SizeChanged EventArgs interaction or programmatic control. Generally preferable to
use the Layout event.

Raised when the Text property changes, either by user


TextChanged EventArgs
interaction or programmatic control.

Raised when a control is validating. If CancelEventArgs


Cancel property set true, then all subsequent focus events
Validating CancelEventArgs
are suppressed.
Suppressed if Control.CausesValidation property set false.

Raised when a control completes validation.


Suppressed if the CancelEventArgs.Cancel property passed to
Validated EventArgs
the Validating event is set true.
Suppressed if Control.CausesValidation property set false.

20 - 73 C# and .NET Programming


Window Based Applications

2. Control Drag-and-Drop events


Event Event argument Description

DragDrop DragEventArgs Raised when a drag-and-drop operation is completed.

Raised when an object is dragged onto the control. At the


DragEnter DragEventArgs time this event is raised, the drag operation is still in
progress (i.e., the user hasn't yet let the mouse button go up).

DragLeave DragEventArgs Raised when an object is dragged off of the control.


DragOver DragEventArgs Raised when an object is dragged over the control.

Raised during a drag operation to allow modification to the


GiveFeedback GiveFeedbackEventArgs
mouse pointer.
3. Control Mouse events
Event Event argument Description
MouseEnter EventArgs Raised when mouse pointer enters control.
MouseMove MouseEventArgs Raised when mouse pointer moved over control.
MouseHover EventArgs Raised when mouse hovers over control.
Raised when mouse button pressed while mouse pointer is
MouseDown MouseEventArgs
over control.
MouseWheel MouseEventArgs Raised when mouse wheel moved while control has focus.
Raised when mouse button released while mouse pointer is
MouseUp MouseEventArgs
over control.
MouseLeave EventArgs Raised when mouse pointer leaves control.
12. Keyboard Events
Keyboard events provide access to implementation of keystrokes generated events.
1. Key Events for all controls
Event Event data Description

Raised when a key is pressed. The KeyDown event occurs prior to


KeyDown KeyEventArgs
the KeyPress event.

Raised when a character generating key is pressed. The KeyPress


KeyPress KeyPressEventArgs event occurs after the KeyDown event and before the KeyUp
event.
KeyUp KeyEventArgs Raised when a key is released.

20 - 74 C# and .NET Programming


Window Based Applications

The KeyDown and KeyPress events are not same as they are fired at different points in
the keyboard event stream and contain different information in the EventArgs object.
The KeyEventArgs event data associated with the KeyDown and KeyUp events
provides low-level information about the keystroke.
This information is used to determine, if an upper - or lowercase character was pressed.
It also tells if any modifier keys (Alt, Ctrl, or Shift) were pressed along with it in
combination.
2. KeyEventArgs properties (KeyDown and KeyUp)

Data
Property Description
type

Read-only value indicating if the Alt key was pressed. true if pressed,
Alt Boolean
false otherwise.

Read-only value indicating if the Ctrl key was pressed. true if pressed,
Control Boolean
false otherwise.

Read-only value indicating if the Shift key was pressed. true if pressed,
Shift Boolean
false otherwise.

Read-only flags indicating the combination of modifier keys (Alt, Ctrl,


Modifiers Keys Shift) pressed. Modifier keys can be combined using the bitwise OR
operator.
Handled Boolean Value indicating if the event was handled. false until set otherwise.

Read-only value containing the key code for the key pressed. Typical values
KeyCode Keys
include the A key, Alt, and BACK (backspace).

Read-only value containing the key code for the key pressed, combined with
KeyData Keys
modifier flags to indicate combination of modifier keys (Alt, Ctrl, Shift).

KeyValue integer Key code property expressed as a read-only integer.

3. Unicode and ASCII Characters

Each character in the American Standards Committee for Information Interchange


(ASCII) character set is represented by a single byte (8 bits) of data, representing 256
characters. The first 128 characters (represented by 7 bits) are standardized and usually
referred to as low-order ASCII characters. The upper 128 characters are not
standardized, although many well established character sets use all 256 characters.

20 - 75 C# and .NET Programming


Window Based Applications

Unicode characters are a superset of the ASCII character set. They are represented by
two bytes, which allows a maximum of 65,536 characters. The Unicode technology was
introduced to allow easier representation of languages other than English, especially
Asian languages such as Chinese and Japanese, which do not have limited alphabets.
Unicode also allows for character sets containing many more characters than an ASCII
character set, such as special symbols and stylings of characters.
4. KeyPressEventArgs properties (KeyPress)

Property Description

Boolean value indicating if the event was handled. false until set otherwise. When
Handled
true, the keystroke is not displayed.
KeyChar Read-only value of type char containing the composed ASCII character.

Example 1
//illustration of Button events
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

public class EventsForm Form{


private Button m_nameButton;
private Button m_okButton;
private Label m_nameLabel;
private Container m_components = null;

public EventsForm(){
initializeComponents();
}
private void initializeComponents(){
m_nameLabel=new Label();
m_nameButton = new Button();
m_okButton = new Button();

SuspendLayout();

m_nameLabel.Location=new Point(16,16);
m_nameLabel.Text="Click User NAME button";
m_nameLabel.Size=new Size(300,23);

20 - 76 C# and .NET Programming


Window Based Applications

m_nameButton.Location=new Point(16,120);
m_nameButton.Size=new Size(176, 23);
m_nameButton.Text="User NAME";
//Create the delegate, add in the method, and assign
// the delegate to the Click event of the button
m_nameButton.Click += new System.EventHandler(NameButtonClicked);

m_okButton.Location=new Point(16,152);
m_okButton.Size=new Size(176,23);
m_okButton.Text="OK";
//Create the delegate, add in the method, and assign
//the delegate to the Click event of the button
m_okButton.Click += new System.EventHandler(okButtonClicked);

this.ClientSize = new Size(292, 271);


this.Controls.AddRange(new Control[] {m_nameLabel,
m_nameButton,
m_okButton});
this.ResumeLayout(false);
}
//Define the methods having signature exactly matching with the //declaration of the
delegate
private void NameButtonClicked(object sender, EventArgs e){
m_nameLabel.Text=
"I am Ravi, please click Ok button to stop";
}
private void okButtonClicked(object sender,EventArgs e){
m_nameLabel.Text="Click NAME button";
}
public static void Main(){
Application.Run(new MyForm());
}
}
Example 2
//illustration of button event
using System;
using System.Drawing;
using System.Windows.Forms;

namespace ProgrammingControlEvents
{
public class HelloWorld : System.Windows.Forms.Form
{

private Button btn;

20 - 77 C# and .NET Programming


Window Based Applications

public HelloWorld( )
{
Text = "Hello World";

btn = new Button( );


btn.Location = new Point(50,50);
btn.Text = "Goodbye";
btn.Click += new System.EventHandler(btn_Click);

Controls.Add(btn);
}

static void Main( )


{
Application.Run(new HelloWorld( ));
}

private void btn_Click(object sender, EventArgs e)


{
Application.Exit( );
}
}
}
Two Marks Questions with Answers

Q.1 What is a Windows Form ?


Ans. : A Windows Forms is an API which exists in Microsoft .NET framework to develop
rich client applications. This API lies within the Microsoft .NET stack and gives interfaces to
extend the API abstract classes or implement the interfaces to develop the rich client
applications. Windows Forms is a form of managed libraries in the .NET framework. It
provides graphics API and provides more security within the client applications.
Q.2 What are the different types of properties in .NET ?
Ans. : The below are the two properties in the .NET to which performs as accessors to read
or write the properties of the Windows Forms or any kind of class or object. The two
property accessors are GET and SET :
1. GET : The GET property accessor is required to return the property value based on
the different access levels as defined. The read-only property has to GET accessor
but not a SET.
2. SET : The SET property accessor is required to assign a value, mostly a new value
on the basis of the access level defined. Write only property have SET accessor but
not a GET.

20 - 78 C# and .NET Programming


Window Based Applications

Q.3 What are the different functionalities and applications of the Windows Form ?
Ans. : The different functionalities those can be performed using Windows Form are as
below :
To build rich client applications.
To develop rich and interactive user interfaces.
To create event handlers.
To develop different kinds of panels within the window.
To create Graphical User Interfaces or Graphics forms.
To display and manage the data submitted by the user.
To perform data binding operations.
Q.4 What are the different data types those can be used in Windows Forms ?
Ans. : The different data types those can be used depends on the programming language
and it is typically based on C# programming language which is as below :
1. Value Types : Simple types, Enum types, Struct types, Nullable Value types.
2. Reference Types : Class types, Interface types, Array types, Delegate types.
Q.5 How a default value can be displayed in a text box of Windows Form ?
Ans. : The default value of a text field in the text box can be set by using the
DefaultResponse parameter of the InputBox() method. DefaultResponse is the argument of
the InputBox() function.
Q.6 How can you display a default value in the text box of an input box ?
Ans. : You can display a default value in the text box of an input box by using the
DefaultResponse argument of the InputBox() function.
Q.7 How can we auto size a button to fit its text ?
Ans. : The Button control has the AutoSize property, which can be set to true or false. If we
set the value of the AutoSize property to true, then the button control automatically alters
its size according to the content displayed on it.
Q.8 What is a message box ? AU : Dec.-17

Ans. : MessageBox is a class in C# and Show is a method that displays a message in a


small window in the center of the Form. MessageBox is used to provide confirmations of a
task being done or to provide warnings before a task is done. Create a Windows Forms app
in Visual Studio and add a button on it.

20 - 79 C# and .NET Programming


Window Based Applications

Q.9 Compare modal and modeless dialog. AU : Dec.-18

Ans. :
1. Modal dialog boxes, which require the user to respond before continuing the
program. Modeless dialog boxes, which stay on the screen and are available for use
at any time but permit other user activities
2. A modal dialog box doesn’t allow the user to access the parent window while the
dialog is open - it must be dealt with and closed before continuing. A modeless
dialog can be open in the background.
3. When a modal dialog is open one cannot interact with anything else than this modal
dialog inside the program, as long as the modal dialog is open. Most dialogs are
modal, for example the File-Save As dialogs are modal. On the other hand a
modeless dialog behaves just like a normal window, one can do anything wanted
while it is open. The spell checker dialog in Microsoft Word is an example of such a
dialog
4. Modal dialog box captures the message loop. Whereas modeless does not.
5. Model dialog does not allow its parent window unless it is closed. Whereas modeless
it allows.
6. Modal Dialog box occupies the Stack Area that the reason it can't give the control to
its parent. Modeless Dialog box occupies the Heap Area it gives the control to its
parent.
7. Modal dialog does not switch the control of dialog box outside the window. Modeless
dialog can perform actions outside dialog box of the window.
8. Model dialog box is an static for the model box control application and the modeless
dialog box is an dynamic, so anything can be done in modeless dialog box.
Q.10 What are modeless dialog boxes ? AU : Dec.-19

Ans. : Modeless dialog box is the dialog box in which the screen remain stable and
available to all the user for use at any time but it doesn’t stop there and allow other user
work to be carried out without any interference. A modeless dialog allows to use the rest of
the application while it is open. It can be hidden by other application windows. modeless
dialog boxes are those found in many word processors and text editors for finding text. For
example The Find dialog box of WordPad. As one search for text, the dialog box remains
open and one can move freely between the dialog box and the document it is searching.

20 - 80 C# and .NET Programming


Window Based Applications

Long Answered Questions

Q.1 What are user interface elements ? (Refer section 20.4)


Q.2 Explain control class hierarchy in C#. (Refer section 20.4)
Q.3 What is MDI form ? (Refer section 20.6)
Q.4 Explain dialog box in general and any 1 dialog box in detail. (Refer section 20.7)
Q.5 Explain FileOpenDialogBox. (Refer section 20.7)
Q.6 Create your own Windows form with events and controls for a library
management system. (Refer section 20.5) AU : Dec.-17, Marks 16
Q.7 Define attributes and show its built in types. (Refer section 20.5)
AU : Dec.-17, Marks 16
Q.8 Differentiate between model and modeless dialog box.
(Refer section 20.6) AU : May-18, Marks 5
Q.9 Create a window form with events and controls using an example.
AU : May-18, Marks 8; May-19, Marks 15

Ans. :
/* Program to create Windows form with controls and event.
In this program a button is created and its click event is handled.
Button control represents a Windows button control. It can be clicked by using the
mouse, Enter key, or Spacebar if the button has focus. */
Program.cs
using System;
using System.Windows.Forms;
using System.Drawing;

namespace QuitButton
{
class MyForm : Form
{
private FlowLayoutPanel flowPanel;

public MyForm()
{
InitComponents();
}

private void InitComponents()


{
Text = "Quit button";
ClientSize = new Size(800, 450);

flowPanel = new FlowLayoutPanel();

20 - 81 C# and .NET Programming


Window Based Applications

flowPanel.Dock = DockStyle.Fill;
flowPanel.BorderStyle = BorderStyle.FixedSingle;

var button = new Button();


button.Margin = new Padding(10, 10, 0, 0);

button.Text = "Quit";
button.AutoSize = true;
button.Click += new EventHandler(OnClick);

flowPanel.Controls.Add(button);
Controls.Add(flowPanel);

CenterToScreen();
}

void OnClick(object sender, EventArgs e)


{
Close();
}

[STAThread]
static void Main()
{
Application.SetHighDpiMode(HighDpiMode.SystemAware);
Application.EnableVisualStyles();
Application.Run(new MyForm());
}
}
}
Q.10 Develop an C# windows forms application for students enrollment in Inter-
College Technical Contest, with appropriate from events, controls, menus and
dialog boxes. (Refer section 20.5) AU : May-18, Marks 15
Q.11 Write a C# Program to Perform Addition with MOUSEUP Event.
AU : Dec.-18, Marks 16

Ans. :
/*
* C# Program to Perform Addition with MOUSEUP Event
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;

20 - 82 C# and .NET Programming


Window Based Applications

using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplicationDemo
{
public partial class FormMouseUp : Form
{
public FormMouseUp()
{
InitializeComponent();
}

private void btn_MouseUp(object sender, MouseEventArgs e)


{
int add;
add = Convert.ToInt32(textBox1.Text) +Convert.ToInt32(textBox2.Text);
textBox3.Text = Convert.ToString(add);
MessageBox.Show("Addition is performed with MouseUp Event");
}
}
}
Q.12 Discuss in detail about the development of SDI and MDI application with
appropriate example. (Refer section 20.6) AU : Dec.-18, Marks 13
Q.13 Create a C# windows forms application for Super Market Stock Management
and Billing System, with appropriate form events, controls, menus and dialog
boxes. (Refer section 20.5) AU : Dec.-18, Marks 15
Q.14 Show how to create a Traditional-Style Main Menu in window forms.
(Refer section 20.5) AU : May-19, Marks 13
Q.15 Develop a library management system on the .NET framework. Allow the
application to issue and return books using database. (Refer section 20.5)
AU : Dec.-19, Marks 13
Q.16 Explain SDI and MDI applications with examples. (Refer section 20.6)
AU : Dec.-19, Marks 13

Window Based Applications ends …

20 - 83 C# and .NET Programming


Window Based Applications

20 - 84 C# and .NET Programming


C# and .NET Framework - Introduction

Syllabus : Core ASP.NET, ASP.NET Web Forms.

Section No. Topic Name Page No.


21.1 .NET 21 - 2

21.2 ASP .NET 21 - 2

21.3 Web Server 21 - 4

21.4 ASP .NET Architecture 21 - 6

21.5 Web Services 21 - 6

21.6 Web Forms 21 - 7

21.7 Building Web Application Project using C# and the ASP.NET 21 - 9

21.8 ASP.NET Page Syntax 21 - 12

21.9 Web Application Example 21 - 13

21.10 ASP.NET Life Cycle 21 - 14

21.11 ASP.NET Applications and Configuration 21 - 19

21.12 ASP.NET Controls 21 - 25

21.13 Web Forms - Data Binding 21 - 44

21.14 Event 21 - 47

21.15 State Management Techniques 21 - 52

Two Marks Questions with Answers 21 - 76

Long Answered Questions 21 - 83

21 - 1 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

21.1 .NET AU : May-19

1. DOT NET (.NET)


Concept

The DOT NET (.NET) created by Microsoft is a software development platform focused
on Rapid Application Development (RAD), platform independence and network transparency.
Explanation

DOT NET (.NET) has brought new functionalities and tools to the Application Programming
Interface (API). This makes development of applications for both Windows and the web as
well as components and services (web services) possible. .NET provides a new reflective,
object-oriented API. .NET is designed in such a way that many different high-level languages
can be compiled.
2. .NET Framework
Concept

.NET Framework also provides a collection of classes and tools to aid in development and
consumption. .NET Framework is built on these standards to promote interoperability with
non-Microsoft solutions.

21.2 ASP .NET

Concept

1. ASP.NET is a web application framework developed and marketed by Microsoft to allow


programmers to build dynamic web sites. It allows to use full featured programming
language such as C# or VB.NET to build web applications easily.
Explanation

2. ASP.NET supports server side coding further one step of Active Server Pages (ASP);
ASP.NET is a web application and development technology use to build dynamic
websites, web applications and web services. ASP.NET benefits over other script - based -
technologies by compiling the server side code to one or more DLL files on web server.
3. Web Applications are built using Web Forms. ASP.NET comes with built-in Web Forms
controls, which are responsible for generating the user interface. They mirror typical
HTML widgets like text boxes or buttons. If these in built controls do not fit one’s needs,
then one can create own user controls.

21 - 2 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

4. Web Forms are designed to make building web-based applications as easy as building
Visual Basic applications
5. ASP.NET pages have the extension .aspx and are normally written in C#.
6. The ASP.NET application codes can be written in any of the following languages :
C#
Visual Basic.NET
Jscript
J#
7. Benefits of Asp.NET
1. Asp.NET makes development simple and easy to maintain with event-driven and
server side programming model.
2. Asp.NET source code is executed on the server. The source code is complied first
time the page is requested. The server serves the complied version of the page for use
next time the page is requested.
3. Asp.NET provides validations controls.
4. The html produced by Asp.NET is sent back to the browser. The application code is
not sent back to the browser and is not stolen easily.
5. In Asp.NET business logic(in .cs class file) and presentation logic(in .aspx file) are
in separate files.

Fig. 21.2.1 ASP .NET in .NET framework

6. The 4th layer of the framework consists of the Windows application model and in
parallel, the Web application model. The Web application model- the ASP.NET-
includes Web Forms and Web Services. ASP.NET comes with built-in Web Forms
controls, which are responsible for generating the user interface. Web Services are
software solutions delivered via Internet to any device.

21 - 3 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

21.3 Web Server

Concept

A Web Server (like Internet Information Server/Apache/etc.) is a piece of software that


enables a website to be viewed using HTTP. One can abstract this concept by saying that a
web server is a piece of software that allows resources (web pages, images, etc.) to be
requested over the HTTP protocol.

Fig. 21.3.1 Web application running process

Explanation

When ASP.NET Web Application is run from visual studio IDE, VS Integrated
ASP.NET Engine is responsible to execute all kind of ASP.NET requests and
responses. The process name is "WebDev.WebServer.Exe" which actually handles all
request and response of an web application which is running from Visual Studio IDE.
“Web Server” come into picture when one needs to host the application on a centralized
location and wanted to access from many locations. Web server is responsible for
handling all the requests that are coming from clients, process them and provide the
responses.

21 - 4 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

IIS (Internet Information Server)


IIS (Internet Information Server) is one of the powerful web servers from Microsoft that is
used to host ASP.NET Web application. IIS has it's own ASP.NET Process Engine to handle
the ASP.NET request. So, when a request comes from client to server, IIS takes that
request and process it and send response back to clients.

Fig. 21.3.2 Client request processing in a web application

Request Processing :
1. Worker Process
2. Application Pool
Worker Process : Worker Process (w3wp.exe) runs the ASP.NET application in IIS.
This process is responsible to manage all the request and response that are coming from
client system. All the ASP.NET functionality runs under the scope of worker process.
When a request comes to the server from a client worker process is responsible to
generate the request and response. In a single word worker process is the heart of
ASP.NET Web Application which runs on IIS.
Application Pool : Application pool is the container of worker process. Application
pools is used to separate sets of IIS worker processes that share the same configuration.
Application pools enables a better security, reliability, and availability for any web
application. The worker process serves as the process boundary that separates each
application pool so that when one worker process or application is having an issue or
recycles, other applications or worker processes are not affected. This makes sure that a
particular web application doesn't not impact other web application as they they are
configured into different application pools.

21 - 5 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

Fig. 21.3.3 Application pool

21.4 ASP .NET Architecture


Explanation
ASP.NET works on three tier architecture. This architecture is extremely popular because
they increase application performance, scalability, flexibility, and code reuse. In three tier
architecture, applications are divided into three major areas of functionality :
- The data layer manages the data storage and retrieval.
- The business layer maintains business rules and logic
- The presentation layer manages the user interface and related presentation code.

Fig. 21.4.1 ASP .NET architecture

21.5 Web Services

Concept

Web services, an important evolution in Web-based technology are distributed, server-side


application components similar to common Web sites.

21 - 6 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

Explanation
Unlike Web-based applications, Web services components have no UI and are not targeted
for browsers such as Internet Explorer. Instead, Web services consist of reusable software
components designed to be consumed by other applications, such as traditional client
applications, Web-based applications or even other Web services.

21.6 Web Forms

ASP.NET is an ever-growing technology for Web application development using the .NET
Framework. It takes the best from both the sides, its predecessor, Active Server Pages (ASP)
as well as the rich services and features provided by the Common Language Runtime (CLR)
and then adds many new features of own. The result is a robust, scalable, and fast Web
development experience that will give a incredible flexibility so one can develop web-based
applications with ease.
Web Forms is one of the 3 programming models for creating ASP.NET web sites and web
applications. The other two programming models are Web Pages and MVC (Model, View,
Controller).
Web Forms is the oldest ASP.NET programming model, with event driven web pages
written as a combination of HTML, server controls, and server code.
Web Forms are compiled and executed on the server, as a response it generates the HTML
that displays the web pages. The response is in the form of elements integrated in a neat
structure with information that gives a Web applications their look and feel. This is known as
a User Interface (UI). Web Forms comes with hundreds of different web controls and web
components to build user-driven web sites with data access.
It is compatible to any browser to any language supported by .NET common language
runtime. It is flexible and allows us to create and add custom controls.
Working of Web Forms

The Web Forms page is composed of 2 components namely,


Aspx file (The UI) - Defines the visual aspect of the web page or UI.
The code-behind file ( The Business Logic) - Defines the behavior of the web page
and controls used in it.

The aspx file, usually contains HTML code along with some Web Form server side
controls that are pre-built and registered in Visual Studio that can drag and drop onto the page.
The HTML code and Web Form controls are stacked on the page in a neat structure that will
become the final visual output of the web page. Client side code like JavaScript and Ajax

21 - 7 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

controls/code can also be put into this file to help define client side behavior (like validations,
etc. that don’t require a round trip to the server).
The code-behind file, sometimes known as the class file, helps to define the behavior that
the page will have through server-side processed code based on page lifecycle events like
page_load, page_init and webform control events available on the web page that is added to
the visual aspx file, like an ASP Button Control Click event or a ASP Dropdown Control
Selected event.
When a user requests a page using the browser, these components are compiled on the
server using IIS and the .NET framework (which includes ASP.NET assemblies) installed on
that server. Then the server, along with any requested data from the database (if any) that is
needed, returns the generated html output of the page as a response that is rendered by the
browser along with the defined behavior it has on certain user interactions one can do on the
page. An interaction happens on the page when the code-behind file sends another request to
be processed, carries out the defined behavior, and renders the desired html output of the page.
For example, there is a web page that displays all the pin codes in our country and the option
is to be selected from a dropdown box that has list of cities, to filter those pin codes. The
behavior of the dropdown is set in such a way that it takes a trip back to the server to give it
the selected city that is chosen, filter the pin codes on that city, and then return the filtered pin
codes back to the page to display.

Fig. 21.6.1 Working of Web Forms over the web

21 - 8 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

For development of ASP.NET Web Forms following tools and software is required to be
installed,
IIS Services.
Visual Studio (required version).
SQL Server (required version).
Visual Studio is used to create ASP.NET Web Forms. Visual Studio is an IDE (Integrated
Development Environment) that allows to drag and drop server controls to the web forms. It
also allows to set properties, events and methods for the controls. To write business logic any
.NET language like, Visual Basic or Visual C# can be used.
The main purpose of Web Forms is to overcome the limitations of ASP and separate
view from the application logic.
ASP.NET provides various controls like server controls and HTML controls for the Web
Forms. Fig. 21.6.2 summarizes the environment of Web forms.

Fig. 21.6.2 Web Form Programming Environment

21.7 Building Web Application Project using C# and the ASP.NET

- Creating a New Web Project


1. Select File->New Project within the Visual Studio 2012 IDE. This brings up the New
Project dialog.
2. Click on the “Visual C#” node in the tree-view on the left hand side of the dialog box and
choose the "ASP.NET Web Application" icon :

21 - 9 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

Fig. 21.7.1 Web application project view

3. Set the location of the project to be created on disk.


4. Visual Studio creates and opens a new web project within the solution explorer. By
default it has a single page (Default.aspx), an AssemblyInfo.cs file, as well as a
web.config file.
5. All project file-meta-data is stored within a MSBuild based project file.

Fig. 21.7.2 Web application project view

6. Add webform (as per application requirement) following steps, Right click solution in
solution explorer and Add-> Item

21 - 10 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

Fig. 21.7.3 Web application options

- Open and Edit the Page as per requirement

Double clicking on the Default.aspx page in the solution explorer would open the file
which can be edited.
Same can be achieved using either the HTML source editor or the design-view.
- Building and Running the web Project

F5 function is used to build and run the project in debug mode.


By default, ASP.NET Web Application projects are configured to use the built-in VS web-
server when run. The default project templates will run on a random port as a root site (for
example: http://localhost:12345/):
-Ending the web project session
Debug session can be concluded by closing the browser window, or by choosing the
Debug->Stop Debugging (Shift-F5) menu item.
- File name extensions

1. Web applications written with ASP.NET will consist of many files with different file
name extensions. The most common are,
1. Native ASP.NET files by default have the extension .aspx (which is, an extension to
.asp) or .ascx. Web Services normally have the extension .asmx.
2. File names containing the business logic will depend on the language used. So, a C#
file would have the extension .aspx.cs.

21 - 11 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

3. ASP.NET application file Global.asax, in the ASP world formerly known as


Global.asa. But now there is also a code behind file Global.asax.vb, for example, if
the file contains Visual Basic.NET code. Global.asax is an optional file that resides in
the root directory of application, and it contains global logic for application.
2. All of these files are text files, and therefore human readable and writeable.

21.8 ASP.NET Page Syntax

1. Directives

Directives are used to specify optional settings used by the page compiler when processing
ASP.NET files. For each directive different attributes can be set.
2. Code Declaration Blocks

Code declaration blocks are lines of code enclosed in <script> tags. They contain the
runat=server attribute, which tells ASP.NET that these controls can be accessed on the server
and on the client. Optionally the language for the block can be specified.
3. Code Render Blocks

Render blocks contain inline code or inline expressions enclosed by the character
sequences. The language used inside those blocks could be specified through a directive.
4. HTML Control Syntax

Several standard HTML elements can be declared as HTML server controls. These controls
are programmatically accessible by using a unique ID. HTML server controls must reside
within a <form> section that also has the attribute runat=server.
5. Custom Control Syntax

There are two different kinds of custom controls.


First type of controls are the controls that ship with .NET, while the second type of
controls are the ones developer can develop and customize that can encapsulate common
programmatic functionality.
6. Data Binding Expression

Bindings are created between server controls and data sources. The data binding expression
is enclosed by the character sequences <%# and %>. The data-binding model provided by
ASP.NET is hierarchical which can create bindings between server control properties and
superior data sources.

21 - 12 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

7. Server-side Object Tags

If Object instance is to be created on the server then server-side object tags are used. When
the page is compiled, an instance of the specified object is created. To specify the object the
identifier attribute is used.
8. Server-side Include Directives

With server-side include directives the raw contents of a file can be included anywhere in
ASP.NET file by specifying the type of the path to filename with the pathtype attribute.
9. Server-side Comments

To prevent server code from executing, certain character sequences are used to comment it
out. Full blocks can also be commented rather than the single line.

21.9 Web Application Example

Simple ASP.NET Web Application

There are two parts to web application in ASP.NET, the markup and the C# portions.
Part I Markup Portion : WebFormTechnical_Info.aspx
<%@ Page Language="C#" AutoEventWireup="true"
odeBehind="WebFormTechnical_Info.aspx.cs"
nherits="WebApplicationtechnical.WebFormTechnical_Info” %>

<html>
<body background="Bookrack.bmp">

<TITLE>Most Read Books</TITLE>

<H1 align="center"><FONT color="white" size="7">Displaying <br> Most Read Books


</FONT></H1>

<P align="left"><FONT color="blue" size="5"><STRONG>

<U>Great Read Times <%WriteDate();%></U>

</STRONG></FONT></P>

<FONT size="5" color="yellow"><%WriteBooks();%></FONT>

</body>
</html>

21 - 13 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

Part II : C# part of a web forms ---- WebFormTechnical_Info.cs


using System;
using System.Web.UI;
using System.Web.UI.WebControls;

public class BooksPage:Page


{
protected void WriteDate()
{
Response.Write(DateTime.Now.ToString());
}

protected void WriteBooks()


{
Response.Write("<P>Meghdoot-Kalidas</P>");
Response.Write("<P>Mahabharat-Vyas</P>");
Response.Write("<P>Ramayana-Valmiki</P>");
}
}
Execution

Server side
A request for an .aspx file causes the ASP.NET runtime to parse the file for code that can
be compiled. It then generates a page class that instantiates and populates a tree of server
control instances. This page class represents the ASP.NET page.
ASP.NET code
The first time a page is requested, the code is compiled. Compiling code in .NET means
that a compiler in a first step emits Microsoft Intermediate Language (MSIL) and produces
metadata if source code is compiled to managed code.

21.10 ASP.NET Life Cycle

The ASP.NET life cycle can broadly be divided into two groups,
1. Application Life Cycle
2. Page Life Cycle
1. ASP.NET Application Life Cycle

The application life cycle has the following stages

21 - 14 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

Fig. 21.10.1 ASP .NET application life cycle

Stage 1 : Application Start

1. User makes a request for accessing application resource, a page. Browser sends this
request to the web server.
2. The life cycle of an ASP.NET application starts when a request is made by a user. This
request is to the Web server for the ASP.NET Application. This happens when the first
user normally goes to the home page for the application for the first time.
3. During this time, there is a method called Application_start which is executed by the web
server. Usually in this method, all global variables are set to their default values.
4. A unified pipeline receives the first request and the following events take place,
o An object of the class ApplicationManager is created for this task.
o An object of the class HostingEnvironment is created that provides information
regarding the resources.
o Now, top level items in the application are compiled.
Stage 2 : Object Creation

1. The next stage is the creation of the HttpContext , HttpRequest & HttpResponse by the
web server.
2. The HttpContext is just the container for the HttpRequest and HttpResponse objects.
3. The HttpRequest object contains information about the current request, including cookies
and browser information.
4. The HttpResponse object contains the response that is sent to the client.
Stage 3 : HttpApplication Creation

1. An instance of the HttpApplication object is created and assigned to the request.


2. This object is created by the web server. It is this object that is used to process each
subsequent request sent to the application. For example, consider 2 web applications. One
is a greeting shopt application, and the other is a songs website. For each application,
there would have 2 HttpApplication objects created. Any further requests to each website
would be processed by each HttpApplication respectively.

21 - 15 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

Stage 4 : Dispose

This event is called before the application instance is destroyed. During this time, one can
use this method to manually release any unmanaged resources.
Stage 5 : Application End

This is the final part of the application. In this part, the application is finally unloaded
from memory.
2. ASP.NET Page Life Cycle

Fig. 21.10.2 ASP.NET page life cycle

1. A requested page is loaded into the server memory, processed, and sent to the browser.
After sending it is unloaded from the memory. At each of these steps, methods and events
are available, which could be overridden according to the need of the application.
Required code can be written by overriding the default code.
2. The Page class creates a hierarchical tree of all the controls on the page. All the
components on the page, except the directives, are part of this control tree.
3. The page life cycle phases are,
Initialization
Instantiation of the controls on the page
Restoration and maintenance of the state
Execution of the event handler codes
Page rendering
4. Understanding the page cycle helps in writing specific codes, writing custom controls and
initializing them at right time, populate their properties with view-state data and run
control behavior code.

21 - 16 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

5. Stages of an ASP.NET page


1. Page request - When ASP.NET gets a page request, it decides whether to parse and
compile the page, or there would be a cached version of the page; accordingly the
response is sent.
2. Starting of page life cycle - At this point, the Request and Response objects are set.
If the request is an old request or post back, the IsPostBack property of the page is set
to true. The UICulture property of the page is also set.
3. Page initialization - During this stage, the controls on the page are assigned unique
ID by setting the UniqueID property and the themes are applied. For a new request,
postback data is loaded and the control properties are restored to the view-state
values.
4. Page load - In this , control properties are set using the view state and control state
values.
5. Validation - Validate method of the validation control is called and on its successful
execution, the IsValid property of the page is set to true.
6. Postback event handling - If the request is a postback (old request), the related
event handler is invoked.
7. Page rendering - In this, view state for the page and all controls are saved. The page
calls the Render method for each control and the output of rendering is written to the
OutputStream class of the Response property of page.
8. Unload - The rendered page is sent to the client and page properties, such as
Response and Request, are unloaded and all cleanup done.
6. ASP.NET Page Life Cycle Events

1. At each stage of the page life cycle, the page raises some events, for which the code
can be written. An event handler is a subroutine, bound to the event, using
declarative attributes such as Onclick or handle.
2. Page life cycle events
PreInit - it is the first event in page life cycle. It checks the IsPostBack property
and determines whether the page is a postback. It sets the themes and master
pages, creates dynamic controls, and gets and sets profile property values. This
event can be handled by overloading the OnPreInit method or creating a
Page_PreInit handler.

21 - 17 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

Init - Init event initializes the control property and the control tree is built. This
event can be handled by overloading the OnInit method or creating a Page_Init
handler.
InitComplete - InitComplete event allows tracking of view state. All the controls
turn on view-state tracking.
LoadViewState - LoadViewState event allows loading view state information
into the controls.
LoadPostData - During this phase, the contents of all the input fields are defined
with the <form> tag are processed.
PreLoad - PreLoad occurs before the post back data is loaded in the controls. This
event can be handled by overloading the OnPreLoad method or creating a
Page_PreLoad handler.
Load - The Load event is raised for the page first and then recursively for all child
controls. The controls in the control tree are created. This event can be handled by
overloading the OnLoad method or creating a Page_Load handler.
LoadComplete - The loading process is completed, control event handlers are
run, and page validation takes place. This event can be handled by overloading the
OnLoadComplete method or creating a Page_LoadComplete handler
PreRender - The PreRender event occurs just before the output is rendered. By
handling this event, pages and controls can perform any updates before the output
is rendered.
PreRenderComplete - As the PreRender event is recursively fired for all child
controls, this event ensures the completion of the pre-rendering phase.
SaveStateComplete - State of control on the page is saved. Personalization,
control state and view state information is saved. The HTML markup is generated.
This stage can be handled by overriding the Render method or creating a
Page_Render handler.
UnLoad - The UnLoad phase is the last phase of the page life cycle. It raises the
UnLoad event for all controls recursively and lastly for the page itself. Final
cleanup is done and all resources and references, such as database connections, are
freed. This event can be handled by modifying the OnUnLoad method or creating
a Page_UnLoad handler.

21 - 18 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

21.11 ASP.NET Applications and Configuration

AU : Dec.-17, 18, 19, May-18

21.11.1 Viewing Application Files, Setting Project Properties and Virtual


Directory
1. Viewing Application Files

When ASP.NET Web Application project is compiled , all code part that is behind code,
embedded resources and standalone class files are compiled into a single assembly that is built
in the \bin sub-directory underneath the project root. If required the physical storage location
can be changed .
To view all the project files, click on "Show All Files" button in the solution explorer.

Fig. 21.11.1 Web application files

2. Setting custom Project Properties

1. ASP.NET Web Application Projects and VS 2012 class library projects have the same
configuration settings and behaviors as standard.
2. These configuration settings can be edited by right-clicking on the project node within the
Solution Explorer and selecting the "Properties" context-menu item which opens the
project properties configuration editor.
3. Using the configuration editor the name of the generated assembly, the build compilation
settings of the project, its references, its resource string values, code-signing settings and
various other properties can be set.

21 - 19 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

Fig. 21.11.2 Web application project settings

4. ASP.NET Web Application Projects also add a new tab called "Web" to the project
properties list. Developers use this tab to configure how a web project is run and
debugged. By default, ASP.NET Web Application Projects are configured to launch and
run using the built-in VS Web Server (also known as Cassini) on a random HTTP port on
the machine.
This port number can be changed if this port is already in use, or if one want to
specifically test and run using a different number :

21 - 20 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

Fig. 21.11.3 Web application project settings

5. Also, Visual Studio can connect and debug IIS when running the web application. To use
IIS instead, select the "Use IIS Web Server" option and enter the url of the application to
launch, connect-to, and use when F5 or Control-F5 is selected :

21 - 21 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

Fig. 21.11.4 Web application project settings

6. Next configure the url to this application in the above property page for the web project.
When press F5 in the project, Visual Studio will then launch a browser to that web
application and automatically attach a debugger to the web-server process to enable to
debug it.
3. Virtual Directory and Configuring Through IIS vroot

1. ASP.NET Web Application Projects can also create the IIS vroot and configure the
application. To do this click the "Create Virtual Directory" button.
2. Virtual Directory
Concept

1. A virtual directory is a directory name that is specified in IIS and map to physical
directory on a local server's hard drive or a directory on another server (remote
server). Internet Information Services Manager can be used to create a virtual
directory for an ASP.NET Web application that is hosted in IIS.

21 - 22 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

Explanation

2. The virtual directory name becomes part of the application's URL. It should be
named appropriately. A virtual directory receives queries and directs them to the
appropriate backend identity repositories. It integrates identity data from multiple
heterogeneous data stores and presents it as though it were coming from one source.
3. Creating a virtual directory by using IIS Manager

Fig. 21.11.5 Web application virtual directory settings

3.1. In IIS Manager, expand the local computer and the Web site to which virtual
directory is to be added.
3.2. Right-click the site or folder in which the virtual directory is to be created,
click New, and then click Virtual Directory.
3.3. In the Add Virtual Directory dialog box, at least enter information in the Alias
and Physical path and then click OK.
4. By default, Internet Information Server uses configuration from Web.config files in
the physical directory to which the virtual directory is mapped, as well as in any child
directories in that physical directory.

21 - 23 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

21.11.2 Global.asax

1. Global.asax is a file used to declare application-level events and objects. Global.asax is


the ASP.NET extension of the ASP Global.asa file. Code to handle application events
(such as the start and end of an application) reside in Global.asax.
2. The Global.asax file must reside in the IIS virtual root. Remember that a virtual root can
be thought of as the container of a web application. Events and state specified in the
global file are then applied to all resources housed within the web application.
3. The Global.asax file is compiled upon the arrival of the first request for any resource in
the application.
21.11.3 Application Directives

Application directives are placed at the top of the Global.asax file and provide information
used to compile the global file. Three application directives are defined, namely Application,
Assembly, and Import. Directive has syntax:,
<%@ appDirective appAttribute=Value ...%>

21.11.4 Machine.config File

1. The machine.config file is the master configuration file on system with a lot of default
settings.
2. The settings of Machine.config file are applied to the whole ASP.NET applications on the
server.
3. Each .NET Framework version has only one machine.config file , at the same time.
5. The machine.config file file is at the highest level in the configuration hierarchy.
6. The machine.config is useful for sharing values between many applications on the server
such as SMTP server settings.
7. If there are changes in machine.config the application needs to be restarted.
8. The machine.config file is automatically installed when Visual Studio.NET is installed
and it resides in the c:\windows\microsoft.NET\framework\version\config folder.
9. Machine.config is configuration file for all the application in the IIS.
21.11.5 web.config File

1. Web.config is the file for the local settings to be applied for a website which store
configuration data in XML format.
2. The settings made in the Web.config file are applied to the particular web application.
3. Every web application has its own web.config file.

21 - 24 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

4. Directories inside a web application can also have web.config files.


5. Web.config file requires to override the settings from the machine.config file.
6. Web.config files contain application specific items such as database connection strings.
7. If there are any changes to the web.config, web application will immediately load the
changes.
8. web.config file is automatically created when an ASP.NET web application project is
created.
9. Web.config is a configuration file for a particular application or folder.

21.12 ASP.NET Controls AU : Dec.18, May-19

Concept

1. Controls are small building blocks of the graphical user interface, which include text
boxes, buttons, check boxes, list boxes, labels, and other tools.
Explanation

2. Controls are also used for structural jobs, like validation, data access, security, creating
master pages, and data manipulation.
3. ASP.NET has five types of web controls, namely,
1. HTML controls
2. HTML Server controls
3. ASP.NET Server controls
4. ASP.NET Ajax Server controls
5. User controls and custom controls
4. ASP.NET server controls are the primary controls that can be grouped into the following
categories-
Control Description
Validation Used to validate user input and they work by running
client-side script.
Data source Used to provide data binding to different data
sources.
Data view These are various lists and tables, which can bind to
data from data sources for displaying.
Personalization Used for personalization of a page according to the
user preferences, based on user information.

21 - 25 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

Login and security Used for user authentication.

Master pages Used for providing consistent layout and interface


throughout the application.

Navigation These controls help in navigation. For example,


menus, tree view etc.

Rich These controls implement special features. For


example, AdRotator, FileUpload, and Calendar
control.

The syntax for using server controls is:


<asp:controlType ID ="ControlID" runat="server" Property1=value1 [Property2=value2]
/>
5. HTML Server controls
Concept

HTML controls used to write GUI applications in HTML and these controls in
ASP.NET are the same HTML controls; which can run on the server by defining the
runat ="server" attribute.
Common HTML server Controls
Control Description

HtmlForm Create an HTML form control, used as a place holder of


other controls
HtmlInputText Creates an input text box control used to get input from user

HtmltextArea Creates multiline text box control


HtmlAnchor Creates a Web navigation
HtmlButton Creates a button control
HtmlImage Creates an image control, which is used to display an image

HtmlInputCheckBox Creates a check box control


HtmlInputRadioButton Creates a radio button control
HtmlTable Creates a table control
HtmlTableRow Creates a row within a table
HtmlTableCell Creates a cell with in a row

21 - 26 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

6. Web Server Controls


Concept

Web server controls provide more functionality than HTML controls and are easier to
use. Additional to commonly used UI controls, ASP.NET provides some more
powerful controls such as DataGrid, DataList, and Calendar.
Explanation

ASP.NET server controls with a visual aspect are derived from the WebControl class
and inherit all the properties, events, and methods of this class.
The WebControl class itself and some other server controls that are not visually
rendered are derived from the System.Web.UI.Control class. For example, PlaceHolder
control or XML control.
ASP.NET server controls inherit all properties, events, and methods of the WebControl
and System.Web.UI.Control class.
Common Web Server controls

Control Description

Label Represents a label control

ListBox Represents a list box control

CheckBox Represents a Check box control

Calendar Represents a calendar control

ImageButton Represents an image button control

TableCell Represents a table cell

Panel Represents a panel control

DataList Represents a data list control

TextBox Represents a text box control

Image Represents an image control

CheckBoxList Represents a list box with check boxes

Button Represents a button control

HyperLink Represents a hyperlink control

TableRow Represents a row of a table

21 - 27 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

RadioButtonList Represents a list box with radio button controls

DataGrid Represents a data grid control

DropDownList Represents a drop-down list control

AdRotator Represents an ad rotator control

RadioButton Represents a radio button control

LinkButton Represents a link button control

Table Represents a table control

Repeater Represents a repeater control

7. Validation Controls
Concept

For validating the user input in the Web applications, validation controls are used. Using
these controls one can check as required field, a value, a range, a pattern of characters
etc.
Common Validation Controls

Control Description

RequiredFieldValidator Makes sure that the user doesn't skip an entry

CompareValidator Compares user input with a value using a comparison operator


such as less than, greater than, and so on

RangeValidator Checks if the user's input falls with in a certain range

RegularExpressionValidator Checks if the user's input matches a defined pattern

CustomValidator Create own customer logic

8. Example
Validation controls are inbuilt controls which can be added through the toolbox. This is
illustrated in following example. Follow the steps as mentioned below for validating the
input required for the various controls.

21 - 28 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

Fig. 21.12.1 Validation control example

Fig. 21.12.2 Validation control example

21 - 29 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

Fig. 21.12.3 Validation control example

Fig. 21.12.4 Validation control example

21 - 30 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

Fig. 21.12.5 Validation control example

Fig. 21.12.6 Validation control example

21 - 31 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

Fig. 21.12.7 Validation control example

Fig. 21.12.8 Validation control example

21 - 32 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

Fig. 21.12.9 Validation control example

Fig. 21.12.10 Validation control example

21 - 33 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

Fig. 21.12.11 Validation control example

Fig. 21.12.12 Validation control example

21 - 34 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

Fig. 21.12.13 Validation control example

Fig. 21.12.14 Validation control example

21 - 35 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

Fig. 21.12.15 Validation control example

Fig. 21.12.16 Validation control example

21 - 36 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

Fig. 21.12.17 Validation control example

Adding Server Controls Using ASP.NET Syntax


There are various methods to add server controls in web form.
Method 1 - using the VS .NET IDE to add server Controls by creating a new ASP.NET
Application project, open the toolbox, drag and drop controls from the toolbox, set properties,
and write event handlers for the control.
Method 2 - adding manually, by creating a text file and save it with an .aspx extension
.NET utilizes XML tags to write server controls. A tag should follow XML syntax. Every
ASP.NET control starts with asp: and a control name. For example, the following line a text
box control :
<asp: textbox id=TxtBox1 runat = "Server" Text =" " text =" "> </asp:textbox>
Here, a text box server control is created. Event control has unique ID. In this sample the
ID is TxtBox1. The runat ="Server" attribute represents that the control will run on the server.
Same code can be written without the closing tag as,
<asp:textbox id = Textbox1 runat ="server" />
Example
//adding a server control
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
nherits="firstaspnet._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

21 - 37 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button" BackColor="#3366FF" Font-
old="True"
ForeColor="Yellow" /><br />
<br />
<asp:TextBox ID="TextBox1" runat="server" BorderColor="#66CCFF"
orderStyle="Groove"
Height="32px" Width="198px"></asp:TextBox>
<br />
<asp:ListBox ID="ListBox1" runat="server" BackColor="#CCFF99" Height="209px"
idth="310px">
</asp:ListBox>
<font size="5"><strong>Adding Server Control in ASP.NET
pplication</strong></font>
<p>
<font><strong>Click Add button to add contents of text box to the list
ox</strong></font>
</p>
</div>
</form>
</body>
</html>
Some Common Properties of the Server Controls
The following table shows the inherited properties, common to all server controls :

Property Description

AccessKey Pressing this key with the Alt key moves focus to the control.

Attributes It is the collection of arbitrary attributes (for rendering only) that


do not correspond to properties on the control.

BackColor Background color.

BindingContainer The control that contains this control's data binding.

BorderColor Border color.

BorderStyle Border style.

BorderWidth Border width.

CausesValidation Indicates if it causes validation.

21 - 38 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

ChildControlCreated It indicates whether the server control's child controls have been
created.

ClientID Control ID for HTML markup.

Context The HttpContext object associated with the server control.

Controls Collection of all controls contained within the control.

ControlStyle The style of the Web server control.

CssClass CSS class

DataItemContainer Gets a reference to the naming container if the naming container


implements IDataItemContainer.

DataKeysContainer Gets a reference to the naming container if the naming container


implements IDataKeysControl.

DesignMode It indicates whether the control is being used on a design surface.

DisabledCssClass Gets or sets the CSS class to apply to the rendered HTML element
when the control is disabled.

Enabled Indicates whether the control is grayed out.

EnableTheming Indicates whether theming applies to the control.

EnableViewState Indicates whether the view state of the control is maintained.

Events Gets a list of event handler delegates for the control.

Font Font.

Forecolor Foreground color.

HasAttributes Indicates whether the control has attributes set.

HasChildViewState Indicates whether the current server control's child controls have
any saved view-state settings.

Height Height in pixels or %.

ID Identifier for the control.

IsChildControlStateCleared Indicates whether controls contained within this control have


control state.
IsEnabled Gets a value indicating whether the control is enabled.
IsTrackingViewState It indicates whether the server control is saving changes to its view
state.

21 - 39 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

IsViewStateEnabled It indicates whether view state is enabled for this control.

LoadViewStateById It indicates whether the control participates in loading its view state
by ID instead of index.

Page Page containing the control.

Parent Parent control.

RenderingCompatibility It specifies the ASP.NET version that the rendered HTML will be
compatible with.

Site The container that hosts the current control when rendered on a
design surface.

SkinID Gets or sets the skin to apply to the control.

Style Gets a collection of text attributes that will be rendered as a style


attribute on the outer tag of the Web server control.

TabIndex Gets or sets the tab index of the Web server control.

TagKey Gets the HtmlTextWriterTag value that corresponds to this Web


server control.

TagName Gets the name of the control tag.

TemplateControl The template that contains this control.

TemplateSourceDirectory Gets the virtual directory of the page or control containing this
control.

ToolTip Gets or sets the text displayed when the mouse pointer hovers over
the web server control.

UniqueID Unique identifier.

ViewState Gets a dictionary of state information that saves and restores the
view state of a server control across multiple requests for the same
page.

ViewStateIgnoreCase It indicates whether the StateBag object is case-insensitive.

ViewStateMode Gets or sets the view-state mode of this control.

Visible It indicates whether a server control is visible.

Width Gets or sets the width of the Web server control.

21 - 40 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

Common Methods of the Server Controls


The following table provides the methods of the server controls:

Method Description

AddAttributesToRender Adds HTML attributes and styles that need to be rendered to


the specified HtmlTextWriterTag.

AddedControl Called after a child control is added to the Controls collection


of the control object.

AddParsedSubObject Notifies the server control that an element, either XML or


HTML, was parsed, and adds the element to the server
control's control collection.

ApplyStyleSheetSkin Applies the style properties defined in the page style sheet to
the control.

ClearCachedClientID Infrastructure. Sets the cached ClientID value to null.

ClearChildControlState Deletes the control-state information for the server control's


child controls.

ClearChildState Deletes the view-state and control-state information for all


the server control's child controls.

ClearChildViewState Deletes the view-state information for all the server control's
child controls.

CreateChildControls Used in creating child controls.

CreateControlCollection Creates a new ControlCollection object to hold the child


controls.

CreateControlStyle Creates the style object that is used to implement all style
related properties.

DataBind Binds a data source to the server control and all its child
controls.

DataBind(Boolean) Binds a data source to the server control and all its child
controls with an option to raise the DataBinding event.

DataBindChildren Binds a data source to the server control's child controls.

Dispose Enables a server control to perform final clean up before it is


released from memory.

21 - 41 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

EnsureChildControls Determines whether the server control contains child


controls. If it does not, it creates child controls.

EnsureID Creates an identifier for controls that do not have an


identifier.

Equals(Object) Determines whether the specified object is equal to the


current object.

Finalize Allows an object to attempt to free resources and perform


other cleanup operations before the object is reclaimed by
garbage collection.

FindControl(String) Searches the current naming container for a server control


with the specified id parameter.

FindControl(String, Int32) Searches the current naming container for a server control
with the specified id and an integer.

Focus Sets input focus to a control.

GetDesignModeState Gets design-time data for a control.

GetType Gets the type of the current instance.

GetUniqueIDRelativeTo Returns the prefixed portion of the UniqueID property of the


specified control.

HasControls Determines if the server control contains any child controls.

HasEvents Indicates whether events are registered for the control or any
child controls.

IsLiteralContent Determines if the server control holds only literal content.

LoadControlState Restores control-state information.

LoadViewState Restores view-state information.

MapPathSecure Retrieves the physical path that a virtual path, either absolute
or relative, maps to.

MemberwiseClone Creates a shallow copy of the current object.

MergeStyle Copies any nonblank elements of the specified style to the


web control, but does not overwrite any existing style
elements of the control.

21 - 42 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

OnBubbleEvent Determines whether the event for the server control is passed
up the page's UI server control hierarchy.

OnDataBinding Raises the data binding event.

OnInit Raises the Init event.

OnLoad Raises the Load event.

OnPreRender Raises the PreRender event.

OnUnload Raises the Unload event.

OpenFile Gets a Stream used to read a file.

RemovedControl Called after a child control is removed from the controls


collection of the control object.

Render Renders the control to the specified HTML writer.

RenderBeginTag Renders the HTML opening tag of the control to the specified
writer.

RenderChildren Outputs the contents of a server control's children to a


provided HtmlTextWriter object, which writes the contents to
be rendered on the client.

RenderContents Renders the contents of the control to the specified writer.

RenderControl(HtmlTextWriter) Outputs server control content to a provided HtmlTextWriter


object and stores tracing information about the control if
tracing is enabled.

RenderEndTag Renders the HTML closing tag of the control into the
specified writer.

ResolveAdapter Gets the control adapter responsible for rendering the


specified control.

SaveControlState Saves any server control state changes that have occurred
since the time the page was posted back to the server.

SaveViewState Saves any state that was modified after the TrackViewState
method was invoked.

SetDesignModeState Sets design-time data for a control.

ToString Returns a string that represents the current object.

21 - 43 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

TrackViewState Causes the control to track changes to its view state so that
they can be stored in the object's view state property.

21.13 Web Forms - Data Binding

Concept

1. Web Forms provides various controls that support data binding. These controls can be
connected to ADO.NET components such as a DataView, DataSet, or a
DataViewManager at design-time as well as at run-time.
Explanation

2. Data binding in Web Forms works in the same way as it does in the Windows Forms with
a few exceptions incase of method calls. For example, to bind a dataset to a DataGrid, the
DataBind method of the DataGrid control is called.
3. 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.
4. 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.
5. Data-Bound Controls
ASP.NET provides a rich set of data-bound server controls.
Single data item control -single-item data-bound controls are used to display the
value of a single item of a database table. These controls don't provide direct
binding with the data source. Some of the single-item data-bound controls are
textboxes, buttons, labels, images, and so on.
Multi-item data bound controls - Multi-item data bound controls are used to
display the entire or a partial table. These controls provide direct binding to the
data source. The DataSource property of these controls is used to bind a database
table to these controls. Some of the multi-item data-bound controls are DataGrid,
ListBox, DataList, DropDownList.

21 - 44 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

Fig. 21.13.1 Data-bound control

In ASP.NET, Databound controls are created using a <asp:controlName> tag.


ASP .NET Data-Bound ControlsASP.NET CODE DESCRIPTION

Control ASP.NET Description

DataGrid <asp:DataGrid> Display a database (through ADO .NET) in a


scrollable grid format and supports selection, adding,
updating, sorting, and paging

DataList <asp:DataList> Displays data in templates and style format

ListBox <asp:ListBox> Displays list box, which can be associated to


ADO.NET data field to display data in a list format

DropDownList <asp:DropDownList> Displays DropDownList control, which can be used to


display ADO.NET data source data in a drop down
combo box format

CheckBox <asp:CheckBox > Display single check box, which can be connected to
an item of the ADO.NET data source

CheckBoxList <asp:CheckBoxList> Display list of check boxes that can be connection to


the to the ADO.NET data source

Repeater <asp:Repeater> Displays a templated data-bound list

TextBox <asp:TextBox> Displays a text box, which can be used to display


ADO.NET using its Text property

21 - 45 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

6. Data Configuration in Simple Data Binding

Simple data binding involves the read-only selection lists.


Configuring the data source control to retrieve two values from database involves
following steps,
Selection of the data source control
Selection of a field to display, which is called the data field
Selection of a field for the value

Fig. 21.13.2 Data source configuration

7. Data Configuration in Declarative Data Binding

Data binding involves the following objects :


A dataset that stores the data retrieved from the database.
The data provider, retrieves data from the database by using a command over a
connection.
The data adapter that issues the select statement stored in the command object; it is also
capable of update the data in a database by issuing Insert, Delete, and Update
statements.

21 - 46 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

Fig. 21.13.3 Relation between the data binding objects

21.14 Event

Concept

1. An event is an action or occurrence such as a mouse click, a key press, mouse


movements, or any system-generated notification. A application communicates with user
through events. As event occurs, the application must respond event and handle.
Explanation

2. Events in ASP.NET raised at the client machine, and handled at the server machine as the
user is accessing the UI from client machine and its handler is present on server side.
3. Event Arguments
ASP.NET event handlers generally take two parameters and return void. The first
parameter represents the object raising the event and the second parameter is event
argument.
The general syntax of an event is:
private void EventName (object sender, EventArgs e);
4. Important Application Events

Application_Start Raised when the application/website is started.

Application_End Raised when the application/website is stopped.

5. Important Session Events

Session_Start Raised when a user first requests a page from the


application.

Session_End Raised when the session ends.

21 - 47 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

6. Page and Control Events


DataBinding Raised when a control binds to a data source.

Disposed Raised when the page or the control is released.

Error A page event, occurs when an unhandled exception is thrown.

Init Raised when the page or the control is initialized.

Load Raised when the page or a control is loaded.

PreRender Raised when the page or the control is to be rendered.

Unload Raised when the page or control is unloaded from memory.

7. Event Handling Using Controls


All ASP.NET controls are implemented as classes with associated events which are
fired when a user performs a certain action on them. For example, user clicks a button
the 'Click' event is generated.
For dealing with the events, in-built attributes and event handlers are supported by
.NET.
By default, Visual Studio creates an event handler by including a Handles clause on the
Sub procedure. This clause names the control and event that the procedure handles.
The ASP tag for a button control
<asp:Button ID="btnOk" runat="server" Text="Ok" />
The event handler for the Click event
Protected Sub btnOk_Click(ByVal sender As Object, ByVal e As System.EventArgs)

Handles btnOk.Click

End Sub
An event can also be coded without Handles clause by naming the handler according to
the appropriate event attribute of the control.
The ASP tag for a button control
<asp:Button ID="btnOk" runat="server" Text="Ok" Onclick="btnOk_Click" />
The event handler for the Click event
Protected Sub btnOk_Click(ByVal sender As Object, ByVal e As System.EventArgs)

End Sub

21 - 48 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

The common control events

Event Attribute Controls

Click OnClick Button, image button, link button,


image map

Command OnCommand Button, image button, link button

TextChanged OnTextChanged Text box

SelectedIndexChanged OnSelectedIndexChanged Drop-down list, list box, radio


button list, check box list.

CheckedChanged OnCheckedChanged Check box, radio button

Postback events and non-postback events


Certain events cause the form to be posted back to the server immediately, which are called
the postback events. For example, the click event such as, Button.Click.
Some events are not posted back to the server immediately, these are called non-postback
events.
For example, the change events or selection events such as CheckBox.CheckedChanged.
The nonpostback events could be made to post back immediately by setting their
AutoPostBack property to true.
Default Events
Every control has a default event. The default event for the Page object is Load event and
default event for the button control is the Click event. The default event handler could be
created in Visual Studio, just by double clicking the control in design view.
Default events for common controls

Control Default Event

AdRotator AdCreated

BulletedList Click

Button Click

Calender SelectionChanged

CheckBox CheckedChanged

CheckBoxList SelectedIndexChanged

21 - 49 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

DataGrid SelectedIndexChanged

DataList SelectedIndexChanged

DropDownList SelectedIndexChanged

HyperLink Click

ImageButton Click

ImageMap Click

LinkButton Click

ListBox SelectedIndexChanged

Menu MenuItemClick

RadioButton CheckedChanged

RadioButtonList SelectedIndexChanged

Example
//Illustration of page events and control events.
/*As the page events happens, (such as Page_Load, Page_Init, Page_PreRender) ,
application sends a message, which is displayed by the label control. When the button
is clicked, the Button_Click event is raised and that also sends a message to be
displayed on the label.*/
//a simple page with a label control and a button control on it.
/*Create a new website and drag a label control and a button control on it from the control
tool box. Using the properties window, set the IDs of the controls as .lblmessage. and
.btnclick. respectively. Set the Text property of the Button control as 'Click'.*/
//The markup file (.aspx)
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
Inherits="eventdemo._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">
<title>Untitled Page</title>
</head>

<body>

21 - 50 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

<form id="form1" runat="server">


<div>
<asp:Label ID="lblmessage" runat="server" >

</asp:Label>

<br />
<br />
<br />

<asp:Button ID="btnclick" runat="server" Text="Click" onclick="btnclick_Click" />


</div>
</form>
</body>

</html>
//Double click on the design view to move to the code behind file.
//The Page_Load event is automatically created without any code in it.
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;

using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

using System.Xml.Linq;

namespace eventdemo {

public partial class _Default : System.Web.UI.Page {

protected void Page_Load(object sender, EventArgs e) {


lblmessage.Text += "Page load event handled. <br />";

if (Page.IsPostBack) {
lblmessage.Text += "Page post back event handled.<br/>";
}
}

protected void Page_Init(object sender, EventArgs e) {

21 - 51 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

lblmessage.Text += "Page initialization event handled.<br/>";


}

protected void Page_PreRender(object sender, EventArgs e) {


lblmessage.Text += "Page prerender event handled. <br/>";
}

protected void btnclick_Click(object sender, EventArgs e) {


lblmessage.Text += "Button click event handled. <br/>";
}
}
}
Execute the page. The label shows page load, page initialization and, the page pre-render
events.

Fig. 21.14.1 Web application output

21.15 State Management Techniques AU : Dec.-18, 19, May-18

21.15.1 State Management


Concept
State Management can be defined as the technique or the way by which the state of the
page or application can be maintained or stored until the user's Session ends.
It can be thought of as a kind of interaction between the User and the Server.
21.15.2 ASP.NET and HTTP
Explanation

In ASP.NET environment, the App Domain is created only once for each Website or an
application. The Http Application Object is also created only once. The creation happens
when the user requests a website for the first time.

21 - 52 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

HTTP

1) Hyper Text Transfer Protocol makes use of the TCP Protocol for communicating with the
server. A specific port is being used by this protocol while communicating with the
server.
2) HTTP provides various methods which represent the actions it will perform while
communicating with the server. Some of its methods are "GET", "POST", "DELETE",
"HEAD", etc....
3) HTTP acts like a bridge between the client and the server as explained below. When user
requests a web page, the HTTP Protocol takes the request being sent by the client (using
client’s browser) and sends it to the server. After receiving the request server locates the
requested page and tells the respective website engine to process the request. The website
Engine processes the request and sends a response back to the client in an HTML format.
Now, HTTP protocol takes the response and sends it to the client which is shown in the
client's browser.
4) As HTTP protocol is a stateless protocol, it is not able to store the state during that
session. With each request the objects are created and memory is being allocated and the
resources are reclaimed once the server completes its process. Therefore, the cycle of
"Create Objects and Utilization of Server Memory" ---- "Process the Request" ----
"Reclaim the Created Resources" continues for each and every user's request. The
information given by the user or the State of an Application gets lost during each round
trip. In this scenario the State Management is helpful.
21.15.3 State Management Approaches and Techniques

There are 2 approaches by which ASP.NET manages the state of an application namely,
1) Client Side State Management.
2) Server Side State Management.
21.15.3.1 Client Side State Management

1) In this method the information added by the user or the information about the user-server
interaction is stored on the client's machine or in the page itself. The server resources, like
server's memory, are not utilized.
2) Bandwidth should be considered while implementing client side state management
options because they involve in each roundtrip to server.

21 - 53 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

3) Client side state management uses following techniques,


1) View State
2) Hidden Fields
3) Query String
4) Cookies
5) Control State
1. View State

1) View state in ASP.NET provides information for the particular ASP.NET page. If
there is a requirement for maintaining the web page, the .NET framework manages it
automatically.
2) View State is used to maintain the State at a page level. By "Page Level" it means
that the information is being stored for a specific page which held till the specific
page is active (the page which is being currently viewed by the user).
3) When the user is re-directed or visits some other page, the information stored in the
View State gets lost.
4) The information about the view state is serialized into XML and encoded through
base. The page performance varies if the data is large. Although the view state is
enabled some of the controls do not need it. The view state can be disabled for a
particular control.
5) In this technique a "Dictionary Object" is used to store data, where in the information
is stored in a key and value pair. The information is stored in a Hidden field on the
page itself in a hashed format. A View State can store a string value only of a specific
length. The string length if exceeded then another hidden field is used to store the
excess information.
6) Manipulating the view state
1) The view state for the control can be disabled by modifying the
EnableViewState attribute to false.
2) The view state for a web page can be modified by changing the
EnableViewState attribute in the @Page directive.
3) The view state for the complete application can be modified through the
<pages> section in config file.
7) Advantages of using view state technique
1) It is quite simple to use.

21 - 54 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

2) The view state values can be encoded, hashed and compressed. Data is stored
in hashed format hence the values are secured from common users but to
make it secured from hackers it should be encrypted.
3) There is no need to implement code for maintaining view state.
4) View state can be customized.
5) There is no server resource used for managing the state.
8) Disadvantages of using view state technique
1) The data stored for view state is saved into more hidden fields on the web
page. The data can be modified by the users therefore cannot be used to store
sensitive data like Passwords, Credit Card Pins, etc.
2) Information is not encrypted, so it is easy for a Hacker to get its value.
3) The performance for the web page decreases as the page becomes heavy due
to the values saved in the page.
4) The data storage is restricted for the memory of the device used.
9) Example

Step 1 : Storing Value in a View State


protected void btnsubmit(Object sender, EventArgs e)
{
Viewstate[“LoginName”]= txtloginname.Text;
}
/* "LoginName" is the key and the value is the text contained in txtloginname.Text */

Step 2 : Retrieving Value from a View State


protected void Page_Load(Object sender, EventArgs e)
{
if( !String.IsNullOrEmpty(Convert.ToString(ViewState[LoginName])))
{
Lblloginname.Text=Convert.ToString(ViewState[LoginName]);
}
}

/* In the Page Load event of a page the values from view state are retrieved if view
state is not empty. */

Step 3 : View state format


View State Information is stored in a Hashed Format which can be viewed in page source.
<div>
,input type = “hidden” name=”_VIEWSTATE” id=”_VIEWSTATE” value=
“/'AMWZ4U6K5W-8Gt4pqjgClstMMUgD6nYl9XOsU =”/>

21 - 55 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

10) View State Settings


View State can be customized using term "Customizable". View State can be
customized to store a value at various levels like
1) Setting View State at Application Level (when pages in the Application are
disallowed to use view state, one can disable or enable it in the web.config
file.)
2) Setting View State at Page Level (if specific page is disallowed to use View
State, then one can disable or enable it in the @ Page Directive which is the
first line of aspx page.
3) Setting View State at Control Level (when a specific control is disallowed
to use View State, then it can be disabled or enabled at a Control Level)
2) Hidden Fields

1) ASP.NET provides a server control named "Hidden Field". This can be used to store
a value at a page level, which is similar to a View State. The value of the Hidden
Field is sent along in the HTTP Form Collection along with the value of other
controls.
2) Advantages
Simple to use and hidden Fields store the value in the page itself, therefore, do not
use server resources.
3) Disadvantages
1) Hidden fields make a page heavy when too many Hidden Fields are used to
store data.
2) Hidden field cannot be used to store sensitive data because value being held is
not hashed or not encrypted.
4) Storing and retrieving hidden values
Step 1 : Setting Value to a Hidden Field
/* (txtUsername.Text) value is assigned to the Hidden Field's Value property. */

protected void btnok_Click(Object sender, EventArgs e)


{
hiddenval.Value = txtUsername.Text;
}

21 - 56 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

Step 2 : Retrieving Value from a Hidden Field


/* a value from in the Hidden field is retrieved and assigned to a label. The Hidden Field's
"Value" property returns a string by default. If required other datatype value the explicit
conversion is required. */

protected void Page_Load(object sender, EventArgs e)


{
if(! String.IsNullOrEmpty(hdfValue.Value))
{
lbllogin.Text = hiddenval.Value;
}

/* hidden field values are stored on the page itself. When the user is redirected to some
other page the value is lost. */

<tr>
<td>
<span id=”lblname”></span>
<input type = “hidden” hdfValue” id=”hdfValue” value=”RaviW”/>
</td>
<tr>

/* here “RaviW” is passed as a value from textbox and assigned to a hidden field */
3) Query String

1) A Query String is appended to the end of the Page URL for holding additional
information. It is a simple technique to use for sending data across pages.
2) It stores information in a key - value pair. A "?" signature is used to append the key
and value to the page URL.
3) Methods to pass a value using Query String
protected void btnOk_Click(Object sender, EventArgs e)
{
Response.Redirect(String.Format(“Default.aspx?Username={0}”,txtLogin.Text.Trim()));
}
/* here code sends the Login to another page and use that value on that page.*/
/* reading Query String value */
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
string Login = this.Request.QueryString[“Login”];
lblLogin.Text =Login;
}
}

21 - 57 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

/*Query string value is read using the Request Object. Multiple parameters can be sent in
the query string along with its respective value. In case of Multiple parameters, individual
parameters are separated using the "&"delimeter.*/
4) Cookies

1) Cookies are another best ways supported by ASP.Net for state management using
which information is stored. It is a text file which is stored on the client's machine.
2) When the user sends a request to the server, the server creates a cookie and attaches a
header and sends it back to the user along with the response. The browser accepts the
cookie and stores it at a specific location on the client's machine. Popular and large
data size sites like Gmail, Facebook, Yahoo use cookies.
3) There are 2 ways of assigning / storing values in cookies.
1. Using the Request Object
protected void btnOk_Click(Object sender, EventArgs e)
{
this.Request.Cookies[“Login”].Value = txtLoginname.Text.Trim();
}

/*The Cookies property of the HTTPResponse Object and the HTTPRequest Object can be
used to assign values to the Cookies Collection and get values back from the Collection.
Multiple values can be stored in a cookie.*/

2. Using the HTTPCookies Object


protected void btnOk_Click(Object sender, EventArgs e)
{
HttpCookie logCookie = HttpCookie(“Login”, txtLogin.Text.Trim());
logCookie[“LId”] =”78”;
logCookie.Expires.AddHours(3);
Response.Cookies.Add(logCookie);
}

/* HTTPCookie class is used to send cookie with cookie expiration time set for that cookie.
Response.Cookies.Add(logCookie) adds cookie to the Cookies Collection. */
4) Advantages of cookies
Cookies are very handy to use and no server resources are used as they get stored on
client machine.
5) Disadvantages of cookies
1) There is chance that user may disable cookies using browser settings.

21 - 58 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

2) As cookies are on client machine hackers have situation to hack data in


cookies therefore for holding sensitive data cookies are not at all a good
choice.
5) Control State

1) Control State introduced in ASP.NET 2.0 which addresses some of the shortcomings
of View State.
2) Control state can be used to store sensitive information across post backs.
3) Control state is a state container in which controls maintain their core behavioral
functionality whereas View State contains state to maintain control's contents (UI)
only.
4) Control State shares same memory data structures with View State.
5) If View State for the control is disabled then also the Control State can be
propagated. For example, new control Grid View in ASP.NET 2.0 makes effective
use of control state to maintain the state needed for its core behavior across post
backs.
21.15.3.2 Server Side State Management

1) It is a way by which ASP.NET provides storage of the user's specific information or the
state of the application on the server machine. It completely makes use of server resources
(the server's memory) to store information in contrast to client side state management
techniques that hold data on client machine.
2) Application, session, cache, databases can be used for server side state management.
3) While doing state management on server side care must be taken to conserve server
resources. For a high traffic web site with large number of concurrent users, usage of
sessions object for state management can create load on server causing performance
degradation
4) Server side state management uses following techniques
1) Application State
2) Session State
1. Application State

1) It stores information as a Dictionary Collection in key - value pairs in specific URL.


This value is accessible across the pages of the application / website.

21 - 59 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

2) The application state data are maintained using the events stated below.
1) Application_Start, It states the start of the application.
2) Application_End, The end of the application is determined.
3) Application_Error, The error present in the application is mentioned.
4) Session_Start, The start of the session is specified.
5) Session_End, The end of the session is specified.
3) The HttpApplication class
1) This is used for providing the application state information. The application
specific values can be saved in the application state and are managed by the
server.
2) The state is a global storage and can be accessed through the pages in the
application.
3) Properties of HttpApplication state
1) Count, gives the number of objects in the HttpApplication class
2) AllKeys, is the collection from which the keys are accessed.
3) StaticObjects, hold the objects present in the <object> tag are accessed
4) Item[Int32], the single HttpApplicationState object which is retrieved by the
index.
5) Contents, is the reference for the HttpApplicationState object.
4) Methods of HttpApplication state
1) Clear, All the objects are removed from the collection
2) Add, A new object is added to the collection
3) GetType, The Type of the current instance is accessed
4) Remove, The named objects are removed from the collection
5) Set, The value of an object is updated
6) Lock, The variable is accessed for managing the synchronization
7) GetHashCode, The default hash function is accessed
4) Advantages of the Application State
1) The application state is accessed through all the web pages therefore, a single
copy can be used for storing the information
2) It is easy for users and provides consistent framework classes.

21 - 60 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

5) Disadvantages of the Application State


1) The server memory is needed by the application state due to which the server
performance is affected. Once the server process is destroyed, the global data of
the application state is removed.
2) The unique values cannot be saved in the application state
6) There are three events provided by ASP.NET application. They are as listed
below.
1) Application_Start : It is raised when the application starts the execution. The
application variables can be initialized.
2) Application_End : When the application closes, the event is raised. All the
application resources for the user are released.
3) Application_Error : When unhandled errors occur, the exception is raised.
7) Getting and setting the values
The values can be set and retrieved in the above mentioned application’s events as
shown below.
1. Setting value to the Application Object -
"PageTitle" is the Key and "Welcome to State Management Application" is the value.

void Application_Start(object sender, EventArgs e)


{
this.Application[“PageTitle”] =”C# ASP .NET Programming”;
}

2. Reading value from the Application Object


protected void Page_Load(object sender, EvenrArgs e)
{
if (!Page.IsPostBack)
{
This.PageTitle =Convert.ToString(this.Application[“PageName”);
}
}
2) Session State

1) Session state in ASP.NET is a very popular and easy way to maintain the application
state in which the values are stored as a dictionary collection in key/value pairs.
2) It utilizes server resources to store the data.
3) The scope of the state is restricted to current browser and every user has a unique
session id.

21 - 61 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

4) The key/value pair structure is used for saving the session.


5) From security view point this technique is always preferable because the data is never
be passed to the client. Data is hold on server only.
6) For every user, a separate Session is created and every Session has its Unique ID.
This ID is being stored in the client's machine using cookies. For multiple users
(accessing same web application), each user a separate Session is created. The
session is killed when user logs out. When same user logs into the application again,
the user is treated as a fresh without effect of any previous history and a new Session
ID is created for the same user.
7) The Session has a default timeout value (in current version it is 20 minutes). The
timeout value for a session can be set in the web.config file.
<sessionState cookieless = “UseUri” mode = “SQLServer”> </sessionState>
8) Built-in SessionStateItemCollection object is used for storing the session variables.
9) The Session property gives the information about the object. The object variables are
indexed by variable name or integer index.
10) The HttpSessionState class
1) Properties of HttpSessionState class
1) Count, gives the number of items present in the session state collection.
2) CookieMode, is used for the application configuration for the cookieless
sessions.
3) IsReadOnly, attribute states whether the session is read only.
4) Keys, are used for accessing the values present in the session collection.
5) Timeout, is the amount of time in minutes used by the provider for ending the
session
2) Methods of the HttpSessionState class
1) Add, adds the new item to the collection.
2) Clear, clears all the key and values are removed from the collection.
3) GetType, returns the Type of the current instance obtained.
4) RemoveAll, removes the key and values from the collection.
5) ToString, the string representing the current object is obtained.
11) Advantages of the Session State
1) The session management events can be raised and used by the application and
can be created by the application as well.

21 - 62 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

2) It supports customization for session state through the state provider.


3) The contents are kept in session state variables using the IIS.
12) Disadvantage of the Session State
The state variables are present in the memory until explicitly removed or replaced
due to which the server performance degrades.
13) Session object
1) Session object is used to store state specific information per client basis. It is
specific to particular user.
2) Session data persists for the duration of user session. Session's data can be
stored on web server in different ways.
3) Session state in ASP.NET can be configured in different ways based on various
parameters including scalability, maintainability and availability
4) Configuring Session State,
Session state can be configured using the <session State> section in the application's
web.config file as mentioned below.
<sessionState mode = <"inproc" | "sqlserver" | "stateserver">
cookieless = <"true" | "false">

timeout = <positive integer indicating the session timeout in minutes>


sqlconnectionstring =

<SQL connection string that is only used in the SQLServer mode>


server =

<The server name that is only required when the mode is State Server>
port =

<The port number that is only required when the mode is State Server>
Where Settings Details are as explained below,

i) Cookie less
This setting takes a Boolean value of either true or false to indicate whether the Session is
a cookie less one.
ii) Timeout
This indicates the Session timeout vale in minutes. This is the duration for which a user's
session is active. Note that the session timeout is a sliding value; Default session timeout
value is 20 minutes

21 - 63 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

iii) SqlConnectionString
This identifies the database connection string that names the database used for mode
SQLServer.
iv) Server
In the out-of-process mode State Server, it names the server that is running the required
Windows NT service: aspnet_state.
v) Port
This identifies the port number that corresponds to the server setting for mode State
Server. Port is an unsigned integer that uniquely identifies a process running over a
network.
5) Mode setting supports 4 types of settings namely OFF, InProc, SQLServer and State
Server options which are discussed below in detail.
1) OFF
When session is not to be stored in the application, then "OFF" mode is set. One can
set off session mode for entire application by setting mode=off in web.config file to
reduce overhead for the entire application. One can disable session for a page using
EnableSessionState attribute.
2) InProc
1) In this default mode ASP.NET stores session variables values in the process in
which the ASP.NET application is running.
2) As it is stored in the same process, it provides high performance as compared to
other modes.
3) Advantages
It is Fastest mode and has Simple configuration.
4) Disadvantage
Session data will be lost if the worker process or application domain recycles.
It is not ideal for web gardens (Web garden is a scenario in which a single
machine has multiple asp.net worker processes running simultaneously) and
web farms (A hosting environment consisting of multiple web servers is said to
be a Web Farm.)
5) Configuration Settings
<sessionState mode="Inproc"
sqlConnectionString="data source=server;
user id=RaviW;password=technical"
cookieless="false" timeout="20" />

21 - 64 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

3) Out of process mode - Storing session in State Server process


1) In this mode, a separate Windows Service runs in a different process that stores
the Session.
2) This method isolates the Session from the ASP.NET running process. Due to
separate process its performance degrades.
3) This mode is ideal for scalable and highly available applications.
4) Advantages
Session data is persisted across application domain recycles. This is achieved
by using separate worker process for maintaining state
Supports web farm and web garden configuration
5) Disadvantages
It requires data serializing.
It has overhead in encoding View State values
Inappropriate for sensitive data
6) Session state is held in a process called aspnet_state.exe that runs as a windows
service which listens on TCP port 42424 by default. State service can be
invoked using services MMC snap-in or by running following net command
from command line.
7) Configuration Settings
<sessionState mode="StateServer"
StateConnectionString="tcpip=127.0.0.1:42424"
sqlConnectionString="data source=127.0.0.1;
user id=RaviW; password=technical"
cookieless="false" timeout="20"/>
4) Storing session in SQL server
1) SQL Server mode is the one in which the Session is stored in SQL Server rather
than in the server's memory.
2) When the application is stored on multiple server machines, then it is infeasible
to use "Inproc" mode as the requests go to any server for processing. Therefore,
in this situation, only feasible centralized place to hold the Session is in SQL
3) Server which can be accessed by any server during the request process. Though
low performance, it is the most secure way of storing Sessions.
4) Following is the Code snippet illustrating how values are stored and retrieved
for Session.

21 - 65 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

//storing session values on server


protected void btnOk_Click(Object sender, EventArgs e)
{
Session[“LoginID”]=txtloginid.Text();
Response.Redirect(“Default.aspx”);
}

//retrieving the session values from server


protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Lblloginid.text = Convert.ToString(Session[“LoginID”]);
}
}
5) Advantages
It supports web farm and web garden configuration
Session state is persisted across application domain recycles and even IIS restarts
when session is maintained on different server.
6) Disadvantages
Requires serialization of objects.
7) Configuration settings
<sessionState mode="SQLServer"
sqlConnectionString="data source=server;user id=RaviW;password=technical"
cookieless="false" timeout="20" />

21.15.3.3 Cookieless Sessions in ASP.NET

To implement cookieless sessions there is need to change the web.config file.

Step 1 : Change the web.config file


1) Open Web.Config file
2) Add a <sessionState> tag under <system.web> tag
3) Add an attribute "cookieless" in the <sessionState> tag and set its value to "AutoDetect"
like below :
<sessionState cookieless="AutoDetect" regenerateExpiredSessionId="true"/>
OR
<sessionState cookieless="true"/>
<authentication mode="Forms">
<forms loginUrl="Login.aspx" protection="All" timeout="30"
name=".ASPXAUTH" path="/"
requireSSL="false" slidingExpiration="true"

21 - 66 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

defaultUrl="default.aspx"
cookieless="UseUri" enableCrossAppRedirects="true"/>
</authentication>
4) The possible values for "cookieless" attribute are,
AutoDetect
Session uses background cookie if cookies are enabled. If cookies are disabled, then
the URL is used to store session information.
UseCookie
Session always use background cookie. This is default.
UseDeviceProfile
Session uses background cookie if browser supports cookies else URL is used.
UseUri
Session always use URL.
"regenerateExpiredSessionId" is used to ensure that if a cookieless url is expired a
new new url is created with a new session. And if the same cookieless url is being
used by multiple users an the same time, they all get a new regenerated session url.

Step 2 : Change all the URL navigations in aspx files


<a runat="server" href="/test/page.aspx">Click</a>
To use absolute URLs, use the ApplyAppPathModifier method on the HttpResponse class.
The ApplyAppPathModifier method takes a string representing a URL and returns an
absolute URL that embeds session information.
<a runat="server"
href=”<% =Response.ApplyAppPathModifier("page.aspx")%>”

>Click</a>

Step 3 : Adjust all the URL navigations in aspx.cs files


If the URL is set in the code, then following code is added,
this.Tab2.Url = Response.ApplyAppPathModifier("Page.aspx");

Step 4 : Create HttpModule to rewrite incoming URL for enabling cross domain posts
using System;
using System.Collections.Specialized;
using System.Web;
using System.Web.SessionState;
using System.IO;
using System.Text;

namespace CustomModule

21 - 67 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

{
public sealed class CookielessPostFixModule : IHttpModule
{
public void Init (HttpApplication application)
{
application.EndRequest += new
EventHandler(this.Application_EndRequest);
}
private string ConstructPostRedirection(HttpRequest req,
HttpResponse res)
{
StringBuilder build = new StringBuilder();
build.Append(
"<html>\n<body>\n<form name='Redirect' method='post' action='");
build.Append(res.ApplyAppPathModifier(req.Url.PathAndQuery));
build.Append("' id='Redirect' >");
foreach (object obj in req.Form)
{
build.Append(string.Format(
"\n<input type='hidden' name='{0}' value = '{1}'>",
(string)obj,req.Form[(string)obj]));
}
build.Append(
"\n<noscript><h2>Object moved <input type='submit'
value='here'></h2>
</noscript>");
build.Append(@"</form>
<script language="'javascript'">
<!--
document.Redirect.submit();
// -->
</script>
");
build.Append("</body></html>");
return build.ToString();
}
private bool IsSessionAcquired
{
get
{
return (HttpContext.Current.Items["AspCookielessSession"]!=null &&
HttpContext.Current.Items["AspCookielessSession"].ToString().Length>0);
}
}
private string ConstructPathAndQuery(string[] segments)
{

21 - 68 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

StringBuilder build = new StringBuilder();

for (int i=0;i<segments.Length;i++)


{
if (!segments[i].StartsWith("(")
&& !segments[i].EndsWith(")"))
build.Append(segments[i]);
}
return build.ToString();
}
private bool IsCallingSelf(Uri referer,Uri newpage)
{
if(referer==null || newpage==null)
return false;
string refpathandquery = ConstructPathAndQuery(
referer.Segments);
return refpathandquery == newpage.PathAndQuery;
}
private bool ShouldRedirect
{
get
{
HttpRequest req = HttpContext.Current.Request;

return (!IsSessionAcquired
&& req.RequestType.ToUpper() == "POST"
&& !IsCallingSelf(req.UrlReferrer,req.Url));
}
}
private void Application_EndRequest(Object source, EventArgs e)
{
HttpRequest req = HttpContext.Current.Request;
HttpResponse res = HttpContext.Current.Response;
if (!ShouldRedirect) return;
res.ClearContent();
res.ClearHeaders();
res.Output.Flush();
char[] chr = ConstructPostRedirection(req,res).ToCharArray();
res.Write(chr,0,chr.Length);
}
public void Dispose()
{}
}
}

21 - 69 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

So as to make above statements effective, update web config as follows,


<httpModules>
<add type="CookielessPostFixModule, TechnicalModule"
name="CookielessPostFixModule" />
</httpModules>

21.15.4 DataList Control for Displaying Data


Concept

1. The DataList control contains a template that is used to display the data items within the
control.
Explanation

2. There are no data columns associated with this control, therefore templates are to be used
to display data. A DataList control is useless without templates.
3. Every column in a DataList control is rendered as a <span> element.
4. Templates
1) A template is a combination of HTML elements, controls and embedded server
controls and can be used to customize and manipulate the layout of a control.
2) A template has HTML tags and controls that can be used to customize the look and
feel of controls like Repeater, DataGrid, or DataList.
3) There are seven templates and seven styles for DataList control as listed below,
1) ItemTemplate
2) AlternatingItemTemplate
3) EditItemTemplate
4) FooterTemplate
5) HeaderTemplate
6) SelectedItemTemplate
7) SeparatorTemplate
4) Templates are grouped under three broad categories.
1) Item Templates
2) Header and Footer Templates
3) Separator Template
The ItemTemplate is the one and only mandatory template that one needs to use
when working with a DataList control.

21 - 70 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

5) DataList control supports the following features :


1) It supports for binding data source controls such as SqlDataSource,
LinqDataSource and ObjectDataSource
2) It do Directional rendering
3) It is Good for columns display.
4) It treats Item as cell
5) It is Updatable
6) It has Control over Alternate item
7) The Paging function needs handwriting.
6) Specifying templates of DataList control :
<asp:DataList id="dlCustomer" runat="server">
<HeaderTemplate>
...
</HeaderTemplate>
<ItemTemplate>
...
</ItemTemplate>
<AlternatingItemTemplate>
...
< /AlternatingItemTemplate>
<FooterTemplate>
...
</FooterTemplate>
</asp:DataList>

Customer ID Name Amount Area Code <- Header Template

502 Ravi 3000 28 <- Item Template

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

656 Avi 5000 31 <- Alternating Item Template

--- --- --- --- <- Separator Template

789 Sunil 6000 55

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

893 Sandy 7500 30

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

915 Lucky 8000 30

Total records 6 <- Footer Template

21 - 71 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

7) Customizing a DataList control at run time


1) At run time using the ListItemType property in the ItemCreated event the
DataList control can be customized, as shown below,
private void DataList1_ItemCreated(object sender, ...........System.Web.UI.WebControls.
{
switch (e.Item.ItemType)
{
case System.Web.UI.WebControls.ListItemType.Item :
e.Item.BackColor = Color.Blue;
break;
case System.Web.UI.WebControls.ListItemType. AlternatingItem :
e.Item.BackColor = Color.Red;
break;
case System.Web.UI.WebControls.ListItemType. SelectedItem :
e.Item.BackColor = Color.Green;
break;
default :
break;
}
}
8) The Styles that can be used with DataList control are,
1) AlternatingItemStyle
2) EditItemStyle
3) FooterStyle
4) HeaderStyle
5) ItemStyle
6) SelectedItemStyle
7) SeparatorStyle
These styles can be used to format the control, that is, format the HTML code that is
rendered.
9) Layouts of the DataList control can be used for formatting, that is, further
customization of user interface can be done. The available layouts are,
1) FlowLayout
2) TableLayout
3) VerticalLayout
4) HorizontalLayout
4) Flow or table format can be specified at design time by specifying the following in the
.aspx file.

21 - 72 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

RepeatLayout = "Flow"
or
DataList1.RepeatLayout = RepeatLayout.Flow
10) Example

Fig. 21.15.1 Datalist control example


//illustration of DataListControl
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace DataListDemo
{
public partial class DataListPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Creating a Table
DataTable dt = new DataTable();

21 - 73 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

//Adding Column in table


dt.Columns.Add("S_no", typeof(int));
dt.Columns.Add("S_Name", typeof(string));
dt.Columns.Add("S_Address", typeof(string));

//Adding Row in table


dt.Rows.Add(1, "Aryaveer", "Ahemdabad");
dt.Rows.Add(2, "Jeetraj", "Baroda");
dt.Rows.Add(3, "Dhruvin", "Surat");

//Binding DataSource i.e:Datatable to a Datalist


DataList1.DataSource = dt;
DataList1.DataBind();
}
}
}

21.15.5 ASP.NET Repeater Control

1) The Repeater control that render HTML to display the contents of a list or data source to
which they are bound.
2) It has no built-in layout or styles, so one must explicitly declare all layout, formatting and
style tags within the controls templates.
3) Every Repeater control must define an ItemTemplate.
4) Other optional templates can be used to customize the appearance of the list. They are,
1) ItemTemplate, is required by the Repeater control and it produces one row of output
for each data row.
2) AlternatingItemTemplate, is same as ItemTemplate and it renders for every other data
row.
3) SeparatorTemplate, render items between each data row like the HTML tags br, p, or
HR.
4) HeaderTemplate and FooterTemplate, render HTML immediately before and after all
the data rows have been rendered.
5) The Repeater control features,
1) It has List format.
2) There is no default output.
3) It can be added more control and complexity.
4) Item are treated as row.
5) There is no built-in support for paging, sorting and grouping capabilities, therefore,
Paging, Sorting and Grouping requires custom code writing.

21 - 74 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

6) Only the Web control that allows to split markup tags across the templates.
7) There is no built-in selection capabilities.
8) There is no built-in support for edit, insert and delete capabilities
9) There are no built-in layout or styles, need to declare all layout, formatting and style
tags explicitly wi01thin the control's templates
10) It strictly emits the markup specified in its templates.
Example

Fig. 21.15.2 Repeater control example


//Illustration of Repeater control
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Repeater
{
public partial class ListPage : System.Web.UI.Page
{
//Creating a Table
DataTable dt = new DataTable();

protected void Page_Load(object sender, EventArgs e)

21 - 75 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

{
//Adding Column in table
dt.Columns.Add("S_no", typeof(int));
dt.Columns.Add("S_Name", typeof(string));
dt.Columns.Add("S_Address", typeof(string));

//Adding Row in table


dt.Rows.Add(1, "Aryaveer", "Ahemdabad");
dt.Rows.Add(2, "Jeetraj", "Baroda");
dt.Rows.Add(3, "Dhruvin", "Surat");
LoadRepeater();
}

protected void LoadRepeater()


{
//Binding DataSource i.e:Datatable to a Datalist
Repeater1.DataSource = dt;
Repeater1.DataBind();
}

protected void btnSubmit_Click(object sender, EventArgs e)


{
dt.Rows.Add(Convert.ToInt32(txtRoll.Text), txtName.Text,txtAddress.Text);
LoadRepeater();
}
}
}

Two Marks Questions with Answers

Q.1 What is ASP.Net ?


Ans. : It is a framework developed by Microsoft on which we can develop new generation
web sites using web forms(aspx), MVC, HTML, Javascript, CSS etc. Its successor of
Microsoft Active Server Pages(ASP). Currently there is ASP.NET 4.0, which is used to
develop web sites. There are various page extensions provided by Microsoft that are being
used for web site development. Eg: aspx, asmx, ascx, ashx, cs, vb, html, XML etc.
Q.2 What is the difference between Server.Transfer and Response.Redirect ?
Ans. : In Server.Transfer page processing transfers from one page to the other page without
making a round-trip back to the client's browser. This provides a faster response with a
little less overhead on the server. The clients url history list or current url Server does not
update in case of Server.Transfer.

21 - 76 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

Response.Redirect is used to redirect the user's browser to another page or site. It


performs trip back to the client where the client's browser is redirected to the new page.
The user's browser history list is updated to reflect the new address.
Q.3 What are the different validators in ASP.NET ?
Ans. :
Required field Validator
Range Validator
Compare Validator
Custom Validator
Regular expression Validator
Summary Validator
Q.4 Where the viewstate is stored after the page postback ?
Ans. : ViewState is stored in a hidden field on the page at client side. ViewState is
transported to the client and back to the server, and is not stored on the server or any other
external source.
Q.5 What is the difference between web config and machine config ?
Ans. : Web config file is specific to a web application where as machine config is specific
to a machine or server. There can be multiple web config files into an application where as
we can have only one machine config file on a server.
Q.6 What is the use of virtual directory in asp .net ? AU : Dec.-17, 18, 19

Ans. : A virtual directory is a directory name that is specified in IIS and map to physical
directory on a local server's hard drive or a directory on another server (remote server). One
can use Internet Information Services Manager to create a virtual directory for an
ASP.NET Web application that is hosted in IIS.
The virtual directory name becomes part of the application's URL. It is a friendly name,
or alias because an alias is usually shorter than the real path of the physical directory and it
is more convenient for users to type. A virtual directory receives queries and directs them
to the appropriate backend identity repositories. It integrates identity data from multiple
heterogeneous data stores and presents it as though it were coming from one source.
Q.7 In which event, all the controls will be fully loaded ? AU : May-18

Ans. : Page load event guarantees that all controls are fully loaded. In asp.net web page
have life cycle from request to load and rendering page but controls are fully loaded in
Page_load event

21 - 77 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

Q.8 List out the server side state management options supported by ASP.NET.
AU : May-18

Ans. : State management is the technique that is used to maintain user and page information
over multiple requests while browsing the web.
HTTP is a stateless protocol. It does not store any information about user on web page. It
is a general requirement that information should be maintained while navigating the
website.
ASP.Net provides two ways to manage state on the server,
1. Application state - The information is global o the application and is available to all
users regardless of the identity of the user requesting the page.
Application object is used to store information at application level rather than user
level. All pages of the application can access the Application object. Application
variables are stored on a web server.
If Application object is being used, then one may face concurrency problem. To avoid
this problem the lock and unlock methods are used. Therefore if multiple thread requests
came for same data then only one thread can do the work.
Writing data to Application object
Application["Message"] = "Hello to all";
One can use Application object in a scenario where it is required to count the number of
visitors of web site. Application State variables are empty, when the process hosting the
application is restarted
2. Session state - user specific state that is stored on the server. It is available on a user
basis who is visiting the site. Session provides that facility to store information on
server memory not browse. It stores the user’s specific information. It can store any
type of object. For every user Session data store separately, means session is user
specific.
Session Events

There are two events that session object supports. These two events are handled in
Global.aspx file.
Session_Start
Session_End
Session Mode

In ASP.NET there are following session modes available,


InProc

21 - 78 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

StateServer
SQLServer
Custom
Off
By default, the Session state mode is InProc means Session state is stored in memory in
the same process as the ASP.NET process. So accessing data is very fast. Another
advantage is that there are no requirements of serialization to store data in InProc Session
Mode.
Session State Mode State Provider

InProc In-Memory Object

StateServer Aspnet_state.exe

SQLServer DataBase

Custom CustomProvider

In server side state management, all the information is stored in the user memory. Due
to this functionality, there are more secure domains at server side in comparison to client
side state management.
Session state and application state at a glance,
Application Session

It works at application level rather than user Session object is user specific.
level.

Application state is stored only in the memory Session state is stored in inProc and outProc
on the server.

Application state does not depends upon Session object depends upon cookie or can be
client's cookies cookieless.

Application state does not depend upon the Session state has scope to the current browser
current browser. only.
Q.9 Name the benefits provided by XML classes in .NET. AU : Dec.-18

Ans. : The .NET Framework provides a comprehensive and integrated set of classes that
enable to build XML-aware apps easily. The classes in the following namespaces support
parsing and writing XML, editing XML data in memory, data validation, and XSLT
transformation.
System.Xml

21 - 79 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

System.Xml.XPath
System.Xml.Xsl
System.Xml.Schema
System.Xml.Linq
The XML classes in the .NET Framework provide these benefits :
Productivity : LINQ to XML (C#) and LINQ to XML (Visual Basic) makes it easier
to program with XML and provides a query experience that is similar to SQL.
Extensibility : The XML classes in the .NET Framework are extensible through the
use of abstract base classes and virtual methods. For example, one can create a
derived class of the XmlUrlResolver class that stores the cache stream to the local
disk.
Pluggable architecture : The .NET Framework provides an architecture in which
components can utilize one another, and data can be streamed between components.
For example, a data store, such as an XPathDocument or XmlDocument object, can be
transformed with the XslCompiledTransform class, and the output can then be
streamed either into another store or returned as a stream from a web service.
Performance : For better app performance, some of the XML classes in the .NET
Framework support a streaming-based model with the following characteristics :
o Minimal caching for forward-only, pull-model parsing (XmlReader).
o Forward-only validation (XmlReader).
o Cursor style navigation that minimizes node creation to a single virtual node
while providing random access to the document (XPathNavigator).
For better performance whenever XSLT processing is required, one can use the
XPathDocument class, which is an optimized, read-only store for XPath queries designed
to work efficiently with the XslCompiledTransform class.
Integration with ADO.NET : The XML classes and ADO.NET are tightly integrated
to bring together relational data and XML. The DataSet class is an in-memory cache
of data retrieved from a database. The DataSet class has the ability to read and write
XML by using the XmlReader and XmlWriter classes, to persist its internal relational
schema structure as XML schemas (XSD), and to infer the schema structure of an
XML document.
Q.10 List down the events in life cycle of a web page. AU : May-19

Ans. : An Asp.Net page is run through a series of phases during its creation and disposal.
These include initialization, instantiating controls, restoring and maintaining state, running
event handler code, and rendering.

21 - 80 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

When a page is requested, it is loaded into the server memory , processed, and sent to the
browser. Then it is unloaded from the memory . At each of these steps, methods and events
are available, which could be overridden according to the need of the application. In general
terms, the page goes through the stages of the following :
Page request
Start
Initialization
Load
Postback event handling
Rendering
Unload
1. Page request : This stage occurs before the lifecycle begins. When a page is
requested by the user, ASP.NET parses and compiles that page.
2. Start : At this stage, the Request and Response objects are set. If the request is an old
request or post back, the IsPostBack property of the page is set to true. The UICulture
property of the page is also set.
3. Initialization : During page initialization, controls on the page are available and each
control's UniqueID property is set. A master page and themes are also applied to the
page if applicable. If the current request is a postback, the postback data has not yet
been loaded and control property values have not been restored to the values from
view state .
4. Load : During this phase, if page request is postback, control properties are loaded
with information.
5. Postback event handling : If the request is a postback (old request), the related
event handler is invoked.
6. Rendering : Before rendering, view state is saved for the page and all controls.
During the rendering stage, the page calls the Render method for each control,
providing a text writer that writes its output to the OutputStream object of the page's
Response property.
7. Unload : At this stage the requested page has been fully rendered and is ready to
terminate.at this stage all properties are unloaded and cleanup is performed.
Each time an ASP.NET page is requested, the same process is repeated, from Page
request to Unload. By understanding the inner workings of the ASP.NET page process,
writing and debugging the code will be much easier and effective.

21 - 81 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

Q.11 How to add the server-side controls to web form ? AU : May-19

Ans. : The server side control must have runat=’server’ attribute tag. All .net controls are
server side controls where as all HTML controls are client side control.
Server Side Controls can be directly accessible from code behind programming page.
The Client Side controls are not directly accessible on code behind page. One can access
them with other methods.
If it is required to add some control on web page, the Toolbox on the left side in Visual
Studio can be used. All the server side controls are placed in Toolbox panel.
Open Toolbox and just select control drag and drop control to web form where it is
required. If Toolbox not visible in visual studio, got to View menu select Toolbox option to
visible Toolbox in Visual Studio OR press “Ctrl + w + x” key to add Toolbox in visual
studio
The other method of adding server controls to an application is to add manually.
VS.NET writes the code in the background for developer when developer drop a control
from the toolbox to Web form.
To add server controls manually, a text file needs to be created and save it with an .aspx
extension .NET utilizes XML tags to write server controls. A tag should be XML syntax.
Every ASP.NET control starts with asp, and a control name. For example, the following
line a text box control :
<asp: textbox id=TextBox1 runat = "Server" Text =" " text =" "> </asp:textbox>
In this line, a text box server control is created. Event control has unique ID. In this
sample the ID is TextBox1. The runat ="Server" attribute represents that the control will
run on the server.
The following code shows that how one can write the same code without the closing
tag :
<asp:textbox id = Textbox1 runat ="server" />
Q.12 What is the razor syntax for C# ? AU : Dec.-19

Ans. : Razor is one of the view engine supported in ASP.NET MVC. Razor allows to write
mix of HTML and server side code using C#.
Main Razor Syntax Rules for C#
1. Razor code blocks are enclosed in @{ ... }
2. Inline expressions (variables and functions) start with @
3. Code statements end with semicolon
4. Variables are declared with the var keyword
5. Strings are enclosed with quotation marks

21 - 82 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

6. C# code is case sensitive


7. C# files have the extension .cshtml

Long Answered Questions

Q.1 Explain ASP .NET page life cycle. (Refer section 21.10)
Q.2 How ASP .NET application is configures ? (Refer section 21.7)
Q.3 Explain ASP .NET page syntax. (Refer section 21.8)
Q.4 What are web services ? (Refer section 21.5)
Q.5 Explain any 2 ASP .NET controls in detail. (Refer section 21.12)
Q.6 Show the steps for creating the virtual directory and configuration for ASP.NET
applications. (Refer section 21.11) AU : Dec.-17, Marks 16
Q.7 Illustrate the following :
i) Virtual directory. (Refer section 21.11)
ii) Session management techniques. (Refer section 21.15) AU : May-18, Marks 13
Q.8 Develop an ASP.Net Web application for Bus Ticket Reservation System -
Ticket Availability, Ticket Booking and Ticket cancellation.
AU : May-18, Marks 15
Q.9 Explain briefly about the following features of ADO.Net
Validating Controls (Refer section 21.11) AU : Dec.-18, Marks 6
Q.10 Explain in detail about Session Management Techniques and Creation of Virtual
directory for an Web application using ASP.NET.
(Refer sections 21.11 and 21.15) AU : Dec.-18, Marks 13
Q.11 Develop an ASP.Net Web application for Online Hotel Reservation System
Availability, Booking and Cancellation. (Refer section 21.12)
AU : Dec.-18, Marks 15
Q.12 Explain ASP.NET Application Life Cycle. (Refer section 21.1)
AU : May-19, Marks 13
Q.13 Analyse the three different aspects of Error handling in ASP.NET.
(Refer section 21.12) AU : May-19, Marks 15
Q.14 With examples explain the session management techniques.
(Refer section 21.15) AU : Dec.-19, Marks 13
Q.15 With examples explain any 7 commonly used web.config tags.
(Refer section 21.11) AU : Dec.-19, Marks 13

Core ASP .NET and ASP .NET Web Forms ends …

21 - 83 C# and .NET Programming


Core ASP .NET and ASP .NET Web Forms

21 - 84 C# and .NET Programming


C# and .NET Framework - Introduction

Syllabus : Windows Communication Foundation (WCF).

Section No. Topic Name Page No.


22.1 WCF - Introduction 22 - 2

22.2 WCF Services 22 - 2

22.3 WCF - Fundamental Concepts 22 - 3

22.4 WCF Communication Model 22 - 4

22.5 WCF Architecture 22 - 6

22.6 WCF Application Components and Programming 22 - 10

22.7 WCF Advantages 22 - 12

22.8 WCF and Web Services Comparative Study 22 - 13

Two Marks Questions with Answers 22 - 14

Long Answered Questions 22 - 15

22 - 1 C# and .NET Programming


WCF - Windows Communication Foundation

22.1 WCF - Introduction

1. Windows Communication Foundation (WCF), is a framework for building, configuring,


and deploying network-distributed services. Earlier WCF was known as Indigo. WCF was
released for the first time in 2006 as a part of the .NET framework with Windows Vista,
and then got updated several times. WCF 4.5 is the most recent version that is now
widely used.
2. WCF enables hosting services in any type of operating system process.
3. WCF is primarily implemented as a set of classes that correspond to the CLR in the .NET
framework. WCF allows .NET application developers to build service-oriented
applications. The WCF client uses Simple Object Access Protocol (SOAP) to
communicate with the server. The client and server are independent of the operating
system, hardware and programming platform, and communication takes place at a high
level of abstraction.
4. The elementary feature of WCF is interoperability. It is Based on the concept of
message-based communication.
5. The mechanism of WCF operation is similar to ASP.NET Web Services (WS). Clients
can invoke and consume multiple services, and a single service can be consumed by
multiple clients.
6. WCF is designed to communicate with other non-WCF applications in addition to the
various successors and predecessors of Microsoft technology.

22.2 WCF Services

A WCF service can be visualized as follows

Fig. 22.2.1 WCF services

22 - 2 C# and .NET Programming


WCF - Windows Communication Foundation

22.3 WCF - Fundamental Concepts

Fundamental Concepts of WCF

1. Message
Message is a communication unit that has body and other several parts. Message
instances are sent as well as received for all types of communication between the
client and the service.
2. Endpoint
1. Endpoint defines the address where a message is to be communicated that is sent
or received. It also specifies the communication mechanism to describe how the
messages will be sent along with defining the set of messages.
2. A structure of an endpoint
1. Address
1. Like a webservice, a WCF service also provides a URI which can be used by
clients to get to the WCF service. This URI is called as the Address of the
WCF service. This indicates "where to locate the WCF service?".
2. Address is specified as a Uniform Resource Identifier (URI) that specifies the
exact location to receive the messages, which has standard format as,
‘ ://domain[:port]/[path]’.
2. Binding
1. Once WCF service is located, communication with the service (protocol wise)
is next step do. The binding is what defines how the WCF service handles the
communication. It could also define other communication parameters like
message encoding, etc. Binding indicates "how to communicate with the WCF
service?".
2. Binding defines the way an endpoint communicates with help of certain
elements. The binding states the protocols used for communication (TCP,
HTTP, etc), the format of message encoding, and the protocols related to
security as well as reliability.
3. Contracts
1. Contract is what defines the public data and interfaces that WCF service
provides to the clients.
2. Contract is a collection of operations that specifies what functionality the
endpoint exposes to the client. It generally consists of an interface name.

22 - 3 C# and .NET Programming


WCF - Windows Communication Foundation

3. Hosting
WCF services hosting is carried out through available options like self-hosting or
server specific IIS hosting, and WAS hosting etc.
4. Metadata
WCF services use metadata to describe how to interact with the service's endpoints.
Metadata are the communication details for a WCF service is generated automatically
when its option is enabled. By inspecting service and its endpoints the metadata is
collected.
5. WCF Client
WCF client is a application that uses the WCF services. This can be hosted by any
application, even the one that does service hosting.
6. Channel
Channel is a communication medium through which a client communicates with a
service.
7. ‘Simple Object Access Protocol’ (SOAP)
‘Simple Object Access Protocol’, SOAP is an XML document comprising of a header
and body section. SOAP web services uses XML as a mechanism for exchanging of
information (one way) between the two programs (end points) over any transport layer
protocol.

22.4 WCF Communication Model

WCF follows a Client-Server Architecture. Communication between Client and Server


are established using Endpoints exposed by the WCF Service. Endpoints are nothing but
the locations defined by a service through which a message can be sent and received. The
service may have multiple end points.

Fig. 22.4.1 WCF communication model-Client-Server Architecture

22 - 4 C# and .NET Programming


WCF - Windows Communication Foundation

A communicating application needs to be developed so as to share/exchange the data or


sharing the logic with another application in the network. This communication can be of
the following two types,
1. Over an intranet (the same Network/Platform, in other words, .NET application to
.NET application)
2. Over the internet (cross-platform maybe ASP.NET to J2EE application)
Suppose a .NET Software with n-tier architecture is being developed in which a Windows
Forms client needs to communicate with the server in the same network. In such case
.NET Remoting can be used for communication between client and server.
Suppose, the application is already developed and needs to expose some business logic to
another J2EE application then this J2EE application is supposed to the .NET application's
logic over the WWW. In such a case a new ASP.NET Web Service is required to be
developed to expose the logic. The following Fig. 22.4.2 depicts the limitation of .NET
Remoting,

Fig. 22.4.2 Limitation of .NET remoting service over network

WCF helps to overcome this kind of scenario since a WCF Service can be used as a .NET
Remoting Component and ASP.NET Web Services as well as illustrated in the below
Fig. 22.4.3.

Fig. 22.4.3 .NET remoting components and ASP .NET web services

22 - 5 C# and .NET Programming


WCF - Windows Communication Foundation

22.5 WCF Architecture

WCF has a layered architecture that support for developing various distributed
applications.

Fig. 22.5.1 WCF architecture

22.5.1 WCF Contracts

The contracts layer is next to the application layer and contains information similar to that
of a real-world contract that specifies the operation of a service and the kind of accessible
information it will make. Contracts are of five types namely,
1. Service contract - Service contract gives the information to the client as well as to the
outer world about the offerings of the endpoint, and the protocols to be used in the
communication process. A service contract defines the operations which are exposed by
the service to the outside world. A service contract is the interface of the WCF service and
it tells the outside world what the service can do. It may have service-level settings, such
as the name of the service and namespace for the service.

22 - 6 C# and .NET Programming


WCF - Windows Communication Foundation

2. Data contract - The data exchanged by a service is defined by a data contract in which
both the client and the service has to be in agreement with the data contract. A data
contract defines the data type of the information that will be exchange between the client
and the service. A data contract can be used by an operation contract as a parameter or
return type, or it can be used by a message contract to define elements.
3. Message contract - Message contract controls the data contract. It primarily does the
customization of the type formatting of the SOAP message parameters. When an
operation contract required to pass a message as a parameter or return value as a message,
the type of this message will be defined as message contract. A message contract defines
the elements of the message (like as Message Header, Message Body), as well as the
message-related settings, such as the level of message security. Message contracts give
complete control over the content of the SOAP header, as well as the structure of the
SOAP body.
4. Policy and binding - Communication pre-conditions for with a service are defined by
policy and binding contract which the client needs to follow.
5. Fault contract - A fault contract defines errors raised by the service, and how the service
handles and propagates errors to its clients.
22.5.2 WCF - Service Runtime

The service runtime layer is below the contracts layer which specifies the various service
behaviors that occur during runtime. Following are the behaviors that can undergo
configuration and come under the service runtime.
1. Throttling Behavior - Manages the number of messages processed during
communication. ServiceThrottlingBehavior class exposes properties like
MaxConcurrentCalls, MaxConcurrentInstances, MaxConcurrentSessions. These
properties are very useful for WCF services perfromance. Using this one can decide how
many instances or sessions can be created at application level
2. Error Behavior - It defines the result of any internal service error occurrence. It allows
decide how to handle errors or exceptions occured at WCF layer. FaultContract are widely
used to handle WCF exceptions.
3. Metadata Behavior - Specifies the availability of metadata to the outside world. It
specify whether service metadata is available to clients. By adding endpoint and
configuring or adding programmatically serviceMetadata element of behavior element in
config file one can enable or disable metadata to clients.

22 - 7 C# and .NET Programming


WCF - Windows Communication Foundation

4. Instance Behavior - It defines the number of instances that needs to be created to make
them available for the client. It decides how objects are created and refers to the life time
of the service object. Whenever clients make request, the runtime will create service
objects to provide the response. Through instancing one can control how long this service
instance wants to be retained. By setting InstanceContextMode property of
ServiceBehavior one can control instance behavior. One can set it as PerCall, PerSession
or Single.
5. Transaction Behavior - This enables a change in transaction state in case of any failure.
It enables WCF operations to be complies with ACID (Atomic, Consistency, Isolation,
Durability) properties and execute operations as single logical unit where either all or
none of the statements get executed. Transactions work with WCF operations however it
also depend on how service is configured and what binding is used.
6. Dispatch Behavior - It controls the way by which a message gets processed by the
infrastructure of WCF. It monitors how a message is processed to and from WCF
environment. Here message compression and optimized file type encoding can be used.
7. Concurrency Behavior - Functions that run parallel during a client-server
communication are controlled by this behavior.
8. Parameter Filtering - The process of validation of parameters to a method before it gets
invoked is handled by parameter filtering.
22.5.3 WCF - Messaging

1. WCF messaging provides a unified programming model and flexibility for presenting data
and messages exchanges. Messaging layer has many channels, those channels are called
as Channel Stack. Each channel involves in some or other way in processing of message
like authentication, sending or recieving messages to and from endpoint. Messaging layer
mainly deals with the message content to be communicated between two endpoints.
2. Channels are included in System.ServiceModel.Channels namespace.
3. A set of channels form a channel stack and the two major types of channels that comprise
the channel stack are the following ones :
1. Transport Channels - Transport channels are present at the bottom of a stack and are
accountable for sending and receiving messages using transport protocols like HTTP,
TCP, Peer-to-Peer, Named Pipes, and MSMQ. These include message Encoding and
Transport Protocol. Handles sending and receiving message from network.
2. Protocol Channels - Protocol channels are Transaction Protocol, Reliable Messaging
Protocol and Security Protocol. Implements SOAP based protocol by processing and
possibly modifying message. E.g. WS-Security and WS-Reliability. These are present
at the top of a stack, these channels also known as layered channels.

22 - 8 C# and .NET Programming


WCF - Windows Communication Foundation

22.5.4 WCF - Activation and Hosting


The last layer of WCF architecture is the place where services are actually hosted or can be
executed for easy access by the client. WCF service can be host in multiple ways and activate
for clients. Every method for hosting comes with advantages and disadvantages. While
choosing hosting environment for WCF service one should consider - what protocols are used,
what kind of security is required, how service should be activated for clients.
This is done by various mechanisms discussed below.
1. IIS (Internet Information Service) - It host only HTTP/HTTPs based WCF services
while using IIS 6.0 or previous versions. Hosting in IIS gives feature like "activation on
demand". The service code is not in memory for all time and gets instantiated whenever
first request comes in.
2. Windows activation service - It is the new process activation method that comes with IIS
7.0. One can host WCF service and have HTTP and non HTTP (TCP or netNamedPipe
protocols) based message based activation.
3. Self-hosting - WCF service can be self hosted as console application, Win Forms or
WPF application with graphical UI. Self-hosting might look like a lot of work - but it does
give the best flexibility. This mechanism offers amazing flexibility in terms of choosing
the desired protocols and setting own addressing scheme. One can introduce own custom
ServiceHost if required to do some extra work to host services, and so on.
4. Windows service - WCF service objects lifetime will be controlled by Service Controller
Manager(SCM) of Windows. SCM is available for all versions of Windows. Advantages
of hosting WCF service in Windows Service includes service remains activated and
available for clients as there is no runtime activation, any type of protocols can be used,
more security through Windows Identity.
5. Advantages of hosting WCF Services in IIS as compared to self-hosting
There are two main advantages of using IIS over self-hosting,
1. Automatic activation : IIS provides automatic activation that means the service is not
necessary to be running in advance. When any message is received by the service it
then launches and fulfills the request. But in case of self hosting the service should
always be running.
2. Process recycling : If IIS finds that a service is not healthy that means if it has
memory leaks etc, IIS recycles the process. For every browser instance, a worker
process is spawned and the request is serviced. When the browser disconnects the
worker, process stops and all the information is lost. IIS also restarts the worker
process. By default, the worker process is recycled at around 120 minutes. So why
does IIS recycle then – the reason - by restarting the worker process it ensures any bad
code or memory leak do not cause issue to the whole system.

22 - 9 C# and .NET Programming


WCF - Windows Communication Foundation

In case of self-hosting both the above features, should be handled by developer by writing
appropriate code. That is why IIS is the best option for hosting services until there is a need of
customization.

22.6 WCF Application Components and Programming

There are three parts of WCF Application from usage point of view, namely,
WCF Service - What is the service and what it is providing.
WCF Service host - Where is the Service hosted.
Service Client - Who is the client of the Service.
Main components of WCF application from programming point of view

There are three main components to be defined as a part of WCF application namely,
Service class.
Hosting environment
End point

Step 1 : A service class


1. First create a Winfx service project. For developing simple first a service class is to be
created. In this project, add a new class and name it as per requirement say,
"serviceDemo.cs". This class will have the core implementation and this is the class,
which has all the action. The service class is the one which has to be exposed to the
external client. The Service Contract attribute is used to mark it as a service class.
2. Service Contract attribute define saying which application interface will be exposed as a
service.
3. The next thing to note is the Operation Contract attribute. Operation Contract dictates
which methods should be exposed to the external client using this service. It defines
individual exchange or request and replies. Now defined necessary method say
methodServiceDemo, which will be used by the end client to get the total cost results.
4. The next thing to note is the Data Contract attribute. In the previous two steps, class as a
service is exposed by using Service Contract and methods by using Operation Contract.
Every operation will definitely do some kind of data transfer.
5. Data Contract attributes defines which type of complex data will be exchanged between
the client and the service. They determine which parameters to be serialized.
6. When simple data types like int, bool are used it is not necessary to mark the data contract
attribute. Because there will be always a matching types on the client. However, complex

22 - 10 C# and .NET Programming


WCF - Windows Communication Foundation

structures are required to be defined in a data contract. Remember data contract define
how this data will be passed during transmission. In short data contract attribute define
how data will be serialized will transmission.
7. Data contract is all about serialization and there is need to import,
System.Runtime.Serialization namespace.
8. Now the service class method methodServiceDemo needs to be implemented. It just
returns a simple string with product name and the total cost of all products.

Step 2 : Hosting the service


1. Once the service class is done next step is to host this service. There are various ways of
hosting a WCF service as discussed in below section.
2. Hosting the WCF service needs two things one is the config file and second is the hosting
code on startup.
3. If the service needs to be hosted in own process then it requires its own windows
application.
4. For hosting the service in process of application make changes in the App.config file.
5. In the configuration section, add a new section <system.serviceModel>. The most
important part of <system.serviceModel> is the endpoint tag. The End handles three
aspects Where, What and How. In short 'where' is the service, 'what' the contract of
the service is and 'how' to communicate with the service.
6. In the program, the contract attribute defines the interface and binding says that the end
clients can communicate using "HTTP" protocol. In Static void Main method, an object of
Service Host class is created and the open method is used to host the service. The URI
object is used to define the address where the service will be hosted.
7. After compilation of the project the service is up and running and ready to serve any WCF
client and this message is shown in the command window.

Step 3 : To develop the consumer of the service


1. Microsoft has provided a decent automation to generate the client through svcuti. It can be
used as below,
Svcutil <Service hosted URI>
In the above command <Service Hosted URI> is the URI on which the service is
hosted. Once this command is run against the URI it will generate two files one is the
config file and the other is the proxy. As a result of run two files are generated
getServiceDemoService.cs and output.config file. With the help of these two files, the
client is developed.

22 - 11 C# and .NET Programming


WCF - Windows Communication Foundation

2. For the client code add output.config and getServiceDemoService.cs files to the client
project. The client code need to be written so as to call the proxy who in turn will call the
service hosted.
3. Client code is simple in which the object of the data structure is created and its values are
set. Then the object of the service is created and a call is given to methodServiceDemo
method.
If everything is compiled, the client and server are run the output of service method can
be seen on client side.
To summarize, creating a WCF service and a client in the Visual Studio IDE
requires six steps as mentioned below,

1. Defining a WCF Service Contract specifies the operations supported by a service.


Contracts are created by defining a C++, C#, or Visual Basic interface, and each method
in the interface must correspond to a specific service operation. Each interface must have
the ServiceContractAttribute applied to it, and each operation must have the
OperationContractAttribute applied, otherwise they will not be exposed.
2. Implementing a Service Contract is done by creating a class that implements the user-
defined interface for the service.
3. Hosting and Running a WCF service consists of the following tasks : creating an URI
instance for the base address of the service, hosting the service, adding an endpoint that
exposes the service, enabling the metadata exchange, and opening the service host.
4. Creating a Client includes generating a proxy to the service and a configuration file using
the command-line Service Model Metadata Utility Tool.
5. Configuring a client consists of specifying the endpoint that the client uses to access the
service. An endpoint has an address, a binding and a contract, and each of these must be
specified in the process of configuring the client.
6. Using a client actually calls the service from the generated proxy and closes the client
once the operation call is completed.

22.7 WCF Advantages

1. It is interoperable with respect to other services. This is in sharp contrast to .NET


Remoting in which both the client and the service must have .Net.
2. WCF concepts can run on any browser.
3. WCF is one of the fastest communication technologies and offers excellent performance
compared to other Microsoft specifications. For improving communication, transmission

22 - 12 C# and .NET Programming


WCF - Windows Communication Foundation

speed needs to be optimized. This is achieved by transmitting binary-coded XML data


instead of plain text to decrease latency.
4. WCF can be configured to work independently of SOAP and use RSS (Really Simple
Syndication) instead.
5. WCF services offer enhanced reliability as well as security in comparison to ASMX
(Active Server Methods) web services.
6. Implementing the security model and binding change in WCF do not require a major
change in coding. Few configuration changes are required to satisfy the constraints.
7. WCF has built-in logging mechanism whereas in other technologies, it is essential to do
the requisite coding.
8. WCF has integrated AJAX and support for JSON (JavaScript object notation).
9. It offers scalability and support for up-coming web service standards.
10. It has a default security mechanism which is extremely robust.
11. Object life-cycle management and distributed transaction management are applicable on
any application developed using WCF. WCF uses WS specifications to provide reliability,
security and transaction management.
12. Messages can be queued using persistence queuing. As a result, no delays occur, even
under high traffic conditions.

22.8 WCF and Web Services Comparative Study

(1) Web services provide an efficient way of facilitating communication between applications
over HTTP only.
(2) The web services provide simplex communication and there is no way to have half duplex
or full duplex communication using web services.
(3) Windows Communication Foundation (WCF) resolves HTTP only and simplex
communication issues of web services that is WCF supports other communication
protocols and even duplex communication. With WCF, once service is defined and
configured, it can be used via HTTP, TCP, IPC, and even Message Queues.
(4) Web services work in an stateless fashion over HTTP and are hosted inside a web server
like IIS. WCF can be hosted in many ways inside IIS, inside a Windows service, or even
self hosted.
(5) WCF supports multiple bindings HTTP, WSHTTP, TCP, MSMQ where as ASP.NET
Web Services supports only HTTP binding.
(6) WCF supports Atomic Transactions that are not supported by ASP .NET web services.

22 - 13 C# and .NET Programming


WCF - Windows Communication Foundation

(7) By default, WCF uses SOAP for sending and receiving the messages. But WCF can
support any kind of message format, not just SOAP. ASP.NET Web Services can send
and receive messages via the SOAP only.
(8) The System.Runtime.Serialization.DataContract and System.Runtime. Serialization.
DataMember attributes of the WCF's System.Runtime.Serialization assembly can be
added for .NET types to indicate that instances of the type are to be serialized into XML,
and which specific fields or properties of the type are to be serialized. ASP.NET Web
Services uses XmlSerializer to translate the XML data (Message Send or received) into
.NET objects.
(9) There are other differences between WCF and web services related to instance
management, sessions, data representation and serialization.

Two Marks Questions with Answers

Q.1 What are advantages of WCF ?


Ans. : Advantages of WCF
1. Service Oriented.
2. Location Independent.
3. Language Independent.
4. Platform Independent.
5. Support Multiple operation.
6. WCF can maintain transaction like COM+ Does.
7. It can maintain state.
8. It can control concurrency.
9. It can be hosted on IIS, WAS, Self hosting, Windows services.
Q.2 What are the various ways of hosting a WCF service ?
Ans. : There are four ways of hosting a WCF service.
Self-Hosting
Windows services hosting
IIS hosting
Windows Activation Services hosting (WAS)
Q.3 What is WCF Data Service ?
Ans. : WCF Data Services uses OData (Open Data Protocol) protocol for querying or
manipulating the data. WCF Data Services is built on top of WCF REST Services. It is a
RESTful service to support CRUD operations on the database using the HTTP protocol. It
22 - 14 C# and .NET Programming
WCF - Windows Communication Foundation

supports all database operations using URI. DATA protocol can expose data from the
relational database, File systems, Web sites, services etc. It supports XML or JSON format
for exposing the data.
Q.4 Explain how does WCF works ?
Ans. : WCF follows the "Software as a Service" model, where all units of functionality are
defined as services. For communication, each point is a portal or connection either with
the client or other services. It is a program that exposes a collection of endpoints.
Q.5 Mention what is the endpoint in WCF and what are the three major points in
WCF ?
Ans. : Every service must have an address that determines where the service is located,
contract that defines what the service does and binding that tells how to communicate with
the service.
Address : It specifies the location of the service which will be like
http://Myserver/Myservice. To communicate with our service client it will use this
location
Contract : It specifies the interface between the server and client. It's a simple
interface with some attribute
Binding : It decides how two parties will communicate with each other in terms of
transport and encoding and protocols

Long Answered Questions

Q.1 Discuss WCF architecture. (Refer section 22.5)


Q.2 What are various WCF services ? (Refer section 22.2)
Q.3 Explain WCF communication model. (Refer section 22.4)
Q.4 What is service runtime ? (Refer section 22.6)
Q.5 What are contracts in WCF ? (Refer section 22.3)

WCF - Windows Communication Foundation ends...

22 - 15 C# and .NET Programming


WCF - Windows Communication Foundation

Notes

22 - 16 C# and .NET Programming


C# and .NET Framework - Introduction

Syllabus : Introduction to Web Services.

Section No. Topic Name Page No.


23.1 Web Services 23 - 2

23.2 SOAP and Web Services 23 - 3

23.3 Creating and Consuming Web Service 23 - 4

23.4 Passing and Returning DataSets from Web Services 23 - 10

Two Marks Questions with Answers 23 - 21

Long Answered Questions 23 - 21

23 - 1 C# and .NET Programming


Introduction to Web Services

23.1 Web Services AU : May-19


Concept
1. A "web service is the communication platform between two different or same platform
applications that allows to use their web method." By different or same platform it means
that, one can create a web service in any language, such as Java or other languages and
that the language web service can be used in a .Net based application and also a .Net web
service or in another application to exchange the information.
Explanation
2. Web Service is an application that is designed to interact directly with other applications
over the internet. The Web serivce consumers are able to invoke method calls on remote
objects by using SOAP and HTTP over the Web.
3. WebService is language independent and Web Services communicate by using standard
web protocols and data formats, such as
HTTP XML SOAP
4. Web Service messages are formatted as XML, a standard way for communication
between two incompatible system. This message is sent via HTTP, so that they can reach
to any machine on the internet without being blocked by firewall.
5. Web method : It is a the method in web services always start with [webMethod]
attributes, it means that it is a web method that is accessible anywhere, the same as my
web application.
6. Web Service Examples
Web services can be used for, a live match score card display, latest news headline
updates, Weather Reporting, current rupees rate and many other tasks.
7. Web Services in application
Application of Asp.net Web Service in different types of applications

Fig. 23.1.1 Web services in application

23 - 2 C# and .NET Programming


Introduction to Web Services

23.2 SOAP and Web Services

Concept

1. SOAP (Simple Object Access Protocol) is a remote function call that invokes method
and execute them on Remote machine and translate the object communication into XML
format. SOAP are way by which method calls are translate into XML format and sent via
HTTP.
Explanation
2. SOAP is a standard XML based protocol that communicated over HTTP. SOAP is
message format for sending messaged between applications using XML. It is
independent of technology, platform and is extensible too.
3. SOAP and XML provide the connectivity between applications.
4. Below web service to work properly ASP.NET framework takes care of doing the low
level SOAP and XML calls.

Fig. 23.2.1 Role of SOAP in web service invocation

WSDL
WSDL stands for Web Service Description Language, a standard by which a web service
can tell clients what messages it accepts and which results it will return. WSDL contains
every detail regarding using web service and Method and Properties provided by web
service and URLs from which those methods can be accessed and Data Types used.
UDDI
UDDI allows to find web services by connecting to a directory.
Discovery or .Disco Files
Discovery files are used to group common services together on a web server. Discovery
files .Disco and .VsDisco are XML based files that contains link in the form of URLs to
resources that provides discovery information for a web service. Disco File contains URL for
the WSDL, URL for the documentation and URL to which SOAP messages should be sent.

23 - 3 C# and .NET Programming


Introduction to Web Services

23.3 Creating and Consuming Web Service

Part I Developing Web service

Step 1 : Creating Web Service


1. "Start" - "All Programs" - "Microsoft Visual Studio 2010"
2. "File" - "New Project" - "C#" - "Empty Web Application" (to avoid adding a master
page)
3. Provide the web site a name such as "firstwebservice" and specify location

Fig. 23.3.1 Selecting web service

4. Then right-click on Solution Explorer - "Add New Item" - the web service templates pop
up.

Fig. 23.3.2 Adding web service

23 - 4 C# and .NET Programming


Introduction to Web Services

5. Select Web Service Template and click on add button. After that the Solution Explorer
look like as,

Fig. 23.3.3 Selecting web service template

6. A website of type ASP.NET Web service provides a skeleton to write the web service
code (which is written in Webservice.cs).
//Illustration of web service that provides arithmetic operations services to other
applications. //User application need to provide 2 numbers and then performs the
requested operation on the // //numbers. Operations can be Addition, Subtraction and
Multiplication.
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
///<summary>
/// Summary description for UtilityWebService
///</summary>

23 - 5 C# and .NET Programming


Introduction to Web Services

[WebService(Namespace = "http://tempuri.or g/")]


[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Service : System.Web.Services.WebService
{
public Service () {

//Uncomment the following line if using designed components


//InitializeComponent();
}

[WebMethod]
public string HelloWorld() {
return "Hello World";
}
}
Points to note

1) The attribute WebService tells that this class contains the code for web service.
2) The namespace is what is used to identify the web service.
3) The WebMethod attribute specifies the methods which web service is providing.
Step 2 : Write code for the functions in webservice.

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class MathOperationService : System.Web.Services.WebService
{
public MathOperationService ()
{
//Uncomment the following line if using designed components
//InitializeComponent();
}

[WebMethod]
public int Add(int n1, int n2)
{
return n1+n2;
}

[WebMethod]
public int Subtract(int n1, int n2)
{
return n1 – n2;
}

23 - 6 C# and .NET Programming


Introduction to Web Services

[WebMethod]
public int Multiply(int n1, int n2)
{
return n1 * n2;
}
}

Step 3 : Create the WebService binary, using following command on Visual Studio
Command Prompt.

>CSC /t:library /out:ArithmeticServiceImpl.dll App_code\ MathOperationService.cs


This creates a DLL file for the web service. This DLL file can be used by any client
application by using the SOAP protocol.

Step 4 : To test and view the web service working over the SOAP protocol, the service.asmx
file can be viewed in the browser which would show what functions web service
exposes. The XML file contains the service description.

Fig. 23.3.4 Testing web service

23 - 7 C# and .NET Programming


Introduction to Web Services

Fig. 23.3.5 Testing web service

Fig. 23.3.6 Testing web service

23 - 8 C# and .NET Programming


Introduction to Web Services

Fig. 23.3.7 Web service output

Part II Consuming a WebService

1. There are three ways a Webservice can be consumed namely,


1. Using HTTP-POST method.
The HTTP-Post method can be used by calling .asmx file directly from client. For this
directly the method name and the parameter names are used from input fields on form.

<html>
<body>
<form action="http://localhost/.../Service.asmx/Multiply" method="POST">
<input name="n1"></input>
<input name="n2"></input>

<input type="submit" value="Enter"> </input>


</form>
</body>
</html>
Upon this form; the web service's method will be called.
2. Using XMLHttp that will use SOAP to call the service
In this method XMLHttp over SOAP is used to access the webservice. This method is
used when one want to use the web service using complete set of SOAP
functionality.

23 - 9 C# and .NET Programming


Introduction to Web Services

3. Using WSDL generated proxy class


In this method a Proxy class for the web service is generated and this proxy class is
used further. This method is more type safe and less error prone as once the proxy
class generated, it handles all the SOAP messages, serialization and ensure that all
the problems are dealt at the compile time instead of runtime. To use this service,
there is need to do "Add Web reference" and add the webservice reference.
Alternatively WSDL.exe, a command line tool, can also be used to generate the
proxy classes and use these classes. "Add web Reference" is also using the same
WSDL.exe to generate the proxy classes.
2. Writing code to use the proxy class to perform the operations, the proxy class will
then communicate to the web service using SOAP and get back the results to us.
protected void Button1_Click(object sender, EventArgs e)
{
if (txtn1.Text != string.Empty
&& txtn2.Text != string.Empty)
{
try
{
int n1 = Convert.ToInt32(txtn1.Text);
int n2 = Convert.ToInt32(txtn2.Text);

ArithmeticService.Service service = new ArithmeticService.Service();

Label1.Text = "Addition " + service.Add(n1, n2).ToString();


Label2.Text = "Difference " + service.Subtract(n1, n2).ToString();
Label3.Text = "Multiplication " + service.Multiply(n1, n2).ToString();
}
catch(Exception)
{
throw;
}
}
}
3. Running the website

23.4 Passing and Returning DataSets from Web Services

AU : May-18, Dec.-18

23.4.1 ADO .NET DataSets

With .NET, one can easily couple Web Services with .NET's new data services to
provide a powerful data delivery mechanism that works over the Web, making it

23 - 10 C# and .NET Programming


Introduction to Web Services

possible to build distributed applications that work easily without a local data store.
Web Services and ADO.NET DataSets can be clubbed together to pass data between
client and server applications to build truly disconnected applications. .NET Web
Services can be used as a transport for data, allowing to build a remote data service with
relatively little code.
.NET makes this type of functionality relatively easy by providing both the Web Service
transport mechanism (SOAP and HTTP), as well the built-in serialization services in the
form of XML for all of the data objects it provides. ADO.NET DataSets make this
process very easy and allow to easily create fully disconnected database applications
that can access data over the Web using standard HTTP.
ADO .NET allows to create an offline data view of multiple tables or data sources in a
single object that contains both the data itself and meta-data describing the data in the
DataSet. In addition, DataSets can directly create data tables from XML input without
any additional conversion routines. ADO.NET uses XML as its native data format and
the data stored in datasets is internally represented as XML. This makes it easy to pass
data from non-.NET sources to a .NET application and have a DataSet accept it without
having to manually parse it through an XMLDOM, SAX, or XmlTextReader parser.
DataSets also intrinsically have the ability to take data offline. In fact, DataSets are
always offline. They are disconnected views of data, meaning that one can pass the data
around to other applications, make changes to it, then update the original data source
with the changes. The DataSet manages the changes and can re-synchronize with the
database as needed. This makes it possible to use DataSets fairly transparently as a
remote data source or in an offline application. DataSets can handle both single record
update functionality (using the request/response model) or the fully offline scenario
where the data is pulled down as a big chunk, worked on and modified, and then
eventually re-synchronized with the data source.
Datasets live a double life. When used within a .NET application, they can be accessed
through ADO.NET object model in a manner similar to accessing recordsets using ADO
in the past. But they also can be persisted into XML, complete with relations, and self-
describing meta-data without any effort on developer part. ADO.NET manages how the
dataset is persisted between its in-memory representation and its XML persisted form
based on a given situation. When passing a Dataset back from a Web service,
ADO.NET serializes the Dataset into XML and sends it along its merry way to the Web
service consumer.

23 - 11 C# and .NET Programming


Introduction to Web Services

23.4.2 Passing Dataset through Web Services

Web Services provide efficient data delivery mechanism for using disconnected dataset.
Below is the process description of how to dataset is passed via Web Services

Step 1 : To create data.


There are three database tables in SQL Server :
1. An Affiliate table, which has information about all the affiliates in the program
2. A Customer table, which keeps track of the customers who have made purchases,
including a foreign key relationship with the Affiliate who referred this customer to
the site.
3. A Purchase table, which has the details about each purchase a particular customer has
made on the site.
The Web site owner can integrate the data from this Web service into his existing customer
management application, his accounting application, or into his Web site in whatever way has
been chosen.

Step 2 : Writing web service and passing data


1. Create a new Visual Basic.NET Web Service project and rename the "service1.asmx" file
to "AffiliateManagement.asmx".
2. In the Server Explorer, create a Data Connection to the database in which the tables are
created, then navigate to the Purchase table, and drag-and-drop the table onto the Web
service Designer Surface. This creates a SQL Connection and a SQL Data Adapter on the
Web service's Designer Surface.
3. Select the SQL Data Adapter and select the "Configure Data Adapter..."link at the bottom
of the Properties window. This opens the "Data Adapter Configuration Wizard."
4. Use the Query Builder to create a SELECT statement that grabs all of the purchase
information from the Purchase table and some customer information, (ESPECIALLY the
affiliate_id) from the Customer table. The SELECT statement looks like this,
SELECT purchase.purchase_id, purchase.purchase_date, purchase.purchase_amount,
purchase.customer_id, purchase.commission_due, purchase.commission_paid_date,
customer.customer_name, customer.customer_email, customer.customer_id
FROM purchase
INNER JOIN customer ON purchase.customer_id = customer.customer_id WHERE
(customer.affiliate_id = @affiliate)

23 - 12 C# and .NET Programming


Introduction to Web Services

A parameter (@affiliate is included in the query which allows to pass in a specific


affiliate_id for the affiliate to search on. Also as per need the wizard can be used to create
the stored procedure for.
5. Next, select the SQL Data Adapter again, and this time, select the "Generate Dataset..."
link under the Properties window. From here one can create a Data Set called
dsAffiliatePurchase and add an instance of it to the Web service Designer Surface.
6. Now, access the code behind for the Web service and create a Web Method that looks like
this,
<WebMethod()> _
Public Function GetAffiliateDetail(ByVal AffiliateID As Integer) _
As dsAffiliatePurchase

SqlDataAdapter1.SelectCommand.Parameters.Item("@affiliate").Value = AffiliateID
SqlDataAdapter1.Fill(DsAffiliatePurchase1, "purchase")
GetAffiliateDetail = DsAffiliatePurchase1

End Function
The working explanation

Notice that the GetAffiliateDetail Web Method returns an instance of


dsAffiliatePurchase. ADO.NET takes care of the details of serializing the Dataset into
XML. The first line of code sets the @affiliate parameter to the value passed into the
Web service by the consumer. The second line of code "fills" the instance of the dataset
that was added to Designer Surface into the "purchase" table (which is just a name... in
this case it does not have the actual structure of the "purchase" table that was named
when it was dragged-and-dropped originally from the Server Explorer in step 4 above).
The third line of code then sets the results in the dataset to the return value for the Web
Method.
When compiled and tested using Web service Help Page to enter the AffiliateID,
one can see the values of the dataset passed back as serialized into XML.
23.4.3 Returning Dataset from Web Services

Below is the process description of how to create a webservice which returns a DataSet and
a Client Which displays the DataSet in a Grid.

Step 1 : Writing a Web service


Open a New WebService project say WebService1. Create a Stock Table on SQL Desktop
Edition with the Following Fields Stock Code, Description, Price (any fields as per need), and
Add some dummy data.

23 - 13 C# and .NET Programming


Introduction to Web Services

Below method is written,


using System.Data.SqlClient ;
// this is the Actual Web Method
[WebMethod]
public DataSet GetData()
{
// First Create a New Connection
System.Data.SqlClient.SqlConnection sqlConnection1 = new
System.Data.SqlClient.SqlConnection();
// Now Pass a Connection String To the Connection
sqlConnection1.ConnectionString = "data source=MyServer-001\\SqlServerName;initial
catalog=Stock;integrated securi" +
"ty=SSPI;persist security info=False;workstation id=MyServer-001;packet size=40" +
"96";
// Now the Select statement to run
string select ="select * from stock ";
// Create an Adapter
SqlDataAdapter da = new SqlDataAdapter(select,sqlConnection1);
// Create a New DataSet
DataSet ds = new DataSet();
// Fill The DataSet With the Contents of the Stock Table
da.Fill(ds , "stock");
// Now Return ds which is a DataSet
return(ds);
}

Step 2 : Writing the Client code


For the Client
1. Open a New Window form Project say WindowsApplication1.
2. Add a DataGrid to the Form. Rename DataGrid1 to dataGrid.
3. Add a Command Button.
4. Now to add a Web reference do the Following.
In the Solution Explorer Right Click on application name and Click Add Web Reference.
A Form is brought up. In the Window Type web service Url it would be
http://localhost/webservice1/service1.asmx
5. Now Click on Add Reference Button. Again solution explorer can be viewed.
6. Now in the solution explorer under web references Rename localhost to WebDataSet
7. Now in the Using Section add the below Code
using WindowsApplication1.WebDataSet;
8. Now in the Button click event add the foll Code

23 - 14 C# and .NET Programming


Introduction to Web Services

private void button1_Click(object sender, System.EventArgs e)


{
// Init MyService to the Web Service
Service1 MyService = new Service1();
// Call the GetData method in the Web Service
DataSet ds = MyService.GetData();
// Bind the DataSet to the Grid
dataGrid.SetDataBinding(ds , "stock");
}

23.4.4 A Web Service with Typed DataSets and Untyped DataSets

The web service returns database data in XML datasets with an embedded schema and it
accepts strongly typed datasets to update the database. A .net windows forms application can
work with this web service and edit the data in a datagrid. The schema describing the dataset
is known at design time, all controls and code know in detail (down to specific field
properties) what to expect. When editing the received dataset in a datagrid the application
itself will report any invalidations in the data.
A web service with untyped datasets

A web service which works with a looser definition of the data, it will expose it as a
DataSet object. Below example considers a dataset schema which describes the data having
two tables, a lookup with brands and a working table with instruments. The keys and the
relation between the two tables are described in this part of the schema.
<xs:unique name="DataSetInstrumentsKey1" msdata:PrimaryKey="true">
<xs:selector xpath=".//mstns:Brands" />
<xs:field xpath="mstns:idBrand" />
</xs:unique>

<xs:unique name="DataSetInstrumentsKey2" msdata:PrimaryKey="true">


<xs:selector xpath=".//mstns:Instruments" />
<xs:field xpath="mstns:idInstrument" />
</xs:unique>

<xs:keyref name="BrandsInstruments" refer="mstns:DataSetInstrumentsKey1">


<xs:selector xpath=".//mstns:Instruments" />
<xs:field xpath="mstns:idBrand" />
</xs:keyref>
The project has a component which handles the actual database access. The main methods
of the component return and accept data.
public DataSetInstruments Data()
{
DataSetInstruments ds = new DataSetInstruments();

23 - 15 C# and .NET Programming


Introduction to Web Services

sqlDataAdapter2.Fill(ds.Brands);
sqlDataAdapter1.Fill(ds.Instruments);
return ds;
}

public string UpdateInstruments(DataSetInstruments ds)


{
string result = "OK";
try
{
sqlDataAdapter1.Update(ds.Instruments);
}
catch(Exception e)
{
result = e.Message;
}
return result;
}
Both web services (typed and untyped) written below are built on these above methods.
The typed web services is below,
public class TypedDataService : System.Web.Services.WebService
{

[WebMethod]
public DataSetInstruments Instruments()
{
using (DataComponent dc = new DataComponent(this.Container))
{ return dc.Data();}
}

[WebMethod]
public string UpdateInstruments(DataSetInstruments ds)
{
using (DataComponent dc = new DataComponent(this.Container))
{ return dc.UpdateInstruments(ds);}
}

}
For the service with untyped dataset the data component needs an overload of the
UpdateInstruments method. The method is identical to its partner except the dataset passed in
being typed less strict.
public string UpdateInstruments(DataSet ds)
{
}

23 - 16 C# and .NET Programming


Introduction to Web Services

For the untyped web service the same coding pattern as in the typed service is followed.

public class UntypedDataService : System.Web.Services.WebService


{
[WebMethod]
public DataSet InstrumentsDataSet()
{
using (DataComponent dc = new DataComponent(this.Container))
{ return dc.Data();}
}

[WebMethod]
public string UpdateInstruments(DataSet ds)
{
using (DataComponent dc = new DataComponent(this.Container))
{ return dc.UpdateInstruments(ds); }
}

23.4.5 A Webservice with XML Strings

A smart device application works well with the second web service. But there is a
drawback. The DataSets coming in and out of the service are all very heavily decorated
and all contain the schema of the dataset that increases the amount of data on the wire.
In a scenario with limited bandwidth, like most smart device apps, this is a problem.
Another drawback with the web services is that not all web service consumers do
understand the DataSet type. Every consumer understands strings and numbers but
when it comes to a complex type like a DataSet many will give up. For instance Delphi.
The good thing with a tool like that is that it has a large library of classes and full access
to an XML parser.
A third version of the webservice just passes the basic XML, without any decoration or
schema, as a plain string. Reading the data from the dataset in this format is a matter of
using one of its other methods :
[WebMethod]
public string Instruments()
{
using (DataComponent dc = new DataComponent(this.Container))
{
return dc.Data().GetXml();
}
}

23 - 17 C# and .NET Programming


Introduction to Web Services

The GetXml method returns the bare minimum XML representation of the data.
The compact application of the demo has do a little work to get the data into a grid.
DataSet ds = new DataSet();

UntypedDataService dws = new UntypedDataService();


System.IO.StringReader sr = new System.IO.StringReader(dws.Instruments());
ds.ReadXml(new System.Xml.XmlTextReader(sr)) ;
ds.AcceptChanges();

dataGrid1.DataSource = ds.Tables["Instruments"];
Here, a StringReader is used to read the xml string and a XmlTextReader to get it into the
dataset. If AcceptChanges is not called the RowState of all rows will read Added.
After editing the dataset is sent back to the service to have that update the database
DocumentServices.UntypedDataService dws
= new CassiKijken.DocumentServices.UntypedDataService();
dws.UpdateInstruments(ds.GetXml());
For the service to correctly write the data to the database the web service has to do some
work to match incoming rows with existing rows
[WebMethod]
public string UpdateInstruments(string onXML)
{
using (DataComponent dc = new DataComponent(this.Container))
{
System.IO.StringReader sr = new System.IO.StringReader(onXML);
DataSetInstruments dsNew = new DataSetInstruments();
dsNew.ReadXml(sr);

DataSetInstruments dsOld = dc.Data();


dsOld.Merge(dsNew);

return dc.UpdateInstruments(dsOld);

}
}
First the webmethod builds a new (typed!) dataset and loads it with the Xml passed in as
a string. Next it creates a second dataset and loads it with the data in the database. The
updated data are then Merged into this second dataset, the id field will bring together the
different versions of the rows. Note that this way of working does see updates in a row
as well as new rows but misses the deletion of rows.

23 - 18 C# and .NET Programming


Introduction to Web Services

23.4.6 Data Validation Inside the Web Service

The consumer of this simplest web service is not passed the schema of the data. This
implies that it cannot validate the data on its own. Anything can be added in the dataset
and one will not notice any problems until the moment the service tries to write the
updates to the database. A solution for this would be to let the web service do the
validation. Below is the example of a web method which accepts a string with Xml data
to be validated and returns any problems found.
The actual handling of XML in the framework is done by the XMLreader and
XMLwriter classes. Amongst them is XmlValidatingReader, instances of this class read
a stream of XML and validate it against any schema assigned to it. When the xml does
not comply with the schema then an exception is thrown. The class has a
ValidationEventHandler, if an eventhandler is registered the event will fire instead of
the exception being thrown.
Below is the code for validating reader,
private XmlValidatingReader validator(string onXML)
{
System.IO.StringReader sr = new System.IO.StringReader(onXML);
XmlTextReader xtr = new System.Xml.XmlTextReader(sr);
XmlValidatingReader result = new XmlValidatingReader(xtr);
result.ValidationType = System.Xml.ValidationType.Schema;

DataSetInstruments ds = new DataSetInstruments();


XmlSchema xs = XmlSchema.Read(new System.IO.StringReader(ds.GetXmlSchema()),
null);
xs.Compile(null);
result.Schemas.Add(xs);

return result;
}
In the first four lines the reader is constructed and its validation type is set to xsd schema.
In the next four lines the schema is extracted from the (typed) dataset, compiled and added to
the validator. The result is a reader which will validate the Xml passed in using the schema of
the expected dataset. It will construct a list of any error messages, the event handler collects
the messages in a stringbuilder that can be accessed as below,
private System.Text.StringBuilder vm;

private void validationEvent(object o, ValidationEventArgs e)


{
vm.Append(e.Severity.ToString());

23 - 19 C# and .NET Programming


Introduction to Web Services

vm.Append(" ");
vm.Append(e.Message);
vm.Append(System.Environment.NewLine);
}
In the validating web method all of this is tied together,
[WebMethod]
public string ValidateWithInfo(string xmlData)
{
vm = new System.Text.StringBuilder("");
XmlValidatingReader xvr = validator(xmlData);
xvr.ValidationEventHandler +=new ValidationEventHandler(validationEvent);

while (xvr.Read()) {};

return vm.ToString();
}
The stringbuilder is initialized, a validating reader for the xml passed in is constructed and
the event handler is assigned to it. Now the reading can start, any errors found will be
collected by the event handler. The result is returned by the web method, if everything was
OK this will be an empty string.
Validating the data from a consumer now boils down to invoking the web service,
UntypedDataService dws = new UntypedDataService();
textBoxValidation.Text = dws.ValidateWithInfo(ds.GetXml());
The validator Failure Scenarios (Validator may fail.)
The Xml passing or failing the validation test is not a guarantee for a (un-)successful
database update. For example, if the xml does not contain any values for the id field the
validation will fail as the id is required and should be unique. The database doesn't care,
the id's are generated by the database. The validation failed but the update succeeded. It
can be the other way round as well. If the foreign keys values in the data are found in
the lookup table of the dataset the validation will pass. In the update the database will
search the key-value in the database table, if the key is gone the update will fail.
A schema can help with an idea what the data should look like. But the only way of
finding out if all assumptions are really valid remains a question of trial and error, in C#
speak that is try and catch. But validating against a schema helps to the rate of success.

23 - 20 C# and .NET Programming


Introduction to Web Services

Two Marks Questions with Answers

Q.1 Give me an example of real web service ?


Ans. : One example of web services is IBM Web Services browser. You can get it from
IBM Alphaworks site. This browser shows various demos related to web services.
Basically web services can be used with the help of SOAP, WSDL, and UDDI . All these,
provide a plug-and-play interface for using web services such as stock-quote service, a
traffic-report service, weather service etc.
Q.2 What kind of security is needed for web services ?
Ans. : The security level for web services should be more than that of what we say Secure
Socket Layer (SSL). This level of security can be only achieved from Entrust Secure
Transaction Platform. Web services need this level of security to ensure reliable
transactions and secure confidential information .
Q.3 What are the situations, when we need ASP.NET web services ?
Ans. : ASP.NET web services are used when one need to implement three tier architecture
in a web service. It allows handy ways to use middle tier components through internet. The
main advantage of .NET Web services is that they are capable enough to communicate
across firewalls because they use SOAP as transport protocol.
Q.4 Differentiate between web services, CORBA and DCOM.
Ans. : Web services transfer/receive messages to/from application respectively, via HTTP
protocol. It uses XML to encode data.
CORBA and DCOM transfer/receive messages to/from application respectively, via
non-standard protocols such as IIOP and RPC.
Q.5 Can you name some standards used in web services ?
Ans. : The standards used in web services are WSDL (used to create interface definition),
SOAP (used to structure data), HTTP (communication channels), DISCO (used to create
discovery documents) and UDDI (used to create business registries).

Long Answered Questions

Q.1 What is role of SOAP in web services ? (Refer section 23.2)


Q.2 Define and discuss web service. (Refer section 23.1)
Q.3 Explain steps to write a web service. (Refer section 23.3)
Q.4 What do you mean by consuming the web service ? How to consume the web
service ? (Refer section 23.3)
Q.5 What are various applications that can have web services ? (Refer section 23.1)

23 - 21 C# and .NET Programming


Introduction to Web Services

Q.6 Explain the following concepts : Passing and returning data sets from web
services. (Refer section 23.4) AU : May-18, Marks 8
Q.7 Illustrate the following with an example,
i) Passing and Returning datasets from Web services. (Refer section 23.4)
AU : Dec.-18, Marks 7
Q.8 Explain Web Services in detail. (Refer section 23.1) AU : May-19, Marks 13

Introduction to Web Services ends …

23 - 22 C# and .NET Programming


C# and .NET Framework - Introduction

Syllabus : .NET Remoting

Section No. Topic Name Page No.


24.1 Remoting 24 - 2

24.2 C# Remoting Architecture 24 - 2

24.3 Types of .NET Remotable Objects 24 - 4

24.4 Domains 24 - 5

24.5 Contexts 24 - 5

24.6 Proxies 24 - 5

24.7 Marshalling and Unmarshalling 24 - 6

24.8 Object Activation 24 - 7

24.9 .NET Remoting Metadata 24 - 11

24.10 Object Lifetime, Sponsorship and Leases 24 - 12

Two Marks Quetions with Answers 24 - 13

Long Answered Questions 24 - 15

24 - 1 C# and .NET Programming


.NET Remoting

24.1 Remoting AU : May-18

Concept

1. Distributed computing is an integral part of almost every software development. Before


.NET Remoting, DCOM (dynamic component object modeling) was widely used method
for developing distributed application on Microsoft platform. Because of object oriented
architecture, .NET remoting replaces DCOM as .NET framework replaces COM.
Explanation

2. .NET Remoting is a architecture/mechanism which enables communicating between


objects which are not in the same process. It is a generic system for different applications
to communicate with one another. .NET objects are exposed to remote processes, by
which it allows inter process communication. The applications can be located on the same
computer, different computers on the same network, or on computers across separate
networks.
3. Remoting enables communication between different application domains or processes
using different transportation protocols, serialization formats, object lifetime schemes, and
modes of object creation.
4. Advantages of Distributed Application Development

Fault tolerance means that a system should be resilient when failures within the system
occur.

Scalability is the ability of a system to handle increased load with only an incremental
change in performance.

Managing the system from one place.


24.2 C# Remoting Architecture
Concept
1. The .NET Remoting provides an inter-process communication between Application
Domains by using Remoting Framework. The applications can be located on the same
computer , different computers on the same network, or on computers across separate
networks. The .NET Remoting supports distributed object communications over the TCP
and HTTP channels by using Binary or SOAP formatters of the data stream.

24 - 2 C# and .NET Programming


.NET Remoting

Explanation

2. The main three components of a Remoting Framework are :


1. C# Remotable Object
2. C# Remote Listener Application - (listening requests for Remote Object)
3. C# Remote Client Application - (makes requests for Remote Object)
3. The Remote Object is implemented in a class that derives from
System.MarshalByRefObject .

Fig. 24.2.1 NET remoting frame work

Above Fig. 24.2.1 depicts workflow of .NET Remoting.


When a client calls the Remote method, actually the client does not call the methods
directly. It receives a proxy to the remote object and is used to invoke the method on the
Remote Object.
Once the proxy receives the method call from the Client, it encodes the message using
appropriate formatter (Binary Formatter or SOAP Formatter) according to the
Configuration file. After that it sends the call to the Server by using selected Channel
(TcpChannel or HttpChannel).
The Server side channel receives the request from the proxy and forwards it to the Server
on Remoting system, which locates and invokes the methods on the Remote Object. When the
execution of remote method is complete, any results from the call are returned back to the
client in the same way.
Before an object instance of a Remotable type can be accessed, it must be created and
initialized by a process known as Activation. Activation is categorized in two models , they
are Client-activated Objects and Server-activated Objects.

24 - 3 C# and .NET Programming


.NET Remoting

4. C# Remote Activation
The real difference between client-activated and server-activated objects is that a server-
activated object is not really created when a client instantiates it. Instead, it is created as
needed.
By default the .NET Framework ships with two formatters(Binary Formatter or SOAP
Formatter) and two channels(TcpChannel,HttpChannel).
5. C# Remote Channels and C# Remote Formatters
Formatters and Channel are configured by using Configuration files. It can be easily
Configured by using XML-based files.
6. C# Remote Configuration
The .NET Remoting is easy to use and powerful, largely because it is based on the
Common Type System (CTS) and the Common Language Runtime (CLR).

24.3 Types of .NET Remotable Objects

There are three types of objects that can be configured to serve as .NET remote objects
which can be chosen depending on the requirement of application.
1. Single Call

Single Call objects service one and only one request coming in. Single Call objects are
useful in scenarios where the objects are required to do a finite amount of work.
Single Call objects are usually not required to store state information, and they cannot
hold state information between method calls.
2. Singleton Objects

Singleton objects are those objects that service multiple clients, and hence share data by
storing state information between client invocations. They are useful in cases in which
data needs to be shared explicitly between clients, and also in which the overhead of
creating and maintaining objects is substantial.
3. Client-Activated Objects (CAO)

Client-activated objects (CAO) are server-side objects that are activated upon request
from the client. When the client submits a request for a server object using a "new"
operator, an activation request message is sent to the remote application.
The server then creates an instance of the requested class, and returns an ObjRef back to
the client application that invoked it. A proxy is then created on the client side using the
ObjRef.

24 - 4 C# and .NET Programming


.NET Remoting

The client's method calls will be executed on the proxy. Client-activated objects can store
state information between method calls for its specific client, and not across different client
objects. Each invocation of "new" returns a proxy to an independent instance of the server
type.

24.4 Domains

Concept

1. In .NET, when an application is loaded in memory, a process is created, and within this
process, an application domain is created.
Explanation

2. The application is actually loaded in the application domain. If this application


communicates with another application, it has to use Remoting because the other
application will have its own domain, and across domains, object cannot communicate
directly.
3. Different application domains may exist in same process, or they may exist in different
processes.

24.5 Contexts

Concept

1. The .NET runtime further divides the application domain into contexts.
2. A context guarantees that a common set of constraints and usage semantics govern all
access to the objects within it.
Explanation

3. All applications have a default context in which objects are constructed, unless otherwise
instructed.
4. A context, like an application domain, forms a .NET Remoting boundary. Access requests
must be marshaled across contexts.

24.6 Proxies

Concept

1. When a call is made between objects in the same Application Domain, only a normal
local call is required; however, a call across Application Domains requires a remote call.

24 - 5 C# and .NET Programming


.NET Remoting

Explanation

2. In order to facilitate a remote call, a proxy is introduced by the .NET framework at the
client side. This proxy is an instance of the TransparentProxy class, directly available to
the client to communicate with the remote object.
3. Generally, a proxy object is an object that acts in place of some other object. The proxy
object ensures that all calls made on the proxy are forwarded to the correct remote object
instance.
4. In .NET Remoting, the proxy manages the marshaling process and the other tasks
required to make cross-boundary calls. The .NET Remoting infrastructure automatically
handles the creation and management of proxies.
5. Types of Proxy
RealProxy and TransparentProxy

The .NET Remoting Framework uses two proxy objects to accomplish its work of making
a remote call from a client object to a remote server object: a RealProxy object and a
TransparentProxy object.
The RealProxy object does the work of actually sending messages to the remote object
and receiving response messages from the remote object.
The TransparentProxy interacts with the client, and does the work of intercepting the
remote method call made by the client.

24.7 Marshalling and Unmarshalling AU : May-18, 19, Dec.-19

Concept

1. By remote it means that any object which executes outside the application domain.
2. The two processes can exist on the same computer or on two computers connected by a
LAN or the Internet. This is called marshalling (This is the process of passing parameters
from one context to another.
Explanation

3. Object Marshalling specifies how a remote object is exposed to the client application. It is
the process of packaging an object access request in one application domain and passing
that request to another domain. The .NET Remoting infrastructure manages the entire
marshaling process.
4. Marshalling done by the .NET Framework, and there is no need to write any code for
it.

24 - 6 C# and .NET Programming


.NET Remoting

5. There are two basic ways to marshal an object.


1. Marshal by value the server creates a copy of the object passes the copy to the client.
Marshaling by value is similar to having a copy of the server object at the client.
Objects that are marshaled by value are created on the remote server, serialized
into a stream, and transmitted to the client where an exact copy is reconstructed.
Once copied to the caller's application domain (by the marshaling process), all
method calls and property accesses are executed entirely within that domain.
Marshal by value objects are, very efficient if they are small, and provide a
repeated function that does not consume bandwidth.
The entire object exists in the caller's domain, so there is no need to marshal
accesses across domain boundaries.
Using marshal-by-value objects one can increase performance and reduce
network traffic, when used for small objects or objects to which one will be
making many accesses.
Marshal by value classes must either be marked with the [Serilaizable] attribute
in order to use the default serialization, or must implement the ISerializable
interface.

2. Marshal by reference the client creates a proxy for the object and then uses the proxy
to access the object Marshaling by reference is similar to having a pointer to the
object.
Marshal by reference passes a reference to the remote object back to the client.
This reference is an ObjRef class that contains all the information required to
generate the proxy object that does the communication with the actual remote
object.
On the network, only parameters and return values are passed. A remote
method invocation requires the remote object to call its method on the remote host
(server).
Marshal by reference classes must inherit from System.MarshalByRefObject.

24.8 Object Activation

Concept

1. Object activation means various ways in which a remote object can be instantiated.
2. Marshal by value objects have a simple activation scheme, they are created when the
client first requests them.
3. Marshal by reference objects have following two activation schemes.

24 - 7 C# and .NET Programming


.NET Remoting

Explanation
3.1 Server Activated Objects
Server Activated Objects are created only when the client makes the first call to the
remote method. That is, when the client asks for the creation of the remote object,
only the local proxy is created on the client, the actual remote object on the server is
instantiated on the first method call. These proxies can be generated as:
// On the Server
RemotingConfiguration.RegisterWellKnownServiceType(
typeof (RemoteServerObject), "Check",
WellKnownObjectMode.SingleCall);

// On the Client
IRemoteCom obj = (IRemoteCom)Activator.GetObject(typeof(IRemoteCom),
"tcp://localhost:1002/Check");
Registration types
There are two registration types, Singleton and SingleCall, which were explained in earlier
section. The basic code for registration is,
RemotingConfiguration.RegisterWellKnownServiceType( typeof(RemoteServerObject),
"Check", WellKnownObjectMode.SingleCall);

RemotingConfiguration.RegisterWellKnownServiceType(
typeof(RemoteServerObject),
"Check", WellKnownObjectMode.Singleton);
For Server Activated Objects, the proxy object (on the client) and the actual object (on
the server) are created at different times.
3.2 Client Activated Objects
1. Client activate objects are created on the server immediately upon the client's
request.
2. An instance of a Client Activated Object is created every time the client
instantiates one, either by the use of new or Activator.CreateInstance(...).
// On the Server
RemotingConfiguration.ApplicationName = "CheckCAO";
RemotingConfiguration.RegisterActivatedServiceType(typeof(RemoteObjectCAO));

// On the Client
RemotingConfiguration.RegisterActivatedClientType(typeof(RemoteObjectCAO),
"tcp://localhost:1002/CheckCAO");
obj = new RemoteObjectCAO();

24 - 8 C# and .NET Programming


.NET Remoting

3. In above code snippets, "localhost" can be replaced with an actual remote machine's
IP address.
4. Which activation to use depends upon different scenarios are discussed below.
1. Singleton object reference is used when persistent data is held on the server,
and is accessible by all clients.
2. SingleCall model is used to provide a stateless programming model (the
traditional Web services request/response model), or any time there is no need
to maintain a persistent object state on the server.
3. Client activation model is used when the object needs to maintain persistent
per-client state information.
Example
//illustration of .Net Remoting.
/*here Remoting object will send the maximum of the two integer numbers sent.
Creating Remote Server and the Service classes on
Machine 1:
Please note for Remoting support service (Remote object) should be derived from
arshalByRefObject.*/

using System;
using System.Runtime.Remoting.Channels; //To support and handle Channel and channel
inks
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels.Http; //For HTTP channel
using System.IO;

namespace ServersideApp
{
public class TechnicalRemotingServer
{
public TechnicalRemotingServer()
{
// constructor code
}
}
//Service class
public class Service: MarshalByRefObject
{
public void WriteMessage (int n)
{
if (n%2 == 0)
Console.WriteLine (“Even”));
else

24 - 9 C# and .NET Programming


.NET Remoting

Console.WriteLine (“Odd”);
}
}

//Server Class
public class TechnicalServer
{
public static void Main ()
{
HttpChannel channel = new HttpChannel(8001); //Create a new channel
ChannelServices.RegisterChannel (channel); //Register channel

RemotingConfiguration.RegisterWellKnownServiceType(typeof
service),"Service",WellKnownObjectMode.Singleton);
Console.WriteLine ("Server Available at port number 8001");
Console.WriteLine ("Press enter to Stop the server.");
Console.ReadLine ();
}
}
}
/* Follow the steps,
1. above file is saved as ServerApp.cs.
2. Create an executable by using Visual Studio.Net command prompt by,
csc /r:system.runtime.remoting.dll /r:system.dll ServerApp.cs
A ServerApp.Exe will be generated in the Class folder.
3. Run the ServerApp.Exe.*/
Output
Server Available at port number 8001
Please press enter to stop the server.
Settings required on the machines are specified below so as to run the remoting
applications..
In order to check whether the HTTP channel is binded to the port, type
http://localhost:8001/Service?WSDL, in the browser, one should see a XML file
describing the Service class.
Before running above URL on the browser, the server (ServerApp.Exe should be
running) should be ON.
Creating Proxy and the Client application on Machine 2
SoapSuds.exe is a utility which can be used for creating a proxy dll.
Type below command on Visual studio.Net command prompt.
soapsuds -url:http://< Machine Name where service is running>:8001/Service?WSDL -
oa:Server.dll

24 - 10 C# and .NET Programming


.NET Remoting

This will generates a proxy dll by name Server.dll. This will be used to access remote
object.
//Client Code
using System;
\using System.Runtime.Remoting.Channels; //To support and handle Channel and
hannel sinks
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels.Http; //For HTTP channel
using System.IO;
using ServerApp;
namespace ClientSideRemotingApp
{
public class TechnicalClientApp
{
public ClientApp()
{
}
public static void Main (string[] args)
{
HttpChannel channel = new HttpChannel (8002); //Create a new channel
ChannelServices.RegisterChannel (channel); //Register the channel
//Create Service class object
Service svc = (Service) Activator.GetObject (typeof (Service),"http://<Machine name
here Service running>:8001/Service"); //Localhost can be replaced by
//Pass Message
svc.WriteMessage (10,20);
}
}
}
/* Follow the steps,
1. Save the above file as ClientApp.cs.
2. Create an executable by using Visual Studio.Net command prompt by,
csc /r:system.runtime.remoting.dll /r:system.dll ClientrApp.cs
A ClientApp.Exe will be generated in the Class folder. Run ClientApp.Exe , one can
see the result on Running ServerApp.EXE command prompt.
3. In the same way this can be implemented for TCP channel also.*/

24.9 .NET Remoting Metadata

Concept
.NET Remoting uses metadata to dynamically create proxy objects.
Explanation
The proxy objects that are created at the client side have the same members as the original
class.

24 - 11 C# and .NET Programming


.NET Remoting

The client can obtain the metadata information required to access the remote object in the
following ways:
The .NET assembly of the server object.
The Remoting object can provide a WSDL (Web Services Description Language) file
that describes the object and its methods.
.NET clients can use the SOAPSUDS utility to download the XML schema from the
server (generated on the server) to generate source files or an assembly that contains
only metadata, no code.
24.10 Object Lifetime, Sponsorship and Leases
1. A Server Activated Object that has been registered as SingelCall has a very simple and
limited lifetime. It lives for a single call only. Thereafter, it is marked by the Garbage
Collector for removal.
2. The other two types, Singleton and Client Activated Objects, have their lifetimes
managed by a service introduced by the .NET Framework, the Leased Based Manager.
On the server, the application domain's lease manager determines when a server-side
object should be marked for deletion.
Each application domain has its own lease manager object. For objects that have object
references that are transported outside the application, a lease is created. The lease has a
lease time; when the lease reaches zero, it expires, and the object is disconnected from the
.NET Remoting Framework.
When all the references to the object within the AppDomain have been freed, the object
will be collected when the next garbage collection occurs.
3. A sponsor is a object that plays a vital role in the life time of remote objects. When a
lease expires, one or more of the lease's sponsors are invoked by the Lease Manager,
where they are given the opportunity to renew the lease. If none of the sponsors decides to
renew the lease, the lease manager removes the lease and the object is garbage collected.
4. The default settings for the lease manager are,
1. five minutes for initial time-to-live
2. poll every ten seconds, and
3. add an additional two minutes for every remote call by a client.
All these values are configurable, by overriding MarshalByRefObject
InitializeLifetimeService() to define own values in the remotable object.
5. Renewing Object Leases and Increasing Life Times
1. While objects have a default lease period, there are ways and reasons to extend the
lease period to keep the object alive. When client wants to maintain state in the same
server object it is always good to renew the object life..

24 - 12 C# and .NET Programming


.NET Remoting

2. The server object lease time can be set to infinity, by which Remoting object is
informed not to collect it during garbage collection cycles.
3. The client can call the RemotingServices.GetLifetimeService method to get the
lease of the server object from the lease manager of the AppDomain. From the Lease
object, the client can then call the Lease.Renew method to renew the lease.
4. The client can register a sponsor for the specific lease with the lease manager of the
AppDomain so that when the remote object's lease expires, the lease manager calls
back to the sponsor to request a lease renewal directly, instead of reaching to client.
5. Lease time can be increased by setting the ILease::RenewOnCallTime property
because of which each call to the remote object renews the lease by the amount of
time specified by the RenewOnCallTime property.
6. When the object is marshaled, the lease goes from the initial to the active state, and
any attempt to initialize the lease properties will be ignored and an exception is
thrown.
7. InitializeLifetimeService is called when the remote object is activated. After
activation, the lease can only be renewed.
8. The .NET Remoting implementation provides two ways to renew the lease on a
remote object. The client can call ILease.Renew directly, or the client can contact a
sponsor and ask the sponsor to renew the lease.
9. The sponsor object listens for queries from the host system's lease manager, and
responds accordingly. Sponsors register with the lease manager by obtaining a
reference to the lease and calling ILease.Register. The lease manager will
periodically query the sponsor to see if it wants to renew the lease. If the sponsor
wants to renew the lease, it returns a renewal TimeSpan value in response to the
server's query.

Two Marks Quetions with Answers

Q.1 What are possible implementations of distributed applications in .net ?


Ans. : .NET Remoting and ASP.NET Web Services. If we talk about the Framework Class
Library, noteworthy classes are in System.Runtime.Remoting and System.Web.Services.
Q.2 What are remotable objects In .net Remoting ?
Ans. : Remotable objects are the objects that can be marshaled across the application
domains. You can marshal by value, where a deep copy of the object is created and then
passed to the receiver. You can also marshal by reference, where just a reference to an
existing object is passed.

24 - 13 C# and .NET Programming


.NET Remoting

Q.3 What is .net Remoting ?


Ans. : .NET Remoting is an enabler for application communication. It is a generic system
for different applications to use to communicate with one another. .NET objects are
exposed to remote processes, thus allowing interprocess communication. The applications
can be located on the same comput
Q.4 Define marshaling.
Ans. : The process of preparing an object to be remoted is called marshaling. On a single
machine, objects might need to be marshaled across context, app domain or process
boundaries.
Q.5 What are channels in .NET remoting ?
Ans. : Channels represent the objects that transfer the other serialized objects from one
application domain to another and from one computer to another, as well as one process to
another on the same box. A channel must exist before an object can be transferred.
Q.6 List the information stored in the configuration file for remoting.
AU : Dec.-18
Ans. : Remoting configuration files, like other configuration files in .NET, are Extensible
Markup Language (XML) files that use the .config extension. Configuration files can be
used in remoting in lieu of source code creation and registration. In the examples so far,
there hasn't been a desperate need for configuration files, but as one should get into
customized sinks, the amount and complexity of code required to create and register remote
objects increases dramatically. Configuration files also permit configuration changes
without code changes.
The naming convention for remoting configuration files is the executable program name
and extension, with a .config extension. Thus, for ClientActivatedServerExe.exe, the
configuration file would be named ClientActivatedServerExe.exe.config. At this point, it
should be evident that less wordy project names are a good idea! The location of the
configuration file must be in the same directory as the executable file.
The configuration files are located in the Samples1 with the source files in the
directories of the four executable files. They should be moved to the respective "bin\debug"
directories. the server's configuration file, and like all .NET configuration files, the root
element is <configuration>. Remoting configuration is placed in the subelement
<system.runtime.remoting>. This is a configuration for a client-activated object. The
<application> tag contains the optional name attribute that identifies the URI of the remote
object. If the name attribute is dropped, the client's configuration tag, below, would have to
be changed to <client url="tcp://localhost:1234">.

24 - 14 C# and .NET Programming


.NET Remoting

The two subelements of <application> are <service> and <channels>. An optional


subelement is a <lifetime> tag. This defines the leasing lifetime of all remote objects on the
server.
The <service> tag contains information about the remote objects and is a server-specific
element. The <channels> tag is common to both client and server configuration and
contains information about the channels to be used by the remote object. Both of these
elements can encapsulate multiple remote objects and channels.
The <activated> element identifies the remote object as being client activated. The type
attribute gives the remote object's name and assembly. Two optional attributes deal with
leasing, leasetime and renewoncall. These can be used to override the default time
associated with those leasing properties.
The <channel> tag on the server contains two attributes. The type attribute, as with the
other type attributes discussed so far, names the channel type and the assembly to be used.
The port attribute indicates the port the channel will listen on.
The client configuration file (see Listing 25.20) is very similar to the server's. The
primary difference is the server's <service> tag counterpart, the <client> tag. The <client>
element contains the url attribute, which, as always, identifies the location of the remote
object. Using configuration files in source code is straightforward.

Long Answered Questions

Q.1 Discuss .NET remoting architecture. (Refer section 24.2)


Q.2 Explain various remotable objects in .NET. (Refer section 24.3)
Q.3 Explain the proxies. (Refer section 24.6)
Q.4 Explain object activation. (Refer section 24.8)
Q.5 What is .NET remoting metadata ? (Refer section 24.9)
Q.6 Discuss in detail about Marshalling and Remoting.
[Refer sections 24.1 and 24.7] AU : May-18, Marks 13
Q.7 What is marshalling ? Explain types of marshalling. [Refer sections 24.7]
AU : May-19, Marks 13
Q.8 Differentiate marshalling and remote and explain them in detail.
[Refer section 24.7] AU : Dec.-19, Marks 13

.NET Remoting ends …

24 - 15 C# and .NET Programming


.NET Remoting

24 - 16 C# and .NET Programming


C# and .NET Framework - Introduction

Syllabus : Windows Services, Windows Workflow Foundation (WWF), Activities


and Workflows.

Section No. Topic Name Page No.

25.1 Windows Services 25 - 2

25.2 Windows Workflow Foundation (WF / WinWF) 25 - 15

Two Marks Questions with Answers 25 - 25

Long Answered Questions 25 - 26

25 - 1 C# and .NET Programming


Windows Services, WWF - Basics, Activities and Workflows

25.1 Windows Services

25.1.1 Introduction to Windows Services

Windows service is a special type of application that is configured to launch and run in
the background, in some cases before the user has even logged in. Windows Services
are a core component of the Microsoft Windows operating system and enable the
creation and management of long-running processes.
Unlike regular software that is launched by the end user and only runs when the user is
logged on, Windows Services can start without user intervention and may continue to
run long after the user has logged off. The services run in the background and will
usually kick in when the machine is booted.
Unlike regular applications, which can be simply launched and run under user account,
a service must be installed and registered with Windows, which requires an
administrator account, and usually a User Account Control prompt before that happens.
So if user does not allow an application to run as administrator, it cannot just create a
service to run in the background.
A service is an application almost like any other. The difference between services and
other programs is that they run in the background and do not have a user interface that
one can click or tap on. They are intended to provide operating system features such as
web serving, event logging, file serving, printing or error reporting.
Services can be configured to run as the local system account. Services are designed to
run continuously in the background and perform system tasks, like backing up computer
or running a server process that listens on a network port.
Back in the Windows XP days, services could be configured to run interactively and run
alongside the rest of applications, but since Vista, all services are forced to run in a
special window session that can't interact with local desktop. So a service that tries to
open a dialog box or show a message won't be allowed to do so.
The services manage a wide variety of functions including network connections, speaker
sound, data backup, user credentials and display colors. Windows Services perform a
similar function as UNIX daemons.
Developers can create Services by creating applications that are installed as a Service,
an option ideal for use on servers when long-running functionality is needed without
interference with other users on the same system.

25 - 2 C# and .NET Programming


Windows Services, WWF - Basics, Activities and Workflows

Not all services are developed by Microsoft. Some applications and drivers install their
services. Security suites are an excellent example, as they install different services to
provide real-time monitoring of system's activities, anti-malware protection, firewall
protection etc. They need to take the advantages offered by services. One such
advantage is that they can be started during the system boot, before other programs and
even before user logs in. However, the most important advantage is that they can
monitor everything that runs on computer while being perfectly integrated into the
Windows core. This way, they can provide a high level of protection.
Another example of a non-Microsoft service could be an SSH server, often used in
offices for secure remote connections or an auto-updating service for the web browser
like the Mozilla Maintenance Service used by Firefox.
Knowing what or when a service does something can be useful. For example, if a
particular service is not required then it can be disabled so that system can speed up
rather than running unnecessary service. For example if a router is installed to manage
the local network, it is likely that there is no need of the Internet Connection Sharing
service to run.
Alternatively, if a particular service is required to run but it is not that important, then it
can be started a little later after Windows, startup apps or other, more critical services,
have started. For example, the service Windows Time service, which synchronizes the
date and time for Windows and applications. It is set to Delayed startup.
25.1.2 Finding the Currently Running Services in the System and Service
Properties

The easiest way to open Services is through the Services shortcut in Administrative
Tools, which is accessible through Control Panel.
Another option is to run services.msc from a Command Prompt or the Run dialog box
(Win key+R).
On Windows 10, Windows 8, Windows 7, or Windows Vista services can be found in
Task Manager.
Services that are actively running currently will say Running in the Status column.
Some of the example of services that would be usually found running in the system are,
Apple Mobile Device Service, Bluetooth Support Service, DHCP Client, DNS Client,
HomeGroup Listener, Network Connections, Plug and Play, Print Spooler, Security Center,
Task Scheduler, Windows Firewall, and WLAN AutoConfig.
It's completely normal if not all of the services are running (nothing, or Stopped, is
shown in the Status column). They can be started up one after the other as needed.

25 - 3 C# and .NET Programming


Windows Services, WWF - Basics, Activities and Workflows

Double-clicking (or tapping) on any service will open its properties, which is where the
purpose for the service can be seen and, for some services, what will happen if it is
stopped. For example, opening the properties for Apple Mobile Device Service
explains that the service is used to communicate with Apple device that is plugged into
computer.
The properties of a service can not be viewed if accessed them through Task Manager.
Services utility is to be used to see the properties.
In the Services window, for each of the services listed, five things can be found namely,
1. Name - The name of the service can be helpful to get an idea of what that service
does. Unfortunately, though, this name is often too cryptic to help to understand
what the service is all about.
2. Description - The description of the service shows some brief information about the
service's purpose or identity.
3. Status - Indicates whether that service is running or if it is stopped.
4. Startup Type - Shows how that service is started by Windows. Services can be
launched automatically, automatically but with a delay, manually, or they can be
disabled, which means that they are never started.
5. Log On As - It allows to select whether the service is started using the Local System
account or using another user account that is manually specified.
It should be noted that the same information can be viewed in the Properties of each
service, by double-clicking (or double-tapping) on its name in the Services window.
25.1.3 Types of Windows Services

Windows Services broadly fall into three categories depending on the actions and
applications they control : Local Services, Network Services and System. Third party
applications such as antivirus software may also install their own services.
25.1.4 Accessing and Managing Windows Services

There quite a few different ways of accessing the Windows services. Simple technique
is to use the search option in Windows. Enter the word services in the search field from
the taskbar in Windows 10, start typing services on the Start screen from Windows 8.1,
or type services in the search field from the Start Menu in Windows 7. In all these
operating systems, click or tap on the Services or "View local services" search results.
Then, the Services window opens. The Services window is the place from one can view,
start, stop and configure any windows service.

25 - 4 C# and .NET Programming


Windows Services, WWF - Basics, Activities and Workflows

Windows Services are managed via the Services Control Manager panel. The panel
shows a list of services and for each, name, description, status (running, stopped or
paused) and the type of service. Double clicking on a service reveals its properties in
greater detail. One can stop, pause, start, delay start, or resume each service as
appropriate. One can also modify the start mechanism (Manual or Automatic) or specify
an account.
Services can be deleted by a user with administrative privileges, but as doing so can
render the operating system unstable, it should be done only when necessary and with
caution.
25.1.4.1 The Services Panel

Windows has always used the Services panel as a way to manage the services that are
running on computer. One can get there at any point by hitting WIN + R on the
keyboard to open the Run dialog, and typing in services.msc.
The Services panel is fairly simple: there are a list of services, a status column to show
whether it is running or not, and more information like name, description, and the
startup type of the service. It can be noticed that not every service is running all the
time.
While one can select a service and either right-click it or click the toolbar buttons to
start, stop, or restart it, one can also double-click to open up the properties view and get
more information.
Disabling the service is as simple as changing the Startup type drop-down to disabled
and choosing Apply, although one can also change it to Manual or automatic with a
delayed start. From this dialog one can see the full path to the executable as well, which
can help in many cases when one wants to see what exactly the service is running.
The Log On tab allows to choose whether the service is logged on as the local system
account or under another account. This is mostly useful in a server environment where
one might want to run a service account from the domain that has access to resources on
other servers.
One might notice the option for "Allow service to interact with desktop", that is - by
default, services are not allowed to access the desktop unless this box is checked, and
this checkbox is really only there for legacy support.
But just checking that box doesn't immediately give them access - one would also need
to make sure that the NoInteractiveServices value in the registry is set to 0, because

25 - 5 C# and .NET Programming


Windows Services, WWF - Basics, Activities and Workflows

when it is set to 1, that checkbox is ignored and services can't interact with the desktop
at all. In Windows 8, the value is set to 1, and interactive services are prohibited.
Services aren't supposed to be interactive because all windows exist in the same user
terminal with access to common resources like the clipboard, and if they are running
along with other processes there could be an issue where a malicious application
running in a normal user process could attempt to gain more access through a service,
and considering that services run as the local system account, that probably isn't a good
thing.
The Recovery tab allows to choose options for what happens when the service fails. One
can choose to automatically restart the service, which is generally the default option, or
can run a program or restart the computer.
Run a program option is probably the most useful, since one could set Windows to
automatically send out an email if the service fails more than once - a helpful option in a
server environment. It's definitely much less helpful on a regular desktop.
The dependencies tab shows which services depend on a particular service, and which
services depend on the one being viewed by the user.
25.1.4.2 More Information on Windows Services

Services are different than regular programs in that a regular piece of software will stop
working if the user logs out of the computer. A service, however, is running with the
Windows OS, sort of in its own environment, which means the user can be logged
completely out of their account but still have certain services running in the background.
Though it may come off as a disadvantage to always have services running, it's actually
very beneficial, like if remote access software is being used. An always-on service
installed by a program like TeamViewer enables user to remote into computer even if
user is not logged on locally.
There are other options within each service's properties window on top of what is
described above that allows to customize how the service should start up (automatically,
manually, delayed, or disabled) and what should automatically happen if the service
suddenly fails and stops running.
A service can also be configured to run under the permissions of a particular user. This
is beneficial in a scenario where a specific application needs to be used but the logged in
user doesn't have proper rights to run it.

25 - 6 C# and .NET Programming


Windows Services, WWF - Basics, Activities and Workflows

25.1.4.3 Looking at Services in Task Manager for Windows 8.x

The regular services panel hasn't changed much in years, but thankfully there is a much
better way to look at which services are running, and which of those services are using a
lot of resources.
Task manager in Windows 8 has a new Services tab, which allows to stop and start
services, but also comes with a "Search online" option, and even more useful, the "Go to
details" option.
Once Go to details option is selected from the menu, it is switched over to the Details
tab, and the process that is responsible for that service will be highlighted.
Right-click it again, and then select Go to Services. Now many services are selected in
the Services window, and it can be noticed that they are all in the
LocalSystemNetworkRestricted group and they are all currently running.
25.1.4.4 Using Process Explorer to Look at Services

To get a much clearer view of what services are running under each process, Process
Explorer can be used that can find the service in the list, double-click it, and then go to the
Services tab. This method works on any version of Windows. In Process Explorer all the
services should be in the tree underneath services.exe.
25.1.4.5 Administering Services from the Command Prompt

Some operations just can't be done through the graphical user interface. To delete a service,
for example, the command line can be used. The status of a service can be queried using the sc
command, like,
sc qc eventlog
There are many other commands and operations that can be performed, including deleting a
service, which is recommended if there are malwares on the system that is running as a
service.
sc delete <malwareservicename>
Other operations can be done through command line, like stopping and restarting services
from using the sc utility. For example, to stop the distributed link tracking client, below
command can be used,
sc stop TrkWks
To start it again below command can be used,
sc start <servicename>

25 - 7 C# and .NET Programming


Windows Services, WWF - Basics, Activities and Workflows

25.1.4.6 To Start or Stop a Windows Service

Starting or stopping a service is easy task that can be done by right-click the service (or
tap and hold) and select the desired action. To execute a service, press Start. To stop a
running service, the Stop option is clicked.
Besides Start and Stop there are some other options available. One can also Pause,
Resume or Restart the selected service. The last option is self-explanatory, as for Pause -
it means that the service is stopped, but only for user accounts that do not have
administrative or service privileges, while it still runs for the latter. Naturally, Resume
starts a paused service for those accounts.
The chosen action is applied only to current computing session. After Windows
restarts, the selected service resumes to its default state.

Note - There is an alternative way of starting or stopping a service - one can also do it
from the service's Properties window. Right-click (or press and hold) on the service and
then on Properties. Then, in the General tab, one can find the same options as in the
right-click menu.
25.1.4.7 Changing the Startup Type of a Windows Service

To change the way a Windows service starts, one must first open its Properties. To do
that, right-click (or press and hold) on the service and then on Properties. In the service's
Properties window, the General tab shares information about the service's name, the
display name, description, the path to its executable and the option to modify its startup
type. The second section shares the status of the service and allows to specify custom
start parameters if needed.
The Startup type can be set to,
1. Automatic - The service starts at boot time.
2. Automatic (Delayed Start) - The service starts only after the system has loaded all
the other services set to start automatically.
3. Manual - The service starts only when it is needed.
5. Disabled - The service never starts, even when its functionality is requested by other
Windows services or apps.
Although the startup type can be modified but it is highly recommend that one should
not change the Startup type for the services, unless it is very correctly know that what is
being modified and what will be its consequences. It is especially dangerous to set a
service to be Disabled, as other system components may depend on it. This can lead to a
malfunctioning operating system or app, or even failure to boot.

25 - 8 C# and .NET Programming


Windows Services, WWF - Basics, Activities and Workflows

25.1.4.8 To Enable and Disable Windows Services

Some services can be delayed or even disabled if one needs to squeeze every bit of
performance and to speed up the system. However, that is possible only if those services
are not at all needed right away and disabling them does not cause problems or
inconveniences.
Some services may need to be restarted for troubleshooting purposes if the program they
belong to or the task they perform is not working as it should. Other services may need
to be stopped completely if some software is being reinstalled but an attached service
won't stop on its own, or if it is suspected that the service is being used maliciously.
One should be extremely careful when editing Windows services. Most of them are very
important for everyday tasks, and some of them even depend on other services to work
properly.
With Services open, one can right-click (or press-and-hold) any of the services for more
options, which allows start, stop, pause, resume, or restart it. These options are pretty
self-explanatory.
As said above, some services may need to be stopped if they're interfering with a
software install or uninstall. Say for example that an antivirus program is being
uninstalled, but for some reason the service is not shutting down with the program,
causing the user to be unable to completely remove the program because part of it is still
running. This is a particular case where one would surely require to open Services, find
the appropriate service, and choose Stop so that the normal uninstall process is
continued.
One instance where a service may need to restart is if some printing is going on but
everything keeps getting hung up in the print queue. The common solution for this
problem is to go into Services and choose Restart for the Print Spooler service.
This service should not be completely shut down because the service needs to run in
order for further printing task. Restarting the service shuts it down temporarily, and then
starts it back up, which is just like a simple refresh to get things running normally again.
Some services can't be disabled through regular means because they may have been
installed with a driver that prevents user from disabling it. In such a case one can try
finding and disabling the driver in Device Manager or booting into Safe Mode and
attempting to disable the service there (because most drivers don't load up in Safe
Mode).

25 - 9 C# and .NET Programming


Windows Services, WWF - Basics, Activities and Workflows

Precautions - while the service is to be disabled

Unfortunately, many crapware applications install Windows Services during their


installation process, and use them to keep their nonsense running in the background and
re-launching repeatedly. Other applications implement a Windows Service to provide
functionality that might not required. These are the services that one should disable.
General rule is that Microsoft's built-in Windows services should be left alone -
Windows 8 or even Windows 7 has done a good job of cutting down the services to just
really important functionality, and one won't gain much in the way of resources by
disabling those services.
What should be definitely done is, look for any service that is not part of Windows, and
try to deal with them instead. If there is no idea what the service is, or it is for an
application that is not required to run all the time, then after some research it can be
decided whether to disable it.
Another rule of thumb is 'Don't Disable, Set to Manual'. One of the rules that should
be followed is to avoid disabling services, since that can cause problems and errors.
Instead, just try setting the service to Manual start.
If it is found that a particular service needs to be running, but maybe doesn't need to be
running immediately, it can be set to Automatic (Delayed Start) instead, which will
delay starting until the system calms down after boot.
25.1.4.19 To Delete/Uninstall Windows Services

Deleting a service may be the only option if a malicious program has installed a service
that can't be disabled. Though the option can't be found in the services.msc program, it
is possible to completely uninstall a service in Windows. This won't only shut the
service down but will delete it from the computer, never to be seen again (unless of
course it's installed again).
Uninstalling a Windows service can be done in both the Windows Registry and with the
Service Control utility (sc.exe), similar to svchost.exe, via an elevated Command
Prompt. On Windows 7 or an older Windows OS, the free Comodo Programs
Manager software can be used to delete Windows services, and it's much easier to use
than either method above (but doesn't work in Windows 10 or Windows 8).
25.1.5 Differences between Windows Services and Regular Applications

Launch Mechanism - A regular application is manually launched by the end user from
the desktop or Start Menu. Examples include web browsers, document editing software

25 - 10 C# and .NET Programming


Windows Services, WWF - Basics, Activities and Workflows

and PDF readers. Windows Services start when the machine is switched on. Note
however that regular applications can be added to the Startup folder in the Start Menu in
which case they would start automatically once the operating system startup is
complete.
User Interface - Unlike regular applications, Windows Services do not have a user
interface; they run in the background and the user does not directly interact with them.
A Windows Service does not stop when a user logs off the computer; a regular
application will.
Multiple Instances - Only one instance of a Windows Service runs on a device.
Regular applications can allow multiple copies if several users are logged into the same
machine.
Administrator Rights - Windows Services usually run under administrative privileges
even when a non-administrator user is logged in and using the computer. The average
Windows Service has more control over the machine compared to a regular application.
25.1.6 Examples of Windows Services

Active Directory Service - Active Directory is a service Microsoft developed for


Windows networks. It is included by default in most Microsoft Windows Server
systems. Active Directory oversees centralized domain management and identity-related
functions.
Prefetch and Superfetch Service - Speeds up operating system and application startup
by caching to RAM frequently used files, libraries and application components. It does
this by monitoring application usage and behavior.
Background Intelligent Transfer Service - This service facilitates throttled, prioritized
and asynchronous file transfer between machines via idle bandwidth. It plays a key role
in the delivery of software updates from servers to clients as well as in the transfer of
files on Microsoft's instant messaging applications.
DNS Client Service - This service resolves domain names to IP addresses and locally
caches this data.
Computer Browser Service - It allows users to easily locate shared resources on
neighboring computers. All information is aggregated on one of the computers (referred
to as the Master Browser) and other computers contact this machine for information on
shared resources.

25 - 11 C# and .NET Programming


Windows Services, WWF - Basics, Activities and Workflows

Internet Connection Sharing (ICS) Service - ICS enables the use of one device
connected to the internet as an access point for other devices. Access could be through
Ethernet broadband, cellular service or other gateway.
Routing and Remote Access Service - This service makes it possible to create
applications that manage the remote access and routing capabilities of the Windows
operating system. It allows the machine to act as a network router.
25.1.7 Creating Windows Service

Developers often use Services for functions that are necessary to run in the background,
such as the ability to monitor performance data and react to specified thresholds. Services can
also be created as Microsoft Visual Studio projects, developing code that specifies what
commands can be sent to the service as well as what actions are taken on receipt of those
commands. After creating and building an application it can be installed as a service by
running the command-line utility InstallUtil.exe, then passing the path to the Service's
executable file. Then the Services Control Manager is used to configure the Service.
Alternatively, services can be configured using the Services node in Server Explorer or with
the ServiceController class.
To Create Windows service using C#

Step 1 - Open Visual Studio, go to File > New and select Project. Now select a new project
from the Dialog box and select "Window Service" and click on the OK button.
Step 2 - Go to Visual C# -> "Windows Desktop" -> "Windows Service" and give an
appropriate name and then click OK. Once the OK button is clicked the service screen
appears.
Step 3 - Right-click on the blank area and select "Add Installer".

Adding an Installer to a Windows Service - Before a Windows Service can run, the
Installer should be installed, which registers it with the Service Control Manager. After
Adding Installer, ProjectInstaller will add in the project and ProjectInstakker.cs file will be
open. Now everything can be saved.
Step 4 - Right-click on the blank area and select "View Code".

Step 5 - Its has Constructor which contains Initialize Component method,


The Initialize Component method contains the logic which creates and initializes the user
interface objects dragged on the forming surface and provided the Property Grid of Form

25 - 12 C# and .NET Programming


Windows Services, WWF - Basics, Activities and Workflows

Designer. It should be noted that no other method should be called before the call of
Initialize Component method.
Step 6 - Select InitializeComponent method and press F12 key to go definition

Step 7 - Now to add the below code line,


this.serviceProcessInstaller1.Account
= System.ServiceProcess.ServiceAccount.LocalSystem;
Optionally the description and display service name can be added as shown below,
this.serviceInstaller1.Description = "First Service demo";
this.serviceInstaller1.DisplayName = "FirstService.Demo";

Step 8 - In this step, a timer is set and a code is implemented to call the service at a given
time. A text fine can be created for this and the current time is added in the text file using the
service.
Service1.cs class
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
namespace FirstService {
public partial class Service1: ServiceBase {
Timer timer = new Timer(); // name space(using System.Timers;)
public Service1() {
InitializeComponent();
}
protected override void OnStart(string[] args) {
WriteToFile("Service is started at " + DateTime.Now);
timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
timer.Interval = 5000; //number in milisecinds
timer.Enabled = true;
}
protected override void OnStop() {
WriteToFile("Service is stopped at " + DateTime.Now);
}
private void OnElapsedTime(object source, ElapsedEventArgs e) {
WriteToFile("Service is recalled at " + DateTime.Now);

25 - 13 C# and .NET Programming


Windows Services, WWF - Basics, Activities and Workflows

}
public void WriteToFile(string Message) {
string path = AppDomain.CurrentDomain.BaseDirectory + "\\Logs";
if (!Directory.Exists(path)) {
Directory.CreateDirectory(path);
}
string filepath = AppDomain.CurrentDomain.BaseDirectory + "\\Logs\\ServiceLog_"
+ DateTime.Now.Date.ToShortDateString().Replace('/', '_') + ".txt";
if (!File.Exists(filepath)) {
// Create a file to write to.
using(StreamWriter sw = File.CreateText(filepath)) {
sw.WriteLine(Message);
}
} else {
using(StreamWriter sw = File.AppendText(filepath)) {
sw.WriteLine(Message);
}
}
}
}
}
Code explanation - The above code will call service every 5 seconds and create a folder if
none exists and write the specified message.
Step 9 - Rebuild the application b Right-clicking on project or solution and selecting Rebuild.

Step 10 - Search "Command Prompt" and run as administrator.

Step 11 - Fire the below command in the command prompt and press ENTER.
cd C:\Windows\Microsoft.NET\Framework\v4.0.30319

Step 12 - Now Go to project source folder > bin > Debug and copy the full path of the
Windows Service exe file.
Installing a Windows Service

Open the command prompt and fire the below command and press ENTER.

25 - 14 C# and .NET Programming


Windows Services, WWF - Basics, Activities and Workflows

Syntax
InstallUtil.exe + service path + \ service name + .exe
To check the status of a Windows Service
Open services by following the below steps :
1. Press Window key + R.
2. Type services.msc
3. View the running Service
Check Windows Service Output

The service will create a text file with the following text in it.
The log folder will be created in the bin folder.
Uninstalling a Windows Service,

To uninstall the service, use the below command,


InstallUtil.exe -u + service path + \service name + .exe

25.2 Windows Workflow Foundation (WF / WinWF)

25.2.1 WWF Introduction

Windows Workflow Foundation (WF or WinWF) is Microsoft's programming model


for building workflow-enabled applications in the Windows operating system.
The WWF provides a platform built on the .Net Framework for building workflows. It is
not an application or a server product, and is included as a component of the .Net 3.0
framework. The platform unleashes the power of a completely different paradigm.
WWF gives developers a declarative way to model the "flow" of their application.
WWF also includes APIs for handling long running workflows as well as the ability to
"rehost" the designer inside the custom application to give an extreme amount of
flexibility in building the workflows. WWF was first introduced with .NET 3.0 and
completely overhauled in .NET 4.
A workflow models a production process as a set of activities applied to work in
progress. As such, workflows describe the order of execution and dependency
relationships between activities as the work progresses through the model from start to
finish, as activities are performed by people or system functions.

25 - 15 C# and .NET Programming


Windows Services, WWF - Basics, Activities and Workflows

25.2.2 WWF - Fundamental Concepts and Building Workflows

WWF includes a namespace, a workflow engine and design tools that can be used with
Visual Studio .NET. WWF covers both system and human workflows and it can be used with
both client and server versions of Windows.
25.2.2.1 Workflows

In WWF terminology Workflows are simply a series of steps, decisions and rules needed
to complete a specific task.
Some of the major criteria for workflows are listed below,

1. Visual Representation of process(es)


2. Can be dynamically modified at run-time
3. Can be long-running
There are two major types of workflows -

1. Sequential workflows - Used for well-defined, process workflows. A series of


activities are called in order.
2. State Machine workflows - Organized as state machine diagrams, typically used for
workflows with human interaction. Activities are called on the basis of the 'state' of
different parameters.
Both kinds of workflow solutions can be created in WWF and since workflows are
state-based, WWF provides good support like, if workflow has reached a state where
it would remain untouched for few minutes/hours/days/months, then it would be
'persisted' and can then be restored on any different computer/platform without any
hassle. This and many other features are part of WWF.
Workflows can either be built declaratively by using only Markup, or only Code or a
combination of both Markup and code.
Once the workflow is developed, it can be hosted on any application that can load the
Workflow Runtime such as Windows Forms, Windows Services, ASP.Net Web Sites
and Web Services.
25.2.2.2 Workflow Runtime Engine

Every running workflow instance is created and maintained by an in-process runtime


engine that is commonly referred to as the workflow runtime engine. There can be
several workflow runtime engines within an application domain, and each instance of
the runtime engine can support multiple workflow instances running concurrently.

25 - 16 C# and .NET Programming


Windows Services, WWF - Basics, Activities and Workflows

When a workflow model is compiled, it can be executed inside any Windows process
including,
o Console applications,
o Forms-based applications,
o Windows Services,
o ASP.NET Web sites, and
o Web services.
Because a workflow is hosted in process, a workflow can easily communicate with its
host application.
25.2.2.3 Activities

Activities are the elemental unit of a workflow. Everything in a workflow is an activity,


including the workflow itself. The term workflow is actually a synonym for a collection
of activities. They are added to a workflow programmatically in a manner similar to
adding XML DOM child nodes to a root node. When all the activities in a given flow
path are finished running, the workflow instance is completed.
There are different types of activities which derived from the base class Activity :
o NativeActivity
o CodeActivity
o AsyncCodeActivity
o ActivityWithResult
Activity<T>
NativeActivity<T>
CodeActivity<T>
AsyncCodeActivity<T>
An activity can perform a single action, such as writing a value to a database, or it can
be a composite activity and consist of a set of activities.
Activities deriving from CodeActivity and AsyncCodeActivity can do far less with their
container compare to NativeActivity. For example, the WriteLine activity needs to write
only to the console. Therefore, it doesn't need access to its runtime environment. A more
complex activity might need to schedule other child activities or communicate with
other systems, in which case it must be derived from NativeActivity to access the full
runtime.

25 - 17 C# and .NET Programming


Windows Services, WWF - Basics, Activities and Workflows

Activities have two types of behavior

Runtime - Specifies the actions upon execution.


Design time - Controls the appearance of the activity and its interaction while being
displayed within the designer.
25.2.2.4 Services

The workflow runtime engine uses many services when a workflow instance runs.
WWF provides default implementations of the runtime services that meet the needs of
many types of applications, such as a persistence service, which stores the execution
details of a workflow instance in a SQL database. These service components are
pluggable, which allows applications to provide these services in ways that are unique to
their execution environment. Other types of services used by the runtime engine include
scheduling services, transaction services, and tracking services.
Custom services can be created to extend the WWF platform by deriving from the base
service classes. An example of this would be a persistence service that uses an XML file
instead of a database for storage.
25.2.2.5 Compensation Overview

Compensation is the act of undoing any actions that were performed by a successfully
completed compensable activity because of an exception that occurred elsewhere in a
workflow.
25.2.2.6 Local Communication and Correlation

Host processes can communicate with workflows by exchanging data through custom
local communication services. These local communication services implement user-
defined interfaces that define methods and events that will be passed between the
workflow and the host process.
Host processes can also interact with a specific activity in a specific workflow instance
by using a unique ID that is passed between the host process and the workflow as an
event argument. This is known as correlation.
25.2.2.7 Persistency

WWF simplifies the process of creating stateful, long-running, persistent workflow


applications. The workflow runtime engine manages workflow execution and enables
workflows to remain active for long periods of time and survive application restarts.
This durability is a key principle of WWF. It means that workflows can be unloaded

25 - 18 C# and .NET Programming


Windows Services, WWF - Basics, Activities and Workflows

from memory while awaiting for input and serialized into a persistent store, such as a
SQL database or XML file. Whenever the input is received, the workflow runtime
engine loads the workflow state information back into memory and continues execution
of the workflow.
WWF provides the SqlWorkflowPersistenceService that integrates well with Microsoft
SQL Server to persist workflow information easily and efficiently. Own persistence
service can be created and can store workflow state information anywhere by deriving
from the WorkflowPersistenceService base class.
25.2.2.8 Tracking

Tracking is the ability to specify and capture information about workflow instances and
store that information as the instances execute. WWF provides the SqlTrackingService,
which is a tracking service that uses a SQL database to store the collected tracking
information. Own tracking service can be written to collect and store this information in
any format that application requires.
When a new workflow is created, the tracking service requests a tracking channel to be
associated with that workflow. All of the tracking information from the workflow is
then sent to this tracking channel.
The tracking service can track three types of events,
1. Workflow instance events,
2. Activity events, and
3. User events.
The type and amount of information to be received can be configured for the service for
a particular workflow instance or types of workflow by providing a tracking profile.
The tracking framework also provides the ability to extract information about activities
or the workflow during an event. If a specific property or field in the activity or
workflow needs to be tracked, this information can be provided in the extracts section of
the tracking profile, and that information will be extracted during the specified event.
25.2.2.9 Serialization

Workflows, activities, and rules can be serialized and de-serialized. This enables to
persist them, use them in workflow markup files, and view their properties, fields, and
events in a workflow designer.
WWF provides default serialization capabilities for standard activities, or one can create
own for custom activities. For example, with a custom activity serializer, one can decide

25 - 19 C# and .NET Programming


Windows Services, WWF - Basics, Activities and Workflows

which members are serialized and how they are serialized. This determines if those
members are visible or hidden in a workflow designer.
25.2.2.10 Workflow Changes

WWF enables to dynamically update the workflow instance and declarative rules during
run time. Before activities are scheduled for execution, one can change expected
behaviors, flow control, and so on. This ability enables to modify business processing
logic without having to recompile and restart the workflow.
25.2.2.11 Rules and Conditions

WWF can implement business logic as either rules or conditions.


Conditions

Conditions are used by IfElseBranchActivity, ConditionedActivityGroup,


WhileActivity, and ReplicatorActivity activities to control activity execution. Conditions can
be expressed as declarative, or defined in code. Declarative conditions are created as code
DOM statements in the rules' XML file. Code-based conditions reference a method in the
workflow's code file that returns its result through the Result property.
Rules

Rules, like conditions, are expressed as code DOM statements, and are collected in the
rules XML file. Rules include a condition statement and collections of actions that are
performed based on the result of the condition. Rules are collected into rule sets, which
support both simple sequential execution of rules, and sophisticated forward-chaining of
rules. Rule sets are executed by the PolicyActivity activity.
A key advantage of defining the logic with rules and declarative conditions is that they
can be modified at run time by doing dynamic updates using workflow changes. In
addition, rules separate the business logic from a workflow in order to share those rules
with other workflows. Finally, defining business logic in rules allows for advanced
tools, such as dependency visualization and impact analysis tools, to be built on top of
the object model.
25.2.2.12 Fault Handling

Exceptions that occur in activities are handled asynchronously by the workflow runtime
engine in a process called fault handling. Exceptions are scheduled in a queue to be handled
later. If the exception type matches the one that is handled by a particular
FaultHandlerActivity activity, that activity will handle the exception. If the exception cannot

25 - 20 C# and .NET Programming


Windows Services, WWF - Basics, Activities and Workflows

be handled, it is bubbled up through parent activities until it ultimately causes the termination
of the workflow instance.
25.2.2.13 Workflow Markup

Workflow markup, which is based on Extensible Application Markup Language (XAML),


enables developers and designers to model business logic declaratively and separate it from
lower-level implementation details that are modeled by code-beside files. Because workflows
can be modeled declaratively, it is possible to activate a workflow by directly loading a
workflow markup file into the workflow runtime engine at run time.
25.2.2.14 Correlation

Correlation is the mechanism for relating workflow service messages to each other or to the
application instance state, such as a reply to an initial request, or a particular order ID to the
persisted state of an order-processing workflow.
Types of Correlation

Correlation can be protocol-based or content-based. Protocol-based correlations use data


provided by the message delivery infrastructure to provide the mapping between
messages. Messages that are correlated using protocol-based correlation are related to
each other using an object in memory, such as a RequestContext, or by a token provided
by the transport protocol. Content-based correlations relate messages to each other using
application-specified data. Messages that are correlated using content-based correlation
are related to each other by some application-defined data in the message, such as a
customer number.
Activities that participate in correlation use a CorrelationHandle to tie the messaging
activities together. For example, a Send that is used to call a service and a subsequent
Receive that is used to receive a callback from the service, share the same
CorrelationHandle. This basic pattern is used whether the correlation is content based or
protocol based. The correlation handle can be explicitly set on each activity or the
activities can be contained in a CorrelationScope activity. Activities contained in a
CorrelationScope have their correlation handles managed by the CorrelationScope and
do not require the CorrelationHandle to be explicitly set.
A CorrelationScope scope provides CorrelationHandle management for a request-reply
correlation and one additional correlation type. Workflow services hosted using
WorkflowServiceHost have the same default correlation management as the
CorrelationScope activity. This default correlation management generally means that in
many scenarios, messaging activities in a CorrelationScope or a workflow service do

25 - 21 C# and .NET Programming


Windows Services, WWF - Basics, Activities and Workflows

not require their CorrelationHandle set unless multiple messaging activities are in
parallel or overlap, such as two Receive activities in parallel, or two Send activities
followed by two Receive activities.
25.2.3 WWF Benefits

1. It's visual

Humans are naturally visual communicators and a lot of times it's easier to describe
complex ideas through visual imagery. One of the hardest part of the development process is
not writing code. It's communicating across a wide range of people in different disciplines to
learn and understand what exactly being built. Business people don't always understand the
code and developers don't always understand the business vocabulary but both can understand
lines and boxes drawn a whiteboard. Workflow gives the capability of representation of the
code's implementation of the process. This makes it much easier to communicate and can help
head off confusion earlier in the process. Even a blank workflow can be added and code can
be dropped in it to create a rough outline of what going to build. By this complex processes
become easier to understand.
2. It naturally lends itself to testability

The smallest component of a Workflow is a Code Activity. Each activity should do one
thing and one thing only and Unit Tests around them. Code Activities pass data in and out of
them through arguments which makes it extremely easy to Mock. AlsoWorkflow includes its
own Service Locator pattern called "Workflow Extensions" which is easy to implement and
efficient. Just like Code Activities, Workflows have arguments that can take data into and get
data out of so can easily mock. This can greatly speed feedback from tests because there are
no external dependencies. Further all the workflows are grouped into a main Workflow,
commonly the Workflow hosting service. Here automated regression suite test can be done for
the service from end to end.
3. It is good for long running processes

Combined with AppFabric there can be long running processes which can spin up and spin
down as necessary. This makes more efficient use of the resources since when a Workflow is
not running its state is preserved in the database and only processing at the moment an event
causes it to reinitialize.
4. It is built into the .NET Framework

For WWF to work there are no frameworks to download and install. It is just there
integrated in .NET. It's built on some of Microsoft's core battle-tested technologies like WCF

25 - 22 C# and .NET Programming


Windows Services, WWF - Basics, Activities and Workflows

and XAML. The developer has to just identify a process to be replaced with Workflow and
start from there. Workflows can be invoked from the existing code.
5. Workflows can be removed easily.

If for some reason developer wants to move away from Workflow then there is a visual
guide of how the processes are built and all code activities are written in C#.
25.2.4 WWF Limitations and Performance Issues

Despite being a popular workflow component for .NET solutions, WWF suffers from
various flaws. The claimed value of the visual representation that WWF is said to bring
has poor performance. In particular, as workflow gets more complex, the slower the
designer becomes. Workflows that amount to 100 kB take more than a minute to load,
whereas their debugging becomes virtually impossible.
Besides, whenever there's an error within the workflow related to persistence,
communication or correlation, the trace logs do not contain any meaningful information
which can tell exactly what went wrong. It takes developers many hours of trial and
error to find the root cause of the problem.
Below are other concerns that WWF users have specified,
o WWF does not have any built-in upgrade strategy that would keep existing
workflows running once a bug fix is done.
o Implementing a WWF state machine through WWF seems to hide the
WorkflowRuntime.
o There is a problem unit-testing WWF activities, yielding an exception, which, in
turn, requires the development of a workaround solution.
o Workflows use a large amount of memory, whereas workflows are much slower
than plain C#.
Simple 1 or 2-line statements in C# become fairly large block activities in WWF,
effectively limiting the programming features.
WWF is not flexible in terms of allowing developers to implement custom functionality
not provided by it.
WWF can and will corrupt an application state that cannot be recovered.

WCF XAML services do not seem to implement everything in an interface.


WWF has a steep learning curve.

25 - 23 C# and .NET Programming


Windows Services, WWF - Basics, Activities and Workflows

25.2.5 Workflow Important Terms Summary

Sr. No. Term Definition


1. Activity A unit of program behavior in WWF. Single activities can be
composed together into more complex activities.
2. Activity Action A data structure used to expose callbacks for workflow and activity
execution.
3. Argument Defines the data flow into and out of an activity. Each argument has
a specified direction: in, out, or in/out. These represent the input,
output, and input/output parameters of the activity.
4. Bookmark The point at which an activity can pause and wait to be resumed.
5. Compensation A group of actions designed to undo or mitigate the effect of
previously completed work.
6. Correlation The mechanism for routing messages to a workflow or service
instance.
7. Expression A construct that takes in one or more arguments, performs an
operation on the arguments and returns a single value. Expressions
can be used anywhere an activity can be used.
8. Flowchart A well-known modeling paradigm that represents program
components as symbols linked together with directional arrows. In
the .NET Framework 4, workflows can be modeled as flowcharts
using the Flowchart activity.
9. Long-running A unit of program execution that does not return immediately and
Process may span system restarts.
10. Persistence Saving the state of a workflow or service to a durable medium, so
that it can be unloaded from memory or recovered after a system
failure.
11. State Machine A well-known modeling paradigm that represents program
components as individual states linked together with event-driven
state transitions. Workflows can be modeled as state machines using
the StateMachine activity.
12. Substance Represents a group of related bookmarks under a common identifier
and allows the runtime to make decisions about whether a particular
bookmark resumption is valid or may become valid.

25 - 24 C# and .NET Programming


Windows Services, WWF - Basics, Activities and Workflows

13. Type A CLR type can be associated with one or more


Converter System.ComponentModel.TypeConverter derived types that enable
converting instances of the CLR type to and from instances of other
types. A type converterr is associated with a CLR type using the
System.ComponentModel.TypeConverterAttribute attribute. A
TypeConverterAttribute can be specified directly on the CLR type or
on a property. A type converter specified on a property always takes
precedence over a type converter specified on the CLR type of the
property.
14. Variable Represents the storage of some data that must be saved and accessed
later.
15. Workflow A single activity or tree of activities invoked by a host process.
16. XAML eXtensible Application Markup Language

Two Marks Questions with Answers

Q.1 What is Windows Workflow Foundation (WF) ?


Ans. : Windows Workflow Foundation (WF) is a technology that was first introduced in
.NET Framework 3.0. WF consists of a programming model, a workflow runtime engine,
workflow designer, a rules engine, and tools to quickly build workflow-based applications
on Windows. WF facilitates the separation between the business process code and the
actual implementation code.
Q.2 What are the components of WF 4.0 ?
Ans. : WF consists of several components that work together to create desired workflow.
The components of WF are given as follows :
Workflows and activities
Base activity library
Custom activities
Host process
Activity data mode!
Runtime engine
Runtime services
Q.3 What are the four workflow principles ?
Ans. : According to Microsoft, there are four major principles that explain the behavior and
working of workflows. Developers can use these principles while developing workflow-
based applications. The four principles are as follows :

25 - 25 C# and .NET Programming


Windows Services, WWF - Basics, Activities and Workflows

Workflows help in coordinating the work performed by people and software.


Workflows are long-running and stateful.
Workflows are based on extensible models.
Workflows remain transparent and dynamic throughout their lifecycle.
Q.4 How can you implement a condition in a workflow ?
Ans. : You can implement a condition by using either of the following ways :
By creating a rule condition : Specifies that you can implement conditions either directly
in code or by using a tool, called the Rule Condition Editor. Rule conditions are stored in a
separate Extensible Markup Language (XML) file. When a rule condition occurs in a
workflow, the expression in a condition is evaluated and a Boolean value is returned.
By creating a code condition : Refers to defining a condition directly in code. A code
condition can be created by writing a method in the code. The method contains code for the
condition and returns a Boolean value.
Q.5 What is a runtime engine ?
Ans. : A runtime engine of WF provides the basic functionality to execute and manage the
workflow lifetime. It runs within the host process and is responsible for executing each
workflow instance. A host process can interact with multiple runtime engines at a time,
where each engine executes multiple workflow instances.
The host process interacts with runtime engine by using any of the following classes :
1. WorkflowInvoker : Invokes a workflow as its method.
2. WorkflowApplication : Controls the execution of a single workflow instance
explicitly.
3. WorkflowServiceHost : Hosts the workflows and allows sending and receiving
messages among various instances of workflows.

Long Answered Questions

Q.1 Explain WWF. (Refer section 25.2)


Q.2 What are WWF activities ? (Refer section 25.2)
Q.3 What are workflows in WWF ? (Refer section 25.2)
Q.4 What is tracking in WWF ? (Refer section 25.2)
Q.5 Explain rules and conditions WWF. (Refer section 25.2)

Windows Services, WWF - Basics, Activities and Workflows ends …

25 - 26 C# and .NET Programming

You might also like