Download as pdf or txt
Download as pdf or txt
You are on page 1of 32

B.C.A.

Semester – V
US05CBCA21: Advanced Web Development Technology
(Syllabus Effective from June 2020)
Unit – 1
 Introduction To ASP.NET
 Introduction to .NET Platform and Web :
Introduction to ASP (Server-side Technology),.NET Framework (FCL
and CLR),Overview of IIS, Processing of ASP.NET page (Execution
model), Features of .NET IDE, Features of ASP.NET, Working with
ASP.NET, Coding Model (Inline and Code-behind), Introduction to Web-
Forms and its Events
 ASP.NET Built-in directory structure
App_data,App_code,Bin
 Application Configuration :
Global.asax file, Web.config
 Common properties :
AccessKey, BackColor, BorderWidth, BorderStyle, CSSClass, Enabled,
Font, ForeColor, Height, TabIndex, Tooltip, Width, ID, Runat, Text.
 Using Visual C# in ASP. NET:
Introduction, Variables, Data Types, Value Types, Scope of Variables,
Operators, OOPs Concepts (Encapsulations, Inheritance, Polymorphism
and Abstraction)
 Introduction To .NET Platform and Web
What is ASP?
ASP stands for Active Server Pages. Microsoft introduced Active Server Pages in December 1996,
beginning with Version 3.0. Microsoft officially defines ASP as: “Active Server Pages is an open,
compile-free application environment in which you can combine HTML, scripts, and reusable
ActiveX server components to create dynamic and powerful Web-based business solutions. Active
Server pages enable server side scripting for IIS with native support for both VBScript and
Jscript.” (2). In other words, ASP is a Microsoft technology that enables you to create dynamic
web sites with the help of server side script, such as VBScript and Jscript. ASP technology is
supported on all Microsoft Web servers that are freely available.
What is 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.
.Net Framework

 NET is tiered, modular, and hierarchal. Each tier of the .NET Framework is a layer of abstraction.
.NET languages are the top tier and the most abstracted level. The common language runtime is the
bottom tier, the least abstracted, and closest to the native environment. This is important since the
common language runtime works closely with the operating environment to manage .NET
applications. The .NET Framework is partitioned into modules, each with its own distinct
responsibility. Finally, since higher tiers request services only from the lower tiers, .NET is
hierarchal. The architectural layout of the .NET Framework is illustrated in Figure 1.1.
Figure 1.1 An overview of the .NET architecture.

 .NET Framework is a managed environment. The common language runtime monitors the
execution of .NET applications and provides essential services. It manages memory, handles
exceptions, ensures that applications are well-behaved, and much more.
 Language interoperability is one goal of .NET. .NET languages share a common runtime (the
common language runtime, a common class library), the Framework Class Library (FCL), a
common component model, and common types. In .NET, the programming language is a lifestyle
choice. Except for subtle differences, C#, VB.NET, or JScript.NET offer a similar experience.
 .NET abstracts lower-level services, while retaining most of their flexibility. This is important to C-
based programmers, who shudder at the limitations presented in Visual Basic 6 and earlier.
 Let us examine each tier of the .NET Framework as it relates to a managed environment, language
interoperability, and abstraction of lower-level services.

Common Language Specification (CLS)


 The CLS is a common platform that integrates code and components from multiple .NET
programming languages. In other words, a .NET application can be written in multiple
programming languages with no extra work by the developer (though converting code between
languages can be tricky).
 .NET includes new object-oriented programming languages such as C#, Visual Basic .NET, J# (a
Java clone) and Managed C++. These languages, plus other experimental languages like F#, all
compile to the Common Language Specification and can work together in the same application.

Framework Class Library (FCL)


 The FCL is a collection of over 7000 classes and data types that enable .NET applications to read
and write files, access databases, process XML, display a graphical user interface, draw graphics,
use Web services, etc. The FCL wraps much of the massive, complex Win32 API into more simple
.NET objects that can be used by C# and other .NET programming languages.

Common Language Runtime (CLR)


 The CLR is the execution engine for .NET applications and serves as the interface between .NET
applications and the operating system. The CLR provides many services such as:
 Loads and executes code
 Converts intermediate language to native machine code
 Separates processes and memory
 Manages memory and objects
 Enforces code and access security
 Handles exceptions
 Interfaces between managed code, COM objects, and DLLs
 Provides type-checking
 Provides code meta data (Reflection)
 Provides profiling, debugging, etc.

 .NET Languages :--


are CLI computer programming languages that may also optionally use the .NET Framework Base
Class Library and which produce programs that execute within the Microsoft .NET Framework.
Microsoft provides several such languages, including C#, F#, Visual Basic .NET, and Managed C++.
Generally .NET languages call into two main categories, TypeSafe Languages (such as C#) and
Dynamic Languages (Such as Python). Type Safe Languages are built on the .NET Common Language
Runtime and Dynamic Languages are built on top of the .NET Dynamic Language Runtime. The .NET
Framework is unique in its ability to provide this flexibility.
Regardless of which .NET language is used, the output of the language compiler is a representation of
the same logic in an intermediate language named Common Intermediate Language (CIL).
As the program is being executed by the CLR, the CLI code is compiled and cached, just in time, to the
machine code appropriate for the architecture on which the program is running. This last compilation
step is usually performed by the Common Language Runtime component of the framework “just in
time” (JIT) at the moment the program is first invoked, though it can be manually performed at an
earlier stage.

 Microsoft Intermediate Language (MSIL) :--


MSIL: (Microsoft Intermediate language) or IL(Intermediate Language) is machine independent code
generated by .NET framework after the compilation of program written in any language by you.
MSIL or IL is now known as CIL(Common Intermediate Language).

One of the more interesting aspects of .NET is that when you compile your code, you do not compile
to native code. Before you VB developers panic and fear that you are returning to the days of
interpreted code, realize that the compilation process translates your code into something called
Microsoft intermediate language, which is also called MSIL or just IL. The compiler also creates the
necessary metadata and compiles it into the component. This IL is CPU independent. After the IL and
metadata are in a file, this compiled file is called the PE, which stands for either portable executable or
physical executable, depending on whom you ask. Because the PE contains your IL and metadata, it is
therefore self-describing, eliminating the need for a type library or interfaces specified with the
Interface.

 The Just-In-Time Compiler


 Your code does not stay IL for long, however. It is the PE file, containing the IL, that can be
distributed and placed with the CLR running on the .NET Framework on any operating system for
which the .NET Framework exists, because the IL is platform independent. When you run the IL,
however, it is compiled to native code for that platform. Therefore, you are still running native
code; you are not going back to the days of interpreted code at all. The compilation to native code
occurs via another tool of the .NET Framework: the Just-In-Time (JIT) compiler.
 With the code compiled, it can run within the Framework and take advantage of low-level features
such as memory management and security. The compiled code is native code for the CPU on which
the .NET Framework is running, meaning that you are indeed running native code instead of
interpreted code. A JIT compiler will be available for each platform on which the .NET Framework
runs, so you should always be getting native code on any platform running the .NET Framework.
Remember, today this is just Windows, but this could change in the future.

 Just-in-time compilation (JIT), also known as dynamic translation, is a method to improve the
runtime performance of computer programs. Historically, computer programs had two modes of
runtime operation, either interpreted or static (ahead-of-time) compilation. Interpreted code is
translated from a high-level language to a machine code continuously during every execution,
whereas statically compiled code is translated into machine code before execution, and only
requires this translation once.
Overview of IIS
 IIS (Internet Information Server) is a group of Internet servers (including a Web or Hypertext
Transfer Protocol server and a File Transfer Protocol server) with additional capabilities for
Microsoft's Windows NT and Windows 2000 Server operating systems. IIS is Microsoft's entry to
compete in the Internet server market that is also addressed by Apache, Sun Microsystems,
O'Reilly, and others. With IIS, Microsoft includes a set of programs for building and administering
Web sites, a search engine, and support for writing Web-based applications that access databases.
Microsoft points out that IIS is tightly integrated with the Windows NT and 2000 Servers in a
number of ways, resulting in faster Web page serving.
 A typical company that buys IIS can create pages for Web sites using Microsoft's Front Page
product (with its WYSIWYG user interface). Web developers can use Microsoft's Active Server
Page (ASP)technology, which means that applications - including ActiveX controls - can be
imbedded in Web pages that modify the content sent back to users. Developers can also write
programs that filter requests and get the correct Web pages for different users by using Microsoft's
Internet Server Application Program Interface (ISAPI) interface. ASPs and ISAPI programs run
more efficiently than common gateway interface (CGI) and server-side include (SSI) programs,
two current technologies. (However, there are comparable interfaces on other platforms.)
 Microsoft includes special capabilities for server administrators designed to appeal to Internet
service providers (ISPs). It includes a single window (or "console") from which all services and
users can be administered. It's designed to be easy to add components as snap-ins that you didn't
initially install. The administrative windows can be customized for access by individual customers.
Processing of ASP.NET page (Execution model)
 Each time a request arrives at a Web server for an ASP.NET Web page, the first thing the Web
server does is hand off the request to the ASP.NET engine. The ASP.NET engine then takes the
request through a pipeline composed of numerous stages, which includes verifying file access
rights for the ASP.NET Web page, resurrecting the user's session state, and so on. At the end of the
pipeline, a class corresponding to the requested ASP.NET Web page is instantiated and the
ProcessRequest() method is invoked (see Figure 1).

Figure 1. ASP.NET Page Handling


 This life cycle of the ASP.NET page starts with a call to the ProcessRequest() method. This
method begins by initializing the page's control hierarchy. Next, the page and its server controls
precede lock-step through various phases that are essential to executing an ASP.NET Web page.
These steps include managing view state, handling postback events, and rendering the page's
HTML markup. Figure 2 provides a graphical representation of the ASP.NET page life cycle. The
life cycle ends by handing off the Web page's HTML markup to the Web server, which sends it
back to the client that requested the page.
 Note A detailed discussion of the steps leading up to the ASP.NET page life cycle is beyond the
scope of this article. For more information read Michele Leroux-Bustamante's Inside IIS &
ASP.NET. For a more detailed look at HTTP handlers, which are the endpoints of the ASP.NET
pipeline, check out my previous article on HTTP Handlers.
 What is important to realize is that each and every time an ASP.NET Web page is requested it goes
through these same life cycle stages (shown in Figure 2).
Figure 2. Events in the 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 this 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
'error 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
 Understanding the page cycle helps in writing codes for making some specific thing happen at any
stage of the page life cycle. It also helps in writing custom controls and initializing them at right
time, populate their properties with view-state data and run control behavior code.
 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 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 if it runs successfully, 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
called.
 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 Page's Response property.
 Unload: The rendered page is sent to the client and page properties, such as Response and
Request are unloaded and all cleanup done.

 ASP.NET PAGE LIFE CYCLE EVENTS


 At each stage of the page life cycle, the page raises some events, which could be coded. An event
handler is basically a function or subroutine, bound to the event, using declarative attributes like
Onclick or handle.
 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 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.
Features of .Net IDE
 Visual Studio has a code editor with IntelliSense as well as code refactoring.
 The integrated debugger works not only as a source-level debugger but also as a machine-level
debugger.
 Forms designer provided in visual studio is used for building GUI applications.
 Web designer
 Class designer
 Database schema designer.

Visual Studio also accepts plug-ins to enhance it’s functionality like adding support for source-control
systems (like Subversion and Visual SourceSafe) or adding new toolsets like editors and visual designers
for domain-specific languages or toolsets for other aspects of the software development lifecycle (like the
Team Foundation Server client: Team Explorer).

Visual Studio supports different programming languages by it’s language services, to support different
programming language and enable support in it’s code editor and debugger. The supporting programming
languages includes C/C++ (via Visual C++), VB.NET (via Visual Basic .NET), C# (via Visual C#), and
F# (as of Visual Studio 2010). Support for XML/XSLT, HTML/XHTML, JavaScript and CSS is also
present.

Microsoft provides “Express” editions of its Visual Studio 2010 components Visual Basic, Visual C#,
Visual C++, and Visual Web Developer are made available to the public and developer community at large
for no cost. Visual Studio 2012, 2010, 2008 and 2005 Professional Editions, along with language-specific
versions (Visual Basic, C++, C#, J#) of Visual Studio Express 2010 are also available for free to academic
community and students as downloads under the Microsoft’s DreamSpark program.

Features of ASP.Net
1. Separation of Code from HTML: To make a clean sweep, with ASP.NET you have the ability to
completely separate layout and business logic. This makes it much easier for teams of programmers
and designers to collaborate efficiently. This makes it much easier for teams of programmers and
designers to collaborate efficiently.
2. Support for compiled languages: Developer can use VB.NET and access features such as strong
typing and object-oriented programming. Using compiled languages also means that ASP.NET
pages do not suffer the performance penalties associated with interpreted code. ASP.NET pages are
precompiled to byte-code and Just In Time (JIT) compiled when first requested. Subsequent
requests are directed to the fully compiled code, which is cached until the source changes.
3. Use services provided by the .NET Framework: The .NET Framework provides class libraries
that can be used by your application. Some of the key classes help you with input/output, access to
operating system services, data access, or even debugging. We will go into more detail on some of
them in this module.
4. Graphical Development Environment: Visual Studio .NET provides a very rich development
environment for Web developers. You can drag and drop controls and set properties the way you
do in Visual Basic 6. And you have full IntelliSense support, not only for your code, but also for
HTML and XML.
5. State management: To refer to the problems mentioned before, ASP.NET provides solutions for
session and application state management. State information can, for example, be kept in memory
or stored in a database. It can be shared across Web farms, and state information can be recovered,
even if the server fails or the connection breaks down.
6. Update files while the server is running: Components of your application can be updated while
the server is online and clients are connected. The Framework will use the new files as soon as they
are copied to the application. Removed or old files that are still in use are kept in memory until the
clients have finished.
7. XML – Based Configuration Files: Configuration settings in ASP.NET are stored in XML files
that you can easily read and edit. You can also easily copy these to another server, along with the
other files that comprise your application.
Coding Model

Code Behind

Code Behind refers to the code for an ASP.NET Web page that is written in a separate class file that can
have the extension of .aspx.cs or .aspx.vb depending on the language used. Here the code is compiled into
a separate class from which the .aspx file derives. You can write the code in a separate .cs or .vb code file
for each .aspx page. One major point of Code Behind is that the code for all the Web pages is compiled
into a DLL file that allows the web pages to be hosted free from any Inline Server Code.

Inline Code

Inline Code refers to the code that is written inside an ASP.NET Web Page that has an extension of .aspx.
It allows the code to be written along with the HTML source code using a <Script> tag. It's major point is
that since it's physically in the .aspx file it's deployed with the Web Form page whenever the Web Page is
deployed.

Now I will show you these differences by using an example.

Step 1

First of all create a new Blank Website in the Visual Studio, then add a Web page to it. Here we are first
creating a Web page for the Code Behind so remember one thing "the check box should be checked
while adding this page". In other words check the "Place the code in a separate file" and then click on the
"Add" button.
Now on the .aspx page use a Button, a Link and a Text Box.

Step 2

Now double-click on the Button, this will use the Code window. Now you will see that this coding section
is opened in a separate window whose extension is .aspx.cs. Write the code in this window. I wrote the
code such that whatever I wrote in the TextBox will also appear in the Label.
Now debug this page and verify that your program is running.

Step 3

Until now we were working on the Code Behind but now we will work on the Inline Code, for that add
another web page to your Web Site. But this time things are different, this time don't check the check box
and if it's checked then Uncheck it and then Click on "Add".
Now on this new .aspx page again use a Button, a Link and a Text Box.

Step 4

Now double-click on the Button so that you can write the code on click of this Button. But Now No New
Window will be opened, Now the coding will appear on the same .aspx page. Here no .aspx.cs page is
available.
Write the same code here also and then debug it.

As you can see it's giving the same output as the Code Behind gave but even after that is different from the
Code Behind.
Introduction to Web-Forms and its Events
ASP.Net web forms

Web Forms are web pages built on the ASP.NET Technology. It executes on the server and generates
output to the browser. 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.

We can use Visual Studio to create ASP.NET Web Forms. It is an IDE (Integrated Development
Environment) that allows us to drag and drop server controls to the web forms. It also allows us to set
properties, events and methods for the controls. To write business logic, we can choose any .NET language
like: Visual Basic or Visual C#.

Web Forms are made up of two components: the visual portion (the ASPX file), and the code behind the
form, which resides in a separate class file.

Fig: This diagram shows the components of the ASP.NET

ASP.Net Event

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.
 ASP.NET Built-in directory structure
App_data,App_code,Bin

App_Code Folder

As its name suggests, the App_Code Folder stores classes, typed data sets, etc. All the items that are stored
in App_Code are automatically accessible throughout the application. If we store any class files (like .cs or
.vb) it compiles them automatically. It automatically creates type data sets from .xsd (XML schema) files,
and creates XML web service proxy classes from WSDL(Web Services Description Language ).Let's have
a look at how we can use the App_Code folder.

We can add an App_Code folder, by Solution File → right click → Add ASP.NET Folder → App_Code.
The App_Code folder is now added to your application.

Note: Try to add one more App_Code folder by using the same steps. Oops... the App_Code folder is no
longer available there. So, ASP.NET allows you to add an App_Code folder only once.

Now we can add new items like classes, text and xml files into the App_Code folder and we can also add
existing files there.

Let's have a look at one example that shows how it works. Into the App_Code folder, I have added a class
MyCSharpClass.cs.
In that class I have written a small spice of code for adding two numbers.

Now, Try to access this class, from any where in your application. You will see that MyCSharpClass is
accessiblethroughout the application.

If we want to store different classes like .cs or .vb, then what will happen? If we kept both .cs and .vb
classes in the same folder, it will give following compilation error:
This is because all the classes contained in the App_Code folder are built into a single assembly and it can't
have different languages at root level, or even at child level folders in following manner:

We have a solution to overcome this problem. We have to create separate folders for C# and for VB or
other classes.

Store class files separately in those folders and an configure the folder hierarchy in the web.config file.
Now I will move to our next part -the Bin folder.

Bin Folder

The Bin folder is used for keeping assemblies inside it. We can access those as a reference from anywhere
of our web application. Use of Bin folder comes into the picture if we use any class library within our web
application. Suppose we are creating a class library called TestLib. After building the library, we will get
TestLib.dll. Now, right click on solution file → Add References → Project, select the TestLib Project,
click on OK. Check the Bin folder, it will contain TestLib.dll and TestLib.pdb files.

Assemblies in the Bin folder do not need to registered on the system, ASP.NET recognizes the presence of
DLLs inside the Bin Folder. Keeping .pdb files inside Bin folder helps us in debugging. The main
limitation of storing assemblies in the Bin folder is that their scope is limited to the current application.
Therefore, they cannot access any code outside of current web application. [Source]

Next, let's have a look at App_Data folder

App_Data Folder
The App_Data folder is used as a data storage for the web application. It can store files such as .mdf,
.mdb, and XML. It manages all of your application's data centrally. It is accessible from anywhere in your
web application.The real advantage of the App_Data folder is that, any file you place there won't be
downloadable.

We can add .mdf files to the App_Data folder directly by selecting Add New Item. From there we can a
create table, procedure or function without opening SQL Server.Now if we want to add that data to our
application, we can easily use it.

Now, look at the connection string that we need to write for accessing the App_Data folder's databases.

We can connect with MyDB.mdf database using this connection string. Check the example below, which I
have used to read the table data from the MyDB.Mdf file.
 Application Configuration :
 Global.asax file:
What is Global.asax file: global.asax allows us to write event handlers that react to global events in web applications.

How it gets called: Global.asax files are never called directly by the user, rather they are called automatically in response to
application events.

Point to remember about global.asax:


1. They do not contain any HTML or ASP.NET tags.
2. Contain methods with specific predefined names.
3. They defined methods for a single class, application class.
4. They are optional, but a web application has no more than one global.asax file.

How to add global.asax file:

Select Website >>Add New Item (or Project >> Add New Item if you're using the Visual Studio web project model) and choose
the Global Application Class template.

After you have added the global.asax file, you will find that Visual Studio has added Application Event handlers:
<%@ Application Language="C#" %>
<script runat="server">
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
}
void Application_End(object sender, EventArgs e)
{
// Code that runs on application shutdown
}
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
}
void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started
}
void Session_End(object sender, EventArgs e)
{
// Code that runs when a session ends.
// Note: The Session_End event is raised only when the sessionstate mode
// is set to InProc in the Web.config file. If session mode is set to StateServer
// or SQLServer, the event is not raised.
}
</script>

Order Application Events What they do


This method is invoked when the application first starts up and
the application domain is created. This event handler is a useful
place to provide application-wide initialization code. For
1 Application_Start()
example, at this point you might load and cache data that will
not change throughout the lifetime of an application, such as
navigation trees, static product catalogs, and so on.
This method is invoked each time a new session begins. This is
2 Session_Start()
often used to initialize user-specific information.
This method is invoked whenever an unhandled exception
3 Application_Error()
occurs in the application.
This method is invoked whenever the user's session ends. A
session ends when your code explicitly releases it or when it
4 Session_End()
times out after there have been no more requests received
within a given timeout period (typically 20 minutes).
This method is invoked just before an application ends. The end
of an application can occur because IIS is being restarted or
5 Application_End() because the application is transitioning to a new application
domain in response to updated files or the process recycling
settings.
This method is invoked some time after the application has
6 Application_Disposed() been shut down and the .NET garbage collector is about to
reclaim the memory it occupies. This point is too late to
perform critical cleanup, but you can use it as a last-ditch
failsafe to verify that critical resources are released.
 Web.Config file :
What is Web.Config File?
A configuration file (web.config) is used to manage various settings that define a website. The settings are
stored in XML files that are separate from your application code. In this way you can configure settings
independently from your code. Generally a website contains a single Web.config file stored inside the
application root directory. However there can be many configuration files that manage settings at various
levels within an application.
Usage of configuration file
ASP.NET Configuration system is used to describe the properties and behaviors of various aspects of
ASP.NET applications. Configuration files help you to manage the many settings related to your website.
Each file is an XML file (with the extension .config) that contains a set of configuration elements.
Configuration information is stored in XML-based text files.
Benefits of XML-based Configuration files
 ASP.NET Configuration system is extensible and application specific information can be stored
and retrieved easily. It is human readable.
 You need not restart the web server when the settings are changed in configuration file. ASP.NET
automatically detects the changes and applies them to the running ASP.NET application.
 You can use any standard text editor or XML parser to create and edit ASP.NET configuration
files.

What Web.config file contains?


There are number of important settings that can be stored in the configuration file. Some of the most
frequently used configurations, stored conveniently inside Web.config file are:

 Database connections
 Caching settings
 Session States
 Error Handling
 Security

Configuration file looks like this

1. <configuration>
2. <connectionStrings>
3. <add name="myCon" connectionString="server=MyServer;
4. database=puran;uid=puranmehra;pwd=mydata1223" />
5. </connectionStrings>
6. </configuration/>
 Common Properties :

Properties of the Server Controls

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.

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.
BackColor Background color.
BorderStyle Border style.
BorderWidth Border width.
CssClass CSS class
Enabled Indicates whether the control is grayed out.
Font Font.
Forecolor Foreground color.
Height Height in pixels or %.
TabIndex Gets or sets the tab index of the Web server control.
Gets or sets the text displayed when the mouse pointer hovers over the web
ToolTip
server control.
UniqueID Unique identifier.
Visible It indicates whether a server control is visible.
Width Gets or sets the width of the Web server control.

Introduction to C#
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:
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.
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.
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.
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#.Net Data Types

Data Type Size Description


Stores whole numbers from -2,147,483,648 to
int 4 bytes
2,147,483,647
Stores whole numbers from -
long 8 bytes 9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
Stores fractional numbers. Sufficient for storing 6 to
float 4 bytes
7 decimal digits
Stores fractional numbers. Sufficient for storing 15
double 8 bytes
decimal digits
bool 1 bit Stores true or false values
Stores a single character/letter, surrounded by single
char 2 bytes
quotes
2 bytes per Stores a sequence of characters, surrounded by
string
character double quotes

Scope of Variables in C#
The part of the program where a particular variable is accessible is termed as the Scope of that variable. A
variable can be defined in a class, method, loop etc. In C/C++, all identifiers are lexically (or statically)
scoped, i.e.scope of a variable can be determined at compile time and independent of the function call
stack. But the C# programs are organized in the form of classes.

So C# scope rules of variables can be divided into three categories as follows:

 Class Level Scope


 Method Level Scope
 Block Level Scope

Class Level Scope

 Declaring the variables in a class but outside any method can be directly accessed anywhere in the
class.
 These variables are also termed as the fields or class members.
 Class level scoped variable can be accessed by the non-static methods of the class in which it is
declared.
 Access modifier of class level variables doesn’t affect their scope within a class.
 Member variables can also be accessed outside the class by using the access modifiers.

Example:

// C# program to illustrate the


// Class Level Scope of variables
using System;

// declaring a Class
class GFG { // from here class level scope starts

// this is a class level variable


// having class level scope
int a = 10;

// declaring a method
public void display()
{
// accessing class level variable
Console.WriteLine(a);

} // here method ends

} // here class level scope ends

Method Level Scope

 Variables that are declared inside a method have method level scope. These are not accessible
outside the method.
 However, these variables can be accessed by the nested code blocks inside a method.
 These variables are termed as the local variables.
 There will be a compile-time error if these variables are declared twice with the same name in the
same scope.
 These variables don’t exist after method’s execution is over.

Example:

// C# program to illustrate the


// Method Level Scope of variables
using System;

// declaring a Class
class GFG { // from here class level scope starts

// declaring a method
public void display()

{ // from here method level scope starts

// this variable has


// method level scope
int m = 47;
// accessing method level variable
Console.WriteLine(m);

} // here method level scope ends

// declaring a method
public void display1()

{ // from here method level scope starts

// it will give compile time error as


// you are trying to access the local
// variable of method display()
Console.WriteLine(m);

} // here method level scope ends

} // here class level scope ends

Block Level Scope

 These variables are generally declared inside the for, while statement etc.
 These variables are also termed as the loop variables or statements variable as they have limited
their scope up to the body of the statement in which it declared.
 Generally, a loop inside a method has three level of nested code blocks(i.e. class level, method
level, loop level).
 The variable which is declared outside the loop is also accessible within the nested loops. It means
a class level variable will be accessible to the methods and all loops. Method level variable will be
accessible to loop and method inside that method.
 A variable which is declared inside a loop body will not be visible to the outside of loop body.

Example:

// C# code to illustrate the Block


// Level scope of variables
using System;

// declaring a Class
class GFG

{ // from here class level scope starts

// declaring a method
public void display()

{ // from here method level scope starts

// this variable has


// method level scope
int i = 0;

for (i = 0; i < 4; i++) {

// accessing method level variable


Console.WriteLine(i);
}

// here j is block level variable


// it is only accessible inside
// this for loop
for (int j = 0; j < 5; j++) {
// accessing block level variable
Console.WriteLine(j);
}

// this will give error as block level


// variable can't be accessed outside
// the block
Console.WriteLine(j);

} // here method level scope ends

} // here class level scope ends

C# Operators :
An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations.
C# has rich set of built-in operators and provides the following type of operators −

 Arithmetic Operators
 Relational Operators
 Logical Operators
 Bitwise Operators
 Assignment Operators
 Misc Operators

This tutorial explains the arithmetic, relational, logical, bitwise, assignment, and other operators one by
one.

Arithmetic Operators

Following table shows all the arithmetic operators supported by C#. Assume variable A holds 10 and
variable B holds 20 then

Operator Description Example


+ Adds two operands A + B = 30
- Subtracts second operand from the first A - B = -10
* Multiplies both operands A * B = 200
/ Divides numerator by de-numerator B/A=2
Modulus Operator and remainder of after an integer
% B%A=0
division
++ Increment operator increases integer value by one A++ = 11
-- Decrement operator decreases integer value by one A-- = 9
Relational Operators

Following table shows all the relational operators supported by C#. Assume variable A holds 10 and
variable B holds 20, then

Operator Description Example


Checks if the values of two operands are equal or not, if
== (A == B) is not true.
yes then condition becomes true.
Checks if the values of two operands are equal or not, if
!= (A != B) is true.
values are not equal then condition becomes true.
Checks if the value of left operand is greater than the
> value of right operand, if yes then condition becomes (A > B) is not true.
true.
Checks if the value of left operand is less than the value
< (A < B) is true.
of right operand, if yes then condition becomes true.
Checks if the value of left operand is greater than or
>= equal to the value of right operand, if yes then condition (A >= B) is not true.
becomes true.
Checks if the value of left operand is less than or equal
<= to the value of right operand, if yes then condition (A <= B) is true.
becomes true.

Logical Operators

Following table shows all the logical operators supported by C#. Assume variable A holds Boolean value
true and variable B holds Boolean value false, then

Operator Description Example


Called Logical AND operator. If both the operands are
&& (A && B) is false.
non zero then condition becomes true.
Called Logical OR Operator. If any of the two operands
|| (A || B) is true.
is non zero then condition becomes true.
Called Logical NOT Operator. Use to reverses the
! logical state of its operand. If a condition is true then !(A && B) is true.
Logical NOT operator will make false.

Bitwise Operators
Bitwise operator works on bits and perform bit by bit operation. The truth tables for &, |, and ^ are as
follows
p q p&q p|q p^q
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
Assume if A = 60; and B = 13; then in the binary format they are as follows −

A = 0011 1100

B = 0000 1101

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

A&B = 0000 1100

A|B = 0011 1101

A^B = 0011 0001

~A = 1100 0011

The Bitwise operators supported by C# are listed in the following table. Assume variable A holds 60 and
variable B holds 13, then

Operator Description Example


Binary AND Operator copies a bit to the result if it
& (A & B) = 12, which is 0000 1100
exists in both operands.
Binary OR Operator copies a bit if it exists in either
| (A | B) = 61, which is 0011 1101
operand.
Binary XOR Operator copies the bit if it is set in one
^ (A ^ B) = 49, which is 0011 0001
operand but not both.
(~A ) = -61, which is 1100 0011 in
Binary Ones Complement Operator is unary and has the
~ 2's complement due to a signed
effect of 'flipping' bits.
binary number.
Binary Left Shift Operator. The left operands value is
<< moved left by the number of bits specified by the right A << 2 = 240, which is 1111 0000
operand.
Binary Right Shift Operator. The left operands value is
>> moved right by the number of bits specified by the right A >> 2 = 15, which is 0000 1111
operand.

Assignment Operators

There are following assignment operators supported by C#

Operator Description Example


Simple assignment operator, Assigns values from right C = A + B assigns value of A + B
=
side operands to left side operand into C
Add AND assignment operator, It adds right operand to
+= C += A is equivalent to C = C + A
the left operand and assign the result to left operand
-= Subtract AND assignment operator, It subtracts right C -= A is equivalent to C = C - A
operand from the left operand and assign the result to
left operand
Multiply AND assignment operator, It multiplies right
*= operand with the left operand and assign the result to C *= A is equivalent to C = C * A
left operand
Divide AND assignment operator, It divides left
/= operand with the right operand and assign the result to C /= A is equivalent to C = C / A
left operand
Modulus AND assignment operator, It takes modulus C %= A is equivalent to C = C %
%=
using two operands and assign the result to left operand A
<<= Left shift AND assignment operator C <<= 2 is same as C = C << 2
>>= Right shift AND assignment operator C >>= 2 is same as C = C >> 2
&= Bitwise AND assignment operator C &= 2 is same as C = C & 2
^= bitwise exclusive OR and assignment operator C ^= 2 is same as C = C ^ 2
|= bitwise inclusive OR and assignment operator C |= 2 is same as C = C | 2

Miscellaneous Operators

There are few other important operators including sizeof, typeof and ? : supported by C#.

Operator Description Example


sizeof() Returns the size of a data type. sizeof(int), returns 4.
typeof() Returns the type of a class. typeof(StreamReader);
& Returns the address of an variable. &a; returns actual address of the variable.
* Pointer to a variable. *a; creates pointer named 'a' to a variable.
If Condition is true ? Then value X :
?: Conditional Expression
Otherwise value Y
Determines whether an object is of a certain If( Ford is Car) // checks if Ford is an object
is
type. of the Car class.
Object obj = new StringReader("Hello");
Cast without raising an exception if the cast
as
fails. StringReader r = obj as StringReader;

Operator Precedence in C#

Operator precedence determines the grouping of terms in an expression. This affects evaluation of an
expression. Certain operators have higher precedence than others; for example, the multiplication operator
has higher precedence than the addition operator.

For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +,
so the first evaluation takes place for 3*2 and then 7 is added into it.

Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at
the bottom. Within an expression, higher precedence operators are evaluated first.
Category Operator Associativity
Postfix () [] -> . ++ - - Left to right
Unary + - ! ~ ++ - - (type)* & sizeof Right to left
Multiplicative */% Left to right
Additive +- Left to right
Shift << >> Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left
Comma , Left to right

OOP Concepts :
C# provides full support for object-oriented programming including abstraction, encapsulation,
inheritance, and polymorphism.

 Abstraction means hiding the unnecessary details from type consumers.


 Encapsulation means that a group of related properties, methods, and other members are treated as a
single unit or object.
 Inheritance describes the ability to create new classes based on an existing class.
 Polymorphism means that you can have multiple classes that can be used interchangeably, even though
each class implements the same properties or methods in different ways.

You might also like