DOTNET Notes by Shivani Deopa
DOTNET Notes by Shivani Deopa
NET Technologies
SIUSCS46
By Shivani Deopa
The .NET Framework
• .NET Core is the latest general purpose development platform maintained by
Microsoft. It works across different platforms and has been redesigned in a way
that makes .NET fast, flexible and modern.
• This happens to be one of the major contributions by Microsoft. Developers can
now build Android, iOS, Linux, Mac, and Windows applications with .NET, all in
Open Source.
• Characteristics of .NET Core
• Open source
1. .NET Core is an open source implementation, using MIT and Apache 2 licenses.
2. .NET Core is a .NET Foundation project and is available on GitHub.
3. As an open source project, it promotes a more transparent development
process and promotes an active and engaged community.
• Cross-platform
1. Application implemented in .NET Core can be run and its code can be reused regardless of your
platform target.
2. It currently supports three main operating systems (OS)
3. Windows
4. Linux
5. MacOS
6. The supported Operating Systems (OS), CPUs and application scenarios will grow over time,
provided by Microsoft, other companies, and individuals.
• Flexible deployment
1. There can be two types of deployments for .NET Core applications −
2. Framework-dependent deployment
3. Self-contained deployment
4. With framework-dependent deployment, your app depends on a system-wide version of .NET
Core on which your app and third-party dependencies are installed.
5. With self-contained deployment, the .NET Core version used to build your application is also
deployed along with your app and third-party dependencies and can run side-by-side with
other versions.
• Command-line tools
• Compatible
1. .NET Core is compatible with .NET Framework, Xamarin and Mono, via the .NET Standard Library
• Modular
2. .NET Framework is one large assembly that contains most of the core functionalities.
4. This modular approach enables the developers to optimize their app by including just those NuGet
packages which they need in their app.
5. The benefits of a smaller app surface area include tighter security, reduced servicing, improved
performance, and decreased costs in a pay-for-what-you-use model.
.NET Languages
• .NET is a software framework which is designed and developed by Microsoft. The
first version of the .Net framework was 1.0 which came in the year 2002.
• In easy words, it is a virtual machine for compiling and executing programs
written in different languages like C#, VB.Net etc.
• It is used to develop Form-based applications, Web-based applications, and Web
services.
• There is a variety of programming languages available on the .Net platform,
VB.Net and C# being the most common ones. It is used to build applications for
Windows, phone, web, etc. It provides a lot of functionalities and also supports
industry standards.
• .NET Framework supports more than 60 programming languages in which 11
programming languages are designed and developed by Microsoft.
• The remaining Non-Microsoft Languages which are supported by .NET
Framework but not designed and developed by Microsoft.
11 Programming Languages which are designed and developed by Microsoft are:
• C#.NET
• VB.NET
• C++.NET
• J#.NET
• F#.NET
• JSCRIPT.NET
• WINDOWS POWERSHELL
• IRON RUBY
• IRON PYTHON
• C OMEGA
• ASML(Abstract State Machine Language)
Main Components of .NET Framework
• Common Language Runtime(CLR):
CLR is the basic and Virtual Machine component of the .NET Framework. It is the
run-time environment in the .NET Framework that runs the codes and helps in
making the development process easier by providing the various services such as
remoting, thread management, type-safety, memory management, robustness,
etc.. Basically, it is responsible for managing the execution of .NET programs
regardless of any .NET programming language. It also helps in the management of
code, as code that targets the runtime is known as the Managed Code and code
doesn’t target to runtime is known as Unmanaged code.
• Framework Class Library(FCL):
It is the collection of reusable, object-oriented class libraries and methods, etc that
can be integrated with CLR. Also called the Assemblies. It is just like the header files
in C/C++ and packages in the java. Installing .NET framework basically is the
installation of CLR and FCL into the system.
C# Language
• C# is a general-purpose, modern and object-oriented programming
language pronounced as “C sharp”.
• It was developed by Microsoft led by Anders Hejlsberg and his team
within the .Net initiative and was approved by the European
Computer Manufacturers Association (ECMA) and International
Standards Organization (ISO).
• C# is among the languages for Common Language Infrastructure and
the current version of C# is version 7.2. C# is a lot similar to Java
syntactically and is easy for the users who have knowledge of C, C++
or Java.
Why C#?
• C# has many other reasons for being popular and in demand. Few of the reasons are
mentioned below:
1.Easy to start: C# is a high-level language so it is closer to other popular programming
languages like C, C++, and Java and thus becomes easy to learn for anyone.
2.Widely used for developing Desktop and Web Application: C# is widely used for
developing web applications and Desktop applications. It is one of the most popular
languages that is used in professional desktop. If anyone wants to create Microsoft apps,
C# is their first choice.
3.Community:The larger the community the better it is as new tools and software will be
developing to make it better. C# has a large community so the developments are done to
make it exist in the system and not become extinct.
4.Game Development: C# is widely used in game development and will continue to
dominate. C# integrates with Microsoft and thus has a large target audience. The C#
features such as Automatic Garbage Collection, interfaces, object-oriented, etc. make C#
a popular game developing language.
C# Syntax
using System;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
Comments
• Single-line comments start with two forward slashes (//). Any text between // and the end of the
line is ignored by C#
Ex:
// This is a comment
Console.WriteLine("Hello World!");
• Multi-line comments start with /* and ends with */. Any text between /* and */ will be ignored
by C#.
Ex:
/* The code below will print the words Hello World
to the screen, and it is amazing */
Console.WriteLine("Hello World!");
Variables and Data Types
• Variables are containers for storing data values.
• In C#, there are different types of variables (defined with different keywords), for example:
1. int - stores integers (whole numbers), without decimals, such as 123 or -123
2. double - stores floating point numbers, with decimals, such as 19.99 or -19.99
3. char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes
4. string - stores text, such as "Hello World". String values are surrounded by double quotes
5. bool - stores values with two states: true or false
Example:
int myNum = 5; // Integer (whole number)
double myDoubleNum = 5.99D; // Floating point number
char myLetter = 'D'; // Character
bool myBool = true; // Boolean
string myText = "Hello"; // String
Variable Operations
• In C#, there are two types of casting:
• Implicit Casting (automatically) - converting a smaller type to a larger type size
char -> int -> long -> float -> double
Example:
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double
Console.WriteLine(myInt); // Outputs 9
Console.WriteLine(myDouble); // Outputs 9
Example:
int myInt = 10;
double myDouble = 5.25;
bool myBool = true;
Example:
Console.WriteLine("Enter username:");
string userName = Console.ReadLine();
Console.WriteLine("Username is: " + userName);
• The Console.ReadLine() method returns a string. Therefore, you cannot get information from another data
type, such as int. The following program will cause an error:
Example:
Console.WriteLine("Enter your age:");
int age = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Your age is: " + age);
Method
• A method is a group of statements that together perform a task. Every C# program has at least
one class with a method named Main.
• To use a method, you need to −
1. Define the method
2. Call the method
• Defining Methods in C#
When you define a method, you basically declare the elements of its structure. The syntax for
defining a method in C# is as follows −
using System;
namespace CalculatorApplication {
class NumberManipulator {
public int FindMax(int num1, int num2) {int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;}
static void Main(string[] args) {int a = 100;
int b = 200;
int ret;
NumberManipulator n = new NumberManipulator();
ret = n.FindMax(a, b);
Console.WriteLine("Max value is : {0}", ret );
Console.ReadLine();
} } }
Defining a Class
• A class definition starts with the keyword class followed by the class name; and the class body enclosed by a pair of curly braces.
Following is the general form of a class definition −
namespace namespace_name {
// code declarations
}
• To call the namespace-enabled version of either function or variable, prepend the namespace
name as follows −
namespace_name.item_name;
using System;
namespace first_space {
class namespace_cl {
public void func() {Console.WriteLine("Inside first_space"); }
}
}
namespace second_space {
class namespace_cl {
public void func() {Console.WriteLine("Inside second_space");}
}
}
class TestClass {
static void Main(string[] args) {
first_space.namespace_cl fc = new first_space.namespace_cl();
second_space.namespace_cl sc = new second_space.namespace_cl();
fc.func();
sc.func();
Console.ReadKey();
}
}
• An Assembly is a basic building block of .Net Framework applications. It is basically a compiled
code that can be executed by the CLR. An assembly is a collection of types and resources that are
built to work together and form a logical unit of functionality. An Assembly can be a DLL or exe
depending upon the project that we choose.
• Assemblies are basically the following two types:
Private Assembly
Shared Assembly
1. Private Assembly
• It is an assembly that is being used by a single application only. Suppose we have a project in
which we refer to a DLL(Dynamic Link Libraries) so when we build that project that DLL will be
copied to the bin folder of our project. That DLL becomes a private assembly within our project.
Generally, the DLLs that are meant for a specific project are private assemblies.
2. Shared Assembly
• Assemblies that can be used in more than one project are known to be a shared assembly. Shared
assemblies are generally installed in the GAC(Global Assembly Csche). Assemblies that are
installed in the GAC are made available to all the .Net applications on that machine.
Inheritance
• Inheritance is an important pillar of OOP(Object Oriented Programming). It is the
mechanism in C# by which one class is allowed to inherit the features(fields and
methods) of another class.
Important terminology:
• Super Class: The class whose features are inherited is known as super class(or a
base class or a parent class).
• Sub Class: The class that inherits the other class is known as subclass(or a derived
class, extended class, or child class). The subclass can add its own fields and
methods in addition to the superclass fields and methods.
• Reusability: Inheritance supports the concept of “reusability”, i.e. when we want
to create a new class and there is already a class that includes some of the code
that we want, we can derive our new class from the existing class. By doing this,
we are reusing the fields and methods of the existing class.
• Single Inheritance: In single inheritance, subclasses inherit the features of one
superclass. In image below, the class A serves as a base class for the derived class
B.
• Multilevel Inheritance: In Multilevel Inheritance, a derived class will be inheriting
a base class and as well as the derived class also act as the base class to other
class. In below image, class A serves as a base class for the derived class B, which
in turn serves as a base class for the derived class C.
• Hierarchical Inheritance: In Hierarchical Inheritance, one class serves as a
superclass (base class) for more than one subclass. In below image, class A serves
as a base class for the derived class B, C, and D.
• Multiple Inheritance(Through Interfaces):In Multiple inheritance, one class can
have more than one superclass and inherit features from all parent classes.
Please note that C# does not support multiple inheritance with classes. In C#, we
can achieve multiple inheritance only through Interfaces. In the image below,
Class C is derived from interface A and B.
• Hybrid Inheritance(Through Interfaces): It is a mix of two or more of the above
types of inheritance. Since C# doesn’t support multiple inheritance with classes,
the hybrid inheritance is also not possible with classes. In C#, we can achieve
hybrid inheritance only through Interfaces.
ASP.NET
• ASP.NET is a web development platform, which provides a programming model, a comprehensive software
infrastructure and various services required to build up robust web applications for PC, as well as mobile
devices.
• ASP.NET works on top of the HTTP protocol, and uses the HTTP commands and policies to set a browser-to-
server bilateral communication and cooperation.
• ASP.NET is a part of Microsoft .Net platform. ASP.NET applications are compiled codes, written using the
extensible and reusable components or objects present in .Net framework. These codes can use the entire
hierarchy of classes in .Net framework.
• The ASP.NET application codes can be written in any of the following languages:
• C#
• Visual Basic.Net
• Jscript
• J#
• ASP.NET is used to produce interactive, data-driven web applications over the internet. It consists of a large
number of controls such as text boxes, buttons, and labels for assembling, configuring, and manipulating
code to create HTML pages
Anatomy of a Web Form - Page Directive,
Doctype
• An ASP.NET page is made up of a number of server controls along with
HTML controls, text, and images.
• Sensitive data from the page and the states of different controls on the
page are stored in hidden fields that form the context of that page request.
• An ASP.NET page is also a server side file saved with the .aspx extension.
• It is modular in nature and can be divided into the following core sections:
1. Page Directives
2. Code Section
3. Page Layout
1. Page Directives
• The page directives set up the environment for the page to run. The @Page directive
defines page-specific attributes used by ASP.NET page parser and compiler. Page
directives specify how the page should be processed, and which assumptions need to be
taken about the page.
• It allows importing namespaces, loading assemblies, and registering new controls with
custom tag names and namespace prefixes.
2. Code Section
• The code section provides the handlers for the page and control events along with other
functions required. We mentioned that, ASP.NET follows an object model. Now, these
objects raise events when some events take place on the user interface, like a user clicks
a button or moves the cursor. The kind of response these events need to reciprocate is
coded in the event handler functions. The event handlers are nothing but functions
bound to the controls.
• The code section or the code behind file provides all these event handler routines, and
other functions used by the developer. The page code could be precompiled and
deployed in the form of a binary assembly.
3. Page Layout
• The page layout provides the interface of the page. It contains the server controls, text,
inline JavaScript, and HTML tags.
Adding Event Handlers
• An event is an action or occurrence such as a mouse click, a key press, mouse
movements, or any system-generated notification. A process communicates
through events.
• For example, interrupts are system-generated events. When events occur, the
application should be able to respond to it and manage it.
• Events in ASP.NET raised at the client machine, and handled at the server
machine.
• For example, a user clicks a button displayed in the browser. A Click event is
raised. The browser handles this client-side event by posting it to the server.
• The server has a subroutine describing what to do when the event is raised; it is
called the event-handler.
• Therefore, when the event message is transmitted to the server, it checks
whether the Click event has an associated event handler. If it has, the event
handler is executed.
• 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);
By Shivani Deopa
Web Controls:
Web Controls:
• The Web controls reside in the System.Web.UI.WebControls namespace, which is
available to all Web Forms pages automatically.
• They provide a range of functionality, from simple data entry to complex data validation.
• Two classes are considered to be base classes of ASP.NET server controls:
System.Web.UI.Control and System.Web.UI.WebControls.WebControl.
• Web controls fall into eight categories: input, display, action, selection, databound, rich,
validation
• They have properties, methods, and events that can be accessed at run time from code
running on the server.
• Controls are small building blocks of the graphical user interface, which include text
boxes, buttons, check boxes, list boxes, labels, and numerous other tools. Using these
tools, the users can enter data, make selections and indicate their preferences.
• Controls are also used for structural jobs, like validation, data access, security, creating
master pages, and data manipulation.
• ASP.NET server controls are the primary controls used in ASP.NET. These controls can be grouped
into the following categories:
1. Validation controls - These are used to validate user input and they work by running client-side
script.
2. Data source controls - These controls provides data binding to different data sources.
3. Data view controls - These are various lists and tables, which can bind to data from data
sources for displaying.
4. Personalization controls - These are used for personalization of a page according to the user
preferences, based on user information.
5. Login and security controls - These controls provide user authentication.
6. Master pages - These controls provide consistent layout and interface throughout the
application.
7. Navigation controls - These controls help in navigation. For example, menus, tree view etc.
8. Rich controls - These controls implement special features. For example, AdRotator, FileUpload,
and Calendar control.
• In addition, visual studio has the following features, to help produce in error-free coding:
a. Dragging and dropping of controls in design view
b. IntelliSense feature that displays and auto-completes the properties
c. The properties window to set the property values directly
List Controls
• ASP.NET provides the following list controls.
1. Drop-down list
2. List box
3. Radio button list
4. Check box list
5. Bulleted list
• These controls display list of options to select. You can select one or
more options, the choice depends upon control.
• They all derive from the System.Web.UI.WebControls.ListControl class
• Some of the important common properties of list controls are as follows:
1. SelectedValue: Get the value of the selected item from the dropdown list.
2. SelectedIndex: Gets the index of the selected item from the dropdown box.
3. SelectedItem: Gets the text of selected item from the list.
4. Items: Gets the collection of items from the dropdown list.
5. DataTextField: Name of the data source field to supply the text of the items. Generally this field came from the
datasource.
6. DataValueField: Name of the data source field to supply the value of the items. This is not visible field to list
controls, but you can use it in the code.
7. DataSourceID: ID of the datasource control to provide data.
• There are several ways through which you can populate these controls such as:
a. By using data from database.
b. Directly write code to add items.
c. Add items through the items collection from property window.
d. Write HTML to populate these controls.
e. Use inbuilt datasource controls.
https://www.tutorialride.com/asp-net/list-controls-in-asp-net.htm
Table Controls
• In the .NET Framework the Table class enables you to build an HTML
table.
• The System.Web.UI.Controls namespace defines the Table class, along
with the other Web controls.
• You can create tables in .NET using a Table control and its helper
controls TableRow and TableCell.
• As with all Web controls, you can create a Table control at run-time as
well as at design-time using the VS .NET IDE
• Table: ASP.NET table and its Helper Control Classes
Manages a collection of table cells such as adding a cell to a row or
removing a cell from it.
Web Control Events and AutoPostBack
• Web controls are basically HTML elements wrapped under easy to use scripting tags of
ASP+ and provide rich functionality in your FORMs or pages. Web controls range from
simple text box to advance girds and lists. Some of the controls like data grid can be
bound to data sources much like Visual Basic data bound controls.
• What are advantages of web controls ?
1. They are highly customizable and provide common properties and methods
throughout.
2. Even though web controls provide rich functionality finally they are rendered as plain
HTML in the client browser thus avoiding browser compatibility problems.
3. They can be used in object oriented manner much like Visual Basic controls.
4. They are processed at server side. This makes ASP+ page much readable and cleaner
as compared to traditional ASP page.
5. They can be data bound
6. State maintenance is automatically taken care by ASP+
• What are common web controls available?
• Following is a list of common web controls :
Label, Panel, Button, TextBox, CheckBox, RadioButton, RadioButtonList,
ListBox, DropDownList, Table/TableRow/TableCell, DataGrid, DataList,
Repeater, Calender, Validation controls
• How do I handle Web control events?
Web control are processed at server side. This means that all the events
generated by a control will be handled at server end. The event handling has
changed with ASP+. Each event handler now has following syntax :
public sub myeventhandler(source as Object, evt as EventArgs)
'access your web controls here and
'manipulate their properties
end sub
Here, source is the object which caused the event to be raised and evt is an
object providing more information about the event.
• Autopostback is the mechanism, by which the page will be posted
back to the server automatically based on some events in the web
controls. In some of the web controls, the property called auto post
back, which if set to true, will send the request to the server when an
event happens in the control
• This is the event which is default associate with any webcontrol. For
example, in case of Button click event, in case of Check box
CheckChangedEvent is there. So in case of AutoPostBack true these
events are called by default and event handle at server side.
ASP .NET-Life Cycle
• ASP.NET life cycle specifies, how:
• ASP.NET processes pages to produce dynamic output
• The application and its pages are instantiated and processed
• ASP.NET compiles the pages dynamically
• The ASP.NET life cycle could be divided into two groups:
1. Application Life Cycle
2. Page Life Cycle
ASP.NET Application Life Cycle
• The application life cycle has the following stages:
• User makes a request for accessing application resource, a page. Browser
sends this request to the web server.
• A unified pipeline receives the first request and the following events take
place:
• An object of the class ApplicationManager is created.
• An object of the class HostingEnvironment is created to provide information
regarding the resources.
• Top level items in the application are compiled.
• Response objects are created. The application objects such as HttpContext,
HttpRequest and HttpResponse are created and initialized.
• An instance of the HttpApplication object is created and assigned to the
request.
• The request is processed by the HttpApplication class. Different events are
raised by this class for processing the request.
ASP.NET Page Life Cycle
• 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 other words, you can write your own code to override
the default code.
• 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. You
can see the control tree by adding trace= "true" to the page directive. We will
cover page directives and tracing under 'directives' and 'event handling'.
• 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
• Following are the different stages of an ASP.NET page:
Page request - When ASP.NET gets a page request, it decides whether to parse and compile the
page, or there would be a cached version of the page; accordingly the response is sent.
Starting of page life cycle - 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.
Page initialization - At this stage, the controls on the page are assigned unique ID by setting the
UniqueID property and the themes are applied. For a new request, postback data is loaded and the
control properties are restored to the view-state values.
Page load - At this stage, control properties are set using the view state and control state values.
Validation - Validate method of the validation control is called and on its successful execution, the
IsValid property of the page is set to true.
Postback event handling - If the request is a postback (old request), the related event handler is
invoked.
Page rendering - At this stage, view state for the page and all controls are saved. The page calls the
Render method for each control and the output of rendering is written to the OutputStream class of
the Response property of page.
Unload - The rendered page is sent to the client and page properties, such as Response and
Request, are unloaded and all cleanup done.
• Following are the page life cycle events:
PreInit - PreInit 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.
Rich Controls:
Rich Controls - Calendar Control
• The calendar control is a functionally rich web control, which provides
the following capabilities:
1. Displaying one month at a time
2. Selecting a day, a week or a month
3. Selecting a range of days
4. Moving from month to month
5. Controlling the display of the days programmatically
• The basic syntax of a calendar control is:
<asp:Calendar ID="Calendar1" runat="server">
• The Calendar control has the following three most important events
and properites that allow the developers to program the calendar
control. They are:
AdRotator Control
• The AdRotator control randomly selects banner graphics from a list, which is specified in
an external XML schedule file. This external XML schedule file is called the advertisement
file.
• The AdRotator control allows you to specify the advertisement file and the type of
window that the link should follow in the AdvertisementFile and the Target property
respectively.
<asp:AdRotator ID="AdRotator1" runat="server" AdvertisementFile =“xmlfilename"
Target=“_blank" />
• The advertisement file is an XML file, which contains the information about the
advertisements to be displayed.
• Extensible Markup Language (XML) is a W3C standard for text document markup. It is a
text-based markup language that enables you to store data in a structured format by
using meaningful tags.
• The term 'extensible' implies that you can extend your ability to describe a document by
defining meaningful tags for the application.
• Like all XML files, the advertisement file needs to be a structured text
file with well-defined tags delineating the data. There are the
following standard XML elements that are commonly used in the
advertisement file:
• Properties and Event of AdRotator are:
MultiView Control
• MultiView and View controls allow you to divide the content of a
page into different groups, displaying only one group at a time. Each
View control manages one group of content and all the View controls
are held together in a MultiView control.
• The MultiView control is responsible for displaying one View control
at a time. The View displayed is called the active view.
<asp:MultView ID= "MultiView1" runat= "server">
<asp:View ID= "View1" runat= "server"> </asp:View>
</asp:MultiView>
• Properties of View and MultiView Controls
• Both View and MultiView controls are derived from Control class and
inherit all its properties, methods, and events. The most important
property of the View control is Visible property of type Boolean,
which sets the visibility of a view.
• The MultiView control has the following important properties:
Properties Description
<asp:RequiredFieldValidator ID="rfvcandidate"
runat="server" ControlToValidate ="ddlcandidate"
ErrorMessage="Please choose a candidate"
InitialValue="Please choose a candidate">
</asp:RequiredFieldValidator>
RangeValidator Control
• The RangeValidator control verifies that the input value falls within a predetermined
range.
• It has three specific properties:
• 2. Setting the theme at the site level: to set the theme for the entire website you can set the theme in the web.config of the
website. Open the web.config file and locate the <pages> element and add the theme attribute to it:
<pages theme="Theme1">
....
….
</pages>
• Setting the theme programmatically at runtime: here the theme is set at runtime through coding. It should be applied earlier in the
page's life cycle ie. Page_PreInit event should be handled for setting the theme. The better option is to apply this to the Base page
class of the site as every page in the site inherits from this class.
Page.Theme = Theme1;
Applying a Simple Theme
• Example
Create 2 themes for the page – one with red background (Theme1) and
another with an image as a background (Theme2). When the user
selects a particular theme from the ListBox then that theme should be
applied dynamically for the page.
• You can have as many themes as you want and you can switch between them by
setting a single attribute in the web.config file or an individual aspx page. Also
you can switch between themes programmatically.
• Setting the themes programmatically, you are offering your users a quick and easy
way to change the page to their likings.
• Themes allow you to improve the usability of your site by giving users with vision
problems the option to select a high contrast theme with a large font size.
Simple Master Page and Content Page,
Connecting Master pages and Content Pages
• Master Pages are used when user needs a consistent look and behavior over all web
pages in an application. When a user needs to attach header and footer for all the web
pages in an application, the master pages are used. Master pages provide a template for
all other pages in an application.
• The master pages define placeholders for the content, which are overridden for the
content. The result is combination of master and content page. Every master page has
one or more content pages in an application.
• The advantages of the master page are as mentioned below:
1. They provide an object model allowing users to customize the master page from the
individual content pages.
2. They allows user design the rendering of the controls in the placeholder
3. It is centralized with common functionality of all pages to makes updates in one place
4. Code can be applied on one set of controls and the results to the set of pages in the
application
• The @Master directive is defines in the master page. The master page contains one or
more <asp:ContentPlaceHolder> for an individual content. The id attribute identifies the placeholder from all
present in a web page. The master page has .master extension. The syntax of the master directive is as
shown below:
• <%@ Master Language=”C#” CodeFile=”MasterPage.master.cs” Inherits=”MasterPage” %
• To create a master page, create an ASP.NET website by clicking ‘File’ > ‘New’ > ‘Website’. Right click on the
Project in the solution explorer and click ‘Add New Item’. In the dialog box, choose the ‘Master Page’ and
click ‘Add’. The ‘MasterPage.master’ appears in the solution explorer.
• The content are used for holding values of the master page placeholder control. The syntax for the content
page is as shown below:
• <%Page Language=”C#” MasterPageFile=”~/MasterPages/Master1.master” Title=”Content Page %>
• The @Page directive defines as a standard page. The content pages are saved with page1.aspx extension.
The MasterPageFile is the master file which is applied to the content page. The content page binds with the
respective master page. The content page looks as shown below:
• <%Page Language=”C#” MasterPageFile=”~/MasterPages/Master1.master” Title=”Content Page1 %>
<asp:Content ID=”Content1” ContentPlaceHolderID=”Main” runat=”server”>
Main Content
</asp:Content>
• The @Page directive page binds the content page to a specific master page. It defines a title for the page to
be merged with the master page. User can create content by adding content controls and mapping them to
the contentplaceholder controls on the master page.
.NET Technologies
SIUSCS46
UNIT 3
By Shivani Deopa
ADO.NET:
Introduction
• It is a module of .Net Framework which is used to establish connection
between application and data sources. Data sources can be such as SQL
Server and XML.
• ADO.NET consists of classes that can be used to connect, retrieve, insert
and delete data.
• All the ADO.NET classes are located into System.Data.dll and integrated
with XML classes located into System.Xml.dll.
• ADO.NET provides a bridge between the front end controls and the back
end database.
• The ADO.NET objects encapsulate all the data access operations and the
controls interact with these objects to display data, thus hiding the details
of movement of data.
• ADO.NET has two main components that
are used for accessing and manipulating
data are the .NET Framework data
provider and the DataSet.
• .NET Framework Data Providers
These are the components that are
designed for data manipulation and fast
access to data. It provides various objects
such as Connection, Command,
DataReader and DataAdapter that are used
to perform database operations.
• The DataSet
It is used to access data independently
from any data resource. DataSet contains a
collection of one or more DataTable
objects of data. The following diagram
shows the relationship between .NET
Framework data provider and DataSet.
The DataSet Class
• The dataset represents a subset of the database. It does not have a
continuous connection to the database.
• To update the database a reconnection is required. The DataSet
contains DataTable objects and DataRelation objects.
• The DataRelation objects represent the relationship between two
tables.
• Following table shows some
important properties of the
DataSet class:
The DataTable Class
• The DataTable class represents the tables in the database. It has the
following important properties; most of these properties are read
only properties except the PrimaryKey property:
• The following table shows some important methods of the DataTable
class:
The DataRow Class
• The DataRow object represents a row in a table. It has the following
important properties and method:
• The DataAdapter Object
The DataAdapter object acts as a mediator between the DataSet object and
the database. This helps the Dataset to contain data from multiple databases
or other data source.
• The DataReader Object
The DataReader object is an alternative to the DataSet and DataAdapter
combination. This object provides a connection oriented access to the data
records in the database. These objects are suitable for read-only access, such
as populating a list and then breaking the connection.
• DbCommand and DbConnection Objects
The DbConnection object represents a connection to the data source. The
connection could be shared among different command objects.
The DbCommand object represents the command or a stored procedure sent
to the database from retrieving or manipulating data.
ADO.NET Framework Data Providers
• Data provider is used to
connect to the database,
execute commands and
retrieve the record. It is
lightweight component with
better performance. It also
allows us to place the data
into DataSet to use it further
in our application.
• The .NET Framework provides
the following data providers
that we can use in our
application.
• Following are the core object of Data Providers.
.NET Framework Data Provider for SQL Server
• Data provider for SQL Server is a lightweight component. It provides better performance because
it directly access SQL Server without any middle connectivity layer. In early versions, it interacts
with ODBC layer before connecting to the SQL Server that created performance issues.
• The .NET Framework Data Provider for SQL Server classes is located in
the System.Data.SqlClient namespace. We can include this namespace in our C# application by
using the following syntax- using System.Data.SqlClient
Data Access - Creating a Connection
• ADO.NET SqlConnection Class- It is used to establish an open connection to
the SQL Server database. It is a sealed class so that cannot be inherited.
• SqlConnection class uses SqlDataAdapter and SqlCommand classes
together to increase performance when connecting to a Microsoft SQL
Server database.
• Connection does not close explicitly even it goes out of scope. Therefore,
you must explicitly close the connection by calling Close() method.
• Syntax
using (SqlConnection con = new SqlConnection("data source=.;
database=Student; integrated security=SSPI"))
• SqlConnection Constructors and Methods
Select Command
• SqlCommand Class- This class is used to store and execute SQL statement for SQL Server
database. It is a sealed class so that cannot be inherited.
• This class provides the following constructors.
• This class provides the following Methods.
DataReader
• ADO.NET SqlDataReader Class- This class is used to read data from SQL Server database. It reads data in
forward-only stream of rows from a SQL Server database.
• It is sealed class so that cannot be inherited. It inherits DbDataReader class and implements IDisposable
interface.
• SqlDataReader Properties
• SqlDataReader Methods
DataAdapter
• ADO.NET DataAdapter- The DataAdapter works as a bridge between a DataSet
and a data source to retrieve data.
• DataAdapter is a class that represents a set of SQL commands and a database
connection. It can be used to fill the DataSet and update the data source.
• DataAdapter Constructors
• DataAdapter Methods
• Example:
• Configuring various data operations on the underlying data depends upon the various properties
(property groups) of the data source control.
• The following table provides the related sets of properties of the
SqlDataSource control, which provides the programming interface of
the control:
Working with XML:
XML Introduction
• XML is short for eXtensible Markup Language. It is a very widely used format for
exchanging data, mainly because it's easy readable for both humans and
machines.
• If you have ever written a website in HTML, XML will look very familiar to you, as
it's basically a stricter version of HTML. XML is made up of tags, attributes and
values and looks something like this:
<users>
<user name="John Doe" age="42" />
<user name="Jane Doe" age="39" />
</users>
• We use System.Xml namespace, to deal with pretty much any aspect of XML in
C#/ASP .Net.
Reading XML with the XmlReader class
• There are mainly two methods for reading XML with C#: The XmlDocument
class and the XmlReader class.
• XmlDocument reads the entire XML content into memory and then lets you
navigate back and forward in it as you please, or even query the document
using the XPath technology.
• The XmlReader is a faster and less memory-consuming alternative. It lets
you run through the XML content one element at a time, while allowing
you to look at the value, and then moves on to the next element.
• By doing so, it obviously consumes very little memory because it only holds
the current element, and because you have to manually check the values,
you will only get the relevant elements, making it very fast.
XmlReader xmlReader = XmlReader.Create(“EuropeanCentralBank.xml");
while(xmlReader.Read())
{
if((xmlReader.NodeType == XmlNodeType.Element) && (xmlReader.Name == "Cube"))
{
if(xmlReader.HasAttributes)
Console.WriteLine(xmlReader.GetAttribute("currency") + ": " + xmlReader.GetAttribute("rate"));
}
}
Console.ReadKey();
• We start off by creating the XmlReader instance, using the static Create() method. It has several overloads, but the
simplest of them just takes a URL pointing to the file.
• In a while loop, we call the Read() method on the XmlReader instance. It advances the reader to the next element and
then returns true as long as there is more to read.
• Inside the loop, we can now use one of the many properties and methods on the XmlReader to access data from the
current element.
• In our case, we check the NodeType to see if we have an Element (the tag part), and if the name is "Cube". As you can
see in the XML document we used, each currency rate is within an element called Cube, so this is of course what we're
looking for - the rest is ignored.
• Once we have a Cube element, we do a formal check to see if it has attributes (which it should) and then we use the
GetAttribute() method to read the two attribute values "currency" and "rate".
• We print them out to the Console and then we move on to the next element. The result should be a complete list of
currencies and their current exchange rate.
Reading XML with the XmlDocument class
• The XmlDocument is more memory consuming and possibly a bit slower than the XmlReader
approach. However, for many purposes, the XmlDocument can be easier to work with and often
require less code.
• Once the XML content has been read, you can read the data in a hierarchical way, just like the XML
structure, with a root element which can have child elements, which can have child elements, and so
on.
• Previously we parsed XML data from the European Central Bank which could tell us about the current
currency exchange rates, and we will do the same now, but using the XmlDocument class instead.
<gesmes:Envelope>
[other child nodes]
<Cube>
<Cube time="2011-04-12">
<Cube currency="USD" rate="1.4470"/>
<Cube currency="JPY" rate="121.87"/>
…
• The gesmes:Envelope is our root element, which we can access using the DocumentElement property.
• We will then be able to access children of this node by using the ChildNodes collection property. In our
example, we want the child nodes three levels below the root/document element.
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(" EuropeanCentralBank.xml ");
foreach(XmlNode xmlNode in
xmlDoc.DocumentElement.ChildNodes[2].ChildNodes[0].ChildNodes)
Console.WriteLine(xmlNode.Attributes["currency"].Value + ": " +
xmlNode.Attributes["rate"].Value);
Console.ReadKey();
• As you can see, we access the Cube nodes by going down the ChildNodes hierarchy.
• From the DocumentElement (the root element), we ask for the third child node (zero-
index based), then we ask for the first child node of that, and then we ask for the entire
collection of child nodes.
• Obviously this is only possible because we know the structure of the XML document, and
it's definitely not very flexible, pretty or easy to change later on.
• However, the way you navigate an XML document very much depends on the XML source
and the data you need.
• For this example, the above will work just fine and even with a very limited amount of
code, but for other purposes, you may want to use a bit more code to increase the
readability.
Working with the XmlNode class
• The XML is basically parsed into an XmlNode which is the root element and then you can
access the child elements using the ChildNodes property.
• However, the XmlNode class gives you access to a lot of other information as well, for
instance the name of the tag, the attributes, the inner text and the XML itself.
• This chapter is a brief description of some of the more interesting aspects of the XmlNode
class, which is important to know about because the XmlNode class is such a key concept
when parsing XML with the XmlDocument class.
• In the following examples we will use the DocumentElement a lot, and while it is in fact of
the type XmlElement, XmlElement does inherit from XmlNode, so it's essentially the same.
• The Name property will simply give you the name of the node. For instance, the following
example will output the text "user":
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml("<user name=\"John Doe\">A user node</user>");
Console.WriteLine(xmlDoc.DocumentElement.Name);
Console.ReadKey();
Writing XML with the XmlWriter class
• Since XML is simply text, you could just start writing out XML tags to a file and
give it an xml extension, but it's more easy and safer to let the .NET framework
handle it, and just like with reading XML, there are at least two different options:
The XmlWriter approach and the XmlDocument approach.
• The difference between the two is once again mostly related to memory
consumption - XmlWriter uses less memory than XmlDocument, which is only an
issue if you write very big files though.
• Another important difference is that when using XmlDocument, you can read an
existing file, manipulate it and then write back the changes.
• With XmlWriter, you will have to write the entire document from scratch each
time.
• This is not necessarily a problem though, so as always, it really comes down to
your situation as well as your personal preferences
• Here's an example of writing XML using the XmlWriter class:
XmlWriter xmlWriter = XmlWriter.Create("test.xml");
xmlWriter.WriteStartDocument();
xmlWriter.WriteStartElement("users");
xmlWriter.WriteStartElement("user");
xmlWriter.WriteAttributeString("age", "42");
xmlWriter.WriteString("John Doe");
xmlWriter.WriteEndElement();
xmlWriter.WriteStartElement("user");
xmlWriter.WriteAttributeString("age", "39");
xmlWriter.WriteString("Jane Doe");
xmlWriter.WriteEndDocument();
xmlWriter.Close();
• The Join clause- The 'join clause' in SQL is used for joining two data tables and displays a
data set containing columns from both the tables. LINQ is also capable of that.
var booktitles = from b in books join s in sales on b.ID equals s.ID
select new { Name = b.Title, Pages = s.pages };
• The Where clause- The 'where clause' allows adding some conditional filters to the query. For example, if
you want to see the books, where the number of pages are more than 500, write the following code :
var booktitles = from b in books join s in sales on b.ID equals s.ID
where s.pages > 500 select new { Name = b.Title, Pages = s.pages };
• Orderby and Orderbydescending Clauses- These clauses allow sorting the query results. To query the
titles, number of pages and price of the book, sorted by the price, write the following code:
var booktitles = from b in books join s in sales on b.ID equals s.ID
orderby b.Price select new { Name = b.Title, Pages = s.pages, Price = b.Price};
• The Let clause- The let clause allows defining a variable and assigning it a value calculated from the data
values. For example, to calculate the total sale from the above two sales, you need to calculate:
TotalSale = Price of the Book * Sales
• To achieve this, use the following code:
• The let clause allows defining a variable and assigning it a value calculated from the data values. For
example, to calculate the total sale from the above two sales, you need to calculate:
var booktitles = from b in book join s in sales on b.ID equals s.ID
let totalprofit = (b.Price * s.sales)
select new { Name = b.Title, TotalSale = totalprofit};
ASP.NET AJAX:
ScriptManager
• AJAX stands for Asynchronous JavaScript and XML. This is a cross platform technology which speeds up
response time. The AJAX server controls add script to the page which is executed and processed by the
browser.
• However like other ASP.NET server controls, these AJAX server controls also can have methods and event
handlers associated with them, which are processed on the server side.
• The control toolbox in the Visual Studio IDE contains a group of controls called the 'AJAX Extensions’
• If you create an 'Ajax Enabled site' or add an 'AJAX Web Form' from the 'Add Item' dialog box, the web form
automatically contains the script manager control. The ScriptManager control takes care of the client-side
script for all the server side controls.
Partial Refreshes
• The UpdatePanel control is a container control and derives from the Control class. It acts
as a container for the child controls within it and does not have its own interface.
• When a control inside it triggers a post back, the UpdatePanel intervenes to initiate the
post asynchronously and update just that portion of the page.
• For example, if a button control is inside the update panel and it is clicked, only the
controls within the update panel will be affected, the controls on the other parts of the
page will not be affected.
• This is called the partial post back or the asynchronous post back.
• The <asp:UpdatePanel> tag has two childtags - the ContentTemplate and
the Triggers tags.
• The ContentTemplate tag is required, since it holds the content of the panel. The content
can be anything that you would normally put on your page, from literal text to web
controls.
• The Triggers tag allows you to define certain triggers which will make the panel update
it's content.
• Properties of the UpdatePanel Control
• Methods of the UpdatePanel Control
Progress Notification
• One of the problems with Ajax, is the fact that since it's asynchronus and in the background, the browser
will not show you any status.
• With fast servers and fast methods, this is not a big problem, but whenever you have a method which
takes up a bit of time, the user is very likely to get impatient.
• The UpdateProgress control provides a sort of feedback on the browser while one or more update panel
controls are being updated.
• For example, while a user logs in or waits for server response while performing some database oriented
job.
• It provides a visual acknowledgement like "Loading page...", indicating the work is in progress.
• You can even have multiple UpdateProgress controls on the page, and by using
the AssociatedUpdatePanelID property, you can make sure that the UpdateProgress is only shown when a
certain UpdatePanel is updated.
• The DynamicLayout property is nice to know as well. It tells whether or not the page should reserve space
for your progress control.
• If it's set to true, which is the default, the space is dynamic, hence it's not reserved, but taken when the
control is shown. If you wish to reserve the space, set this property to false.
• Properties and Methods of the UpdateProgress Control
Timed Refreshes
• Timer controls allow you to do postbacks at certain intervals. If used together with UpdatePanels, which is the most
common approach, it allows for timed partial updates of your page, but it can be used for posting back the entire page as
well.
(2) Placing a timer control directly inside the UpdatePanel to act as a child control trigger. A single timer can be the trigger
for multiple UpdatePanels.
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Always">
<ContentTemplate>
<asp:Timer ID="Timer1" runat="server" Interval="1000"></asp:Timer>
<asp:Label ID="Label1" runat="server" Height="101px" style="width:304px" ></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>