Professional Documents
Culture Documents
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
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
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
1. Using .NET Framework coupled with C# enables the creation of Windows applications,
Web services, database tools, components, controls.
7. Properties Window
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.
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).
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.)
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.
The code has partial class Form1. It's partial because some code is hidden from
developer.
It's in Designer view that controls like buttons and text boxes are added to form.
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.
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.
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.
Fig. 20.3.4 IDE with setting the properties for the solution, project, and Windows Forms form
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
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.
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.
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.
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.
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.
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,
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
ToString Overridden.
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 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 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.)
MouseDoubleClick Occurs when the user double-clicks the Button control with the mouse.
Example
using System;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
20.5.2 TextBox
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.)
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.)
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.)
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.)
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.
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.)
GetFirstCharIndexOfCurrentLine Retrieves the index of the first character of the current line.
(Inherited from TextBoxBase.)
ScrollToCaret Scrolls the contents of the control to the current caret position.
(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 addnum() {
BtnAdd.Text = "Add";
this.Controls.Add(bsum);
20.5.3 Label
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.
DefaultSize Overridden.
FlatStyle Gets or sets the flat style appearance of the label control.
ImageList Gets or sets the ImageList that contains the images to display in the
Label control.
Text Overridden.
GetPreferredSize Overridden.
Important Events
Example
using System;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
20.5.4 CheckBox
Appearance Gets or sets the value that determines the appearance of a CheckBox
control.
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.
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.)
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.
Events
AutoSizeChanged Occurs when the value of the AutoSize property changes. (Inherited
from ButtonBase.)
ImeModeChanged Occurs when the ImeMode property is changed. This event is not
relevant for this class. (Inherited from ButtonBase.)
Example
using System;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
if (chb1.Checked == true)
{
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
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.)
CheckAlign Gets or sets the location of the check box portion of the
RadioButton.
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.)
ForeColor Gets or sets the foreground color of the control. (Inherited from
Control.)
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.)
Methods
Events
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();
}
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.)
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.
FormatString Gets or sets the format-specifier characters that indicate how a value
is to be displayed. (Inherited from ListControl.)
IntegralHeight Gets or sets a value indicating whether the control should resize to
avoid showing partial items.
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.
SelectedText Gets or sets the text that is selected in the editable portion of a
ComboBox.
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.)
Methods
BeginUpdate Maintains performance when items are added to the ComboBox one at
a time.
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.
GetItemText Returns the text representation of the specified item. (Inherited from
ListControl.)
ResetText Overridden.
Select Overloaded.
SelectAll Selects all the text in the editable portion of the ComboBox.
Events
BackgroundImageChanged Occurs when the value of the BackgroundImage property
changes.
SelectionChangeCommitted Occurs when the selected item has changed and that change
is displayed in the ComboBox.
TextUpdate Occurs when the control has formatted the text, but before
the text is displayed.
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
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.
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.)
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.
MultiColumn Gets or sets a value indicating whether the ListBox supports multiple
columns.
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.)
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.
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.)
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.
RefreshItems Overridden. Refreshes all ListBox items and retrieves new strings for them.
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)
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.
20.5.8 PictureBox
ErrorImage Gets or sets the image to display when an error occurs during the image-
loading process or if the image load is canceled.
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.
Methods
Events
Example
using System;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
}
}
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.
Properties
ImageSize Gets or sets the size of the images in the image list.
Tag Gets or sets an object that contains additional data about the ImageList.
Methods
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.
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
9. Creating menus
Examples
Menu example
3. The menu strip is inserted on the form. Appropriately name the menu . The form looks as
follows.
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.
6. After adding the separator the menu looks as follows. Here, 2 separators are added.
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;
namespace WindowsFormsApplicationMenus
{
public partial class FrmMenu : Form
{
public FrmMenu()
{
InitializeComponent();
}
}
}
Output
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.
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
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.
}
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
}
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.
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; }
}
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();
}
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();
}
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,
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.
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.
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
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.
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.
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);
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#
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.
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)
Event
Event Description
argument
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.
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 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).
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 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);
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);
namespace ProgrammingControlEvents
{
public class HelloWorld : System.Windows.Forms.Form
{
public HelloWorld( )
{
Text = "Hello World";
Controls.Add(btn);
}
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. :
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.
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();
}
flowPanel.Dock = DockStyle.Fill;
flowPanel.BorderStyle = BorderStyle.FixedSingle;
button.Text = "Quit";
button.AutoSize = true;
button.Click += new EventHandler(OnClick);
flowPanel.Controls.Add(button);
Controls.Add(flowPanel);
CenterToScreen();
}
[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;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplicationDemo
{
public partial class FormMouseUp : Form
{
public FormMouseUp()
{
InitializeComponent();
}
21.14 Event 21 - 47
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.
Concept
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.
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.
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.
Concept
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.
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.
Concept
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.
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 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
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.
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.
6. Add webform (as per application requirement) following steps, Right click solution in
solution explorer and Add-> Item
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
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.
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
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.
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.
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">
</STRONG></FONT></P>
</body>
</html>
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.
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
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
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
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.
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.
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.
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.
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.
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 :
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 :
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.
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
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.11.2 Global.asax
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 ...%>
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.
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.
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
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
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
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.
<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.
ChildControlCreated It indicates whether the server control's child controls have been
created.
DisabledCssClass Gets or sets the CSS class to apply to the rendered HTML element
when the control is disabled.
Font Font.
HasChildViewState Indicates whether the current server control's child controls have
any saved view-state settings.
LoadViewStateById It indicates whether the control participates in loading its view state
by ID instead of index.
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.
TabIndex Gets or sets the tab index of the Web server 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.
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.
Method Description
ApplyStyleSheetSkin Applies the style properties defined in the page style sheet to
the control.
ClearChildViewState Deletes the view-state information for all the server control's
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.
FindControl(String, Int32) Searches the current naming container for a server control
with the specified id and an integer.
HasEvents Indicates whether events are registered for the control or any
child controls.
MapPathSecure Retrieves the physical path that a virtual path, either absolute
or relative, maps to.
OnBubbleEvent Determines whether the event for the server control is passed
up the page's UI server control hierarchy.
RenderBeginTag Renders the HTML opening tag of the control to the specified
writer.
RenderEndTag Renders the HTML closing tag of the control into the
specified writer.
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.
TrackViewState Causes the control to track changes to its view state so that
they can be stored in the object's view state property.
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.
CheckBox <asp:CheckBox > Display single check box, which can be connected to
an item of the ADO.NET data source
21.14 Event
Concept
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
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
AdRotator AdCreated
BulletedList Click
Button Click
Calender SelectionChanged
CheckBox CheckedChanged
CheckBoxList SelectedIndexChanged
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" %>
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
</asp:Label>
<br />
<br />
<br />
</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 {
if (Page.IsPostBack) {
lblmessage.Text += "Page post back event handled.<br/>";
}
}
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.
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.
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.
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
/* In the Page Load event of a page the values from view state are retrieved if view
state is not empty. */
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. */
/* 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;
}
}
/*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.*/
/* 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.
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
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.
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.
<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
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" />
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.
>Click</a>
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
{
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)
{
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()
{}
}
}
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.
RepeatLayout = "Flow"
or
DataList1.RepeatLayout = RepeatLayout.Flow
10) Example
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();
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.
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
namespace Repeater
{
public partial class ListPage : System.Web.UI.Page
{
//Creating a Table
DataTable dt = new DataTable();
{
//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));
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
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
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
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
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.
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.
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
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
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.
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.
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
WCF has a layered architecture that support for developing various distributed
applications.
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.
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.
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.
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.
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
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.
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) 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.
(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.
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
Notes
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.
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.
4. Then right-click on Solution Explorer - "Add New Item" - the web service templates pop
up.
5. Select Web Service Template and click on add button. After that the Solution Explorer
look like as,
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>
[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;
}
[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.
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.
<html>
<body>
<form action="http://localhost/.../Service.asmx/Multiply" method="POST">
<input name="n1"></input>
<input name="n2"></input>
AU : May-18, Dec.-18
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
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.
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
SqlDataAdapter1.SelectCommand.Parameters.Item("@affiliate").Value = AffiliateID
SqlDataAdapter1.Fill(DsAffiliatePurchase1, "purchase")
GetAffiliateDetail = DsAffiliatePurchase1
End Function
The working explanation
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.
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>
sqlDataAdapter2.Fill(ds.Brands);
sqlDataAdapter1.Fill(ds.Instruments);
return ds;
}
[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)
{
}
For the untyped web service the same coding pattern as in the typed service is followed.
[WebMethod]
public string UpdateInstruments(DataSet ds)
{
using (DataComponent dc = new DataComponent(this.Container))
{ return dc.UpdateInstruments(ds); }
}
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();
}
}
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();
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);
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.
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;
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;
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);
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.
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
24.4 Domains 24 - 5
24.5 Contexts 24 - 5
24.6 Proxies 24 - 5
Concept
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.
Explanation
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).
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.
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
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.
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.
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.
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.
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.
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();
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
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
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.*/
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.
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..
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.
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.
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.
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.
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
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.
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>
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.
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).
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
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
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".
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 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);
}
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 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.
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,
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,
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
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
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
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
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
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
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
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
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.