Professional Documents
Culture Documents
Credits : 04
The CLR is described as the "execution engine" of .NET. It provides the environment within
which the programs run. It's this CLR that manages the execution of programs and provides
core services, such as code compilation, memory allocation, thread management, and garbage
collection. Through the Common Type System (CTS), it enforces strict type safety, and it
ensures that the code is executed in a safe environment by enforcing code access security.
When the .NET program is compiled, the output of the compiler is not an executable file but a
file that contains a special type of code called the Microsoft Intermediate Language (MSIL),
which is a low-level set of instructions understood by the common language run time. This
MSIL defines a set of portable instructions that are independent of any specific CPU. It's the
job of the CLR to translate this Intermediate code into a executable code when the program is
executed making the program to run in any environment for which the CLR is implemented.
And that's how the .NET Framework achieves Portability. This MSIL is turned into executable
code using a JIT (Just In Time) complier. The process goes like this, when .NET programs are
executed, the CLR activates the JIT complier. The JIT complier converts MSIL into native code
on a demand basis as each part of the program is needed. Thus the program executes as a
native code even though it is compiled into MSIL making the program to run as fast as it
would if it is compiled to native code but achieves the portability benefits of MSIL.
The common language runtime manages memory, thread execution, code execution, code
safety verification, compilation, and other system services. These features are intrinsic to the
With regards to security, managed components are awarded varying degrees of trust,
depending on a number of factors that include their origin (such as the Internet, enterprise
network, or local computer). This means that a managed component might or might not be
The runtime enforces code access security. For example, users can trust that an executable
embedded in a Web page can play an animation on screen or sing a song, but cannot access
their personal data, file system, or network. The security features of the runtime thus enable
infrastructure called the common type system (CTS). The CTS ensures that all managed code
is self-describing. The various Microsoft and third-party language compilers generate managed
code that conforms to the CTS. This means that managed code can consume other managed
types and instances, while strictly enforcing type fidelity and type safety.
In addition, the managed environment of the runtime eliminates many common software
issues. For example, the runtime automatically handles object layout and manages references
to objects, releasing them when they are no longer being used. This automatic memory
management resolves the two most common application errors, memory leaks and invalid
memory references.
The runtime also accelerates developer productivity. For example, programmers can write
applications in their development language of choice, yet take full advantage of the runtime,
the class library, and components written in other languages by other developers. Any
compiler vendor who chooses to target the runtime can do so. Language compilers that target
the .NET Framework make the features of the .NET Framework available to existing code
written in that language, greatly easing the migration process for existing applications.
While the runtime is designed for the software of the future, it also supports software of today
and yesterday. Interoperability between managed and unmanaged code enables developers to
The runtime is designed to enhance performance. Although the common language runtime
provides many standard runtime services, managed code is never interpreted. A feature called
just-in-time (JIT) compiling enables all managed code to run in the native machine language
of the system on which it is executing. Meanwhile, the memory manager removes the
increase performance.
Microsoft® SQL Server™ and Internet Information Services (IIS). This infrastructure enables
you to use managed code to write your business logic, while still enjoying the superior
performance of the industry's best enterprise servers that support runtime hosting.
2. With the help of a suitable example, explain the steps in compiling and running a C#
program.
using System;
class Hello
{
public static void Main()
{
Console.WriteLine("Hello C#");
}
}
After entering the above code in an editor, you have to perform the following steps
1.Compile the code by giving the following command at the command prompt:
csc Hello.cs
1.If there are compile errors you will be prompted accordingly. Otherwise, you
will be viewing a command prompt along with the copyright information as
shown in Figure 4.
2.
As a final step, you have to execute the program in order to view the final output. For
that purpose, you have to simply give a command as shown below at the command
prompt. See Figure 4. If everything goes on well, then you can be able to view the
message “Hello C#” as shown in the figure above.
3. With the help of a suitable example explain the creation of a simple windows form
based application.
Answer
1. Double-click the button to add an event handler for the Click event. The Code
Editor will open with the insertion point placed within the event handler.
2. Insert the following code:
J# Copy
MessageBox.Show("Hello, World!");
This release of ASP.NET uses IIS 5.0 as the primary host environment. When
considering ASP.NET authentication, you should understand the interaction with IIS
authentication services.
IIS always assumes that a set of credentials maps to a Windows NT account and
uses them to authenticate a user. There are three different kinds of authentication
available in IIS 5.0: basic, digest, and Integrated Windows Authentication ( NTLM or
Kerberos ). You can select the type of authentication to use in the IIS administrative
services. For more information on IIS authentication, see the IIS documentation.
ASP.NET
authentication Description
provider
Forms A system by which unauthenticated requests are
authentication redirected to an HTML form using HTTP client-side
redirection. The user provides credentials and submits the
form. If the application authenticates the request, the
system issues a form that contains the credentials or a key
for reacquiring the identity. Subsequent requests are
issued with the form in the request headers; they are
authenticated and authorized by an ASP.NET handler using
whatever validation method the application developer
specifies.
Passport Centralized authentication service provided by Microsoft
authentication that offers a single log on and core profile services for
member sites.
<authorization>
<allow users = " [ comma separated list of users ] "
roles = " [ comma separated list of roles ] " />
<deny users = " [ comma separated list of users ] "
roles = " [ comma separated list of roles ] " />
</authorization>
The default settings for these elements are shown in the following table.
Answer
Use the MvcHttpHandler to handle MVC requests. Open the code-behind file of
Default.aspx (default.aspx.cs) and in the Page_Load method, process the request in
MVC style:
4. In order to use the MapRoute and IgnoreRoute methods, you should add a using
directive to use the namespace System.Web.Mvc, since those are extension methods.
The MapRoute method takes a name of a route as the first parameter, a URI template as
the second, and default values as the third. Notice that the default values object should
have properties that correspond the names of the properties in the URI template. The
route above maps an incoming Url to a combination of a controller and an action.
5. Create a default controller. Add a class to the web application under a Controllers
folder and name it DefaultController. Notice the naming convention for it: Default
comes from the route default value and the controller is just a suffix in the convention.
This class should inherit from System.Web.Mvc.Controller class, and should contain a
public method with a name the corresponds to an action. Since the default action is Index
(taken from the default route), then the class should look like this:
6. Run the application, and navigate to the application directory ( “/” ), what you should
get is the response “hello, world”.
But, If you try to navigate to the Index action in the Default controller (/Default/Index),
you will get an error.
7. Add the Url Routing Module. Open the web.config, and locate the <httpModules>
tab in the system.web section. There, register the Url Routing Module:
<httpModules>
...
<add name="UrlRoutingModule"
type="System.Web.Routing.UrlRoutingModule, System.Web.Routing,
Version=3.5.0.0, Culture=neutral,
PublicKeyToken=31BF3856AD364E35" />
</httpModules>
8. Run the application and navigate to the Index action in the Default Controller. Now,
you should get the same response as earlier.
9. Return a view as the result of the Index action. Change the return value of the Index
method in the default controller to be of type ActionResult. There are several types of
results we can return (such as JosnResult, ContentResult etc.) but in this sample we will
return a ViewResult, by calling the View method.
public ActionResult Index()
{
return View();
}
Create a view that corresponds to this action. When called parameterless, the
View method will look for a view whose name is equals to the name of the
action, inside a folder the corresponds to the name of the controller. Create a
new ASP.Net Form called Index.aspx inside Views\Default\ folder.
In order to make this an MVC View, open the code behind file (Index.aspx.cs) and
change the class to inherit from System.Web.Mvc.ViewPage.
Edit the page (in design mode or source mode) and add a greeting message:
<body>
<form id="form1" runat="server">
<div>
<h1>Hello, world</h1>
</div>
</form>
</body>
10. Run the application and you should receive the response from the View we’ve just
created. The routing engine called the Index action in the Default controller, which
returned the Index.aspx view.
11. Display data in the View. Open the controller, and in the Index method, add data to
the ViewData dictionary:
Now, in the view markup, use that data in the greeting line:
<body>
<form id="form1" runat="server">
<div>
<h1>Hello, <%= ViewData["name"] %></h1>
</div>
</form>
</body>
12. Run the application and receive a greeting message bounded to the data that the
controller has added to the dictionary.
In this post I build an ASP.Net MVC application from scratch in order to understand the
anatomy of an ASP.Net MVC application and the magic behind this framework. This
understanding can help me with adding MVC capabilities to my existing web
applications as well.
a. View State – Asp.Net uses View State to track the values in the Controls. You can
add custom values to the view state. It is used by the Asp.net page framework to
automatically save the values of the page and of each control just prior to rendering
to the page. When the page is posted, one of the first tasks performed by page
processing is to restore view state.
b. Control State – If you create a custom control that requires view state to work
properly, you should use control state to ensure other developers don’t break your
control by disabling view state.
c. Hidden fields – Like view state, hidden fields store data in an HTML form without
displaying it in the user's browser. The data is available only when the form is
processed.
d. Cookies – Cookies store a value in the user's browser that the browser sends with
every page request to the same server. Cookies are the best way to store state data
that must be available for multiple Web pages on a web site.
e. Query Strings - Query strings store values in the URL that are visible to the user.
Use query strings when you want a user to be able to e-mail or instant message
state data with a URL.
Both application state and session state information is lost when the application
restarts. To persist user data between application restarts, you can store it using
profile properties.
Implementation Procedure
View State:
The ViewState property provides a dictionary object for retaining values between
multiple requests for the same page. When an ASP.NET page is processed, the
current state of the page and controls is hashed into a string and saved in the page
as a hidden field. If the data is too long for a single field, then ASP.NET performs
view state chunking (new in ASP.NET 2.0) to split it across multiple hidden fields.
The following code sample demonstrates how view state adds data as a hidden form
within a Web page’s HTML:
Encrypting of the View State: You can enable view state encryption to make it more
difficult for attackers and malicious users to directly read view state information.
Though this adds processing overhead to the Web server, it supports in storing
confidential information in view state. To configure view state encryption for an
application does the following:
<Configuration>
<system.web>
<pages viewStateEncryptionMode="Always"/>
</system.web>
</configuration>
Alternatively, you can enable view state encryption for a specific page by setting the
value in the page directive, as the following sample demonstrates:
View State is enabled by default, but if you can disable it by setting the
EnableViewState property for each web control to false. This reduces the server
processing time and decreases page size.
Reading and Writing Custom View State Data:
If you have a value that you’d like to keep track of while the user is visiting a single
ASP.NET Web page, adding a custom value to ViewState is the most efficient and
secure way to do that. However, ViewState is lost if the user visits a different Web
page, so it is useful only for temporarily storing values.
Example: Determine the time of last visit to the page
Control State: If you create a custom control that requires ViewState, you can use
the ControlState property to store state information for your control. ControlState
allows you to persist property information that is specific to a control and cannot be
turned off like the ViewState property. To use control state in a custom control, your
control must override the OnInit method and call the Register-RequiresControlState
method during initialization and then override the SaveControl-State and
LoadControlState methods.
Hidden fields: ViewState stores information in the Web page using hidden fields.
Hidden fields are sent back to the server when the user submits a form; however,
the information is never displayed by the Web browser (unless the user chooses to
view the page source). ASP.NET allows you to create your own custom hidden fields
and store values that are submitted with other form data. A HiddenField control
stores a single variable in its Value property and must be explicitly added to the
page. You can use hidden fields only to store information for a single page, so it is
not useful for storing session data. If you use hidden fields, you must submit your
pages to the server using Hypertext Transfer Protocol (HTTP) POST (which happens if
the user presses a button) rather than requesting the page using HTTP GET (which
happens if the user clicks a link). Unlike view state data, hidden fields have no built-
in compression, encryption, hashing, or chunking, so users can view or modify data
stored in hidden fields.
Cookies: Web applications can store small pieces of data in the client’s Web browser
by using cookies. A cookie is a small amount of data that is stored either in a text file
on the client file system (if the cookie is persistent) or in memory in the client
browser session (if the cookie is temporary). The most common use of cookies is to
identify a single user as he or she visits multiple Web pages.
If you do not define the Expires property, the browser stores it in memory and the
cookie is lost if the user closes his or her browser.
To delete a cookie, overwrite the cookie and set an expiration date in the past. You
can’t directly delete cookies because they are stored on the client’s computer.
Controlling the Cookie Scope: By default, browsers won’t send a cookie to a Web site
with a different hostname. You can control a cookie’s scope to either limit the scope
to a specific folder on the Web server or expand the scope to any server in a domain.
To limit the scope of a cookie to a folder, set the Path property, as the following
example demonstrates:
Example:
Response.Cookies["lastVisit"].Path = "/Application1";
Through this the scope is limited to the “/Application1” folder that is the browser
submits the cookie to any page with in this folder and not to pages in other folders
even if the folder is in the same server. We can expand the scope to a particular
domain using the following statement:
Example:
Response.Cookies[“lastVisit”].Domain = “Contoso”;
Response.Cookies["info"]["visit"].Value = DateTime.Now.ToString();
Response.Cookies["info"]["firstName"].Value = "Tony";
Response.Cookies["info"]["border"].Value = "blue";
Response.Cookies["info"].Expires = DateTime.Now.AddDays(1);
Running the code in this example sends a cookie with the following value to the Web
browser:
(visit=4/5/2006 2:35:18 PM) (firstName=Tony) (border=blue)
Query Strings: Query strings are commonly used to store variables that identify
specific pages, such as search terms or page numbers. A query string is information
that is appended to the end of a page URL. A typical query string might look like the
following real-world example:
http://support.microsoft.com/Default.aspx?kbid=315233
In this example, the URL identifies the Default.aspx page. The query string (which
starts with a question mark [?]) contains a single parameter named “kbid,” and a
value for that parameter, “315233.” Query strings can also have multiple
parameters, such as the following real-world URL, which specifies a language and
query when searching the Microsoft.com Web site:
http://search.microsoft.com/results.aspx?mkt=en-US&setlang=en-
US&q=hello+world
Application State: ASP.NET allows you to save values using application state, a
global storage mechanism that is accessible from all pages in the Web application.
Application state is stored in the Application key/value dictionary. Once you add your
never exposed to the client. Application state is a great place to store information
that is not user-specific. By storing it in the application state, all pages can access
data from a single location in memory, rather than keeping separate copies of the
data. Data stored in the Application object is not permanent and is lost any time the
application is restarted.
ASP.NET provides three events that enable you to initialize Application variables (free
resources when the application shuts down) and respond to Application errors:
a. Application_Start: Raised when the application starts. This is the perfect place to
error logging.
Session State: ASP.NET allows you to save values using session state, a storage
mechanism that is accessible from all pages requested by a single Web browser
session. Therefore, you can use session state to store user-specific information.
Session state is similar to application state, except that it is scoped to the current
browser session. If different users are using your application, each user session has
a different session state. In addition, if a user leaves your application and then
returns later after the session timeout period, session state information is lost and a
new session is created for the user. Session state is stored in the Session key/value
dictionary.
session instances on the server. This allows you to track which pages a user saw on
ii. Store session-specific data on the server for use across multiple browser or client-
device requests during the same session. This is perfect for storing shopping cart
information.
iii. Raise appropriate session management events. In addition, you can write
ASP.NET session state supports several different storage options for session data:
a. InProc Stores session state in memory on the Web server. This is the default, and
it offers much better performance than using the ASP.NET state service or storing
state information in a database server. InProc is fine for simple applications, but
robust applications that use multiple Web servers or must persist session data
This ensures that session state is preserved if the Web application is restarted and
also makes session state available to multiple Web servers in a Web farm. ASP.NET
State Service is included with any computer set up to run ASP.NET Web applications;
configuring the ASP.NET State Service, you must set the startup type to Automatic.
c. SQLServer Stores session state in a SQL Server database. This ensures that
session state is preserved if the Web application is restarted and also makes session
state available to multiple Web servers in a Web farm. On the same hardware, the
d. Custom Enables you to specify a custom storage provider. You also need to
e. Off Disables session state. You should disable session state if you are not using it
to improve performance.
Advantages
1. Better Scalability: With server-side state management, each client that connects
to the Web server consumes memory on the Web server. If a Web site has hundreds
management information can become a limiting factor. Pushing this burden to the
2. Supports multiple Web servers: With client-side state management, you can
distribute incoming requests across multiple Web servers with no changes to your
application because the client provides all the information the Web server needs to
process the request. With server-side state management, if a client switches servers
in the middle of the session, the new server does not necessarily have access to the
client’s state information. You can use multiple servers with server-side state
management, but you need either intelligent load-balancing (to always forward
requests from a client to the same server) or centralized state management (where
sending that information back and forth to the client can increase bandwidth
utilization and page load times, potentially increasing your costs and reducing
scalability. The increased bandwidth usage affects mobile clients most of all, because
they often have very slow connections. Instead, you should store large amounts of
Functionality exists in the Visual Studio IDE to create specialized subclasses of the
DataSet classes for a particular database schema, allowing convenient access to each field
through strongly-typed properties. This helps catch more programming errors at compile-
time and makes the IDE's Intellisense feature more beneficial.
Entity Framework
ADO.NET Entity Framework is a set of data-access APIs for the Microsoft .NET
Framework, similar to the Java Persistence API, targeting the version of ADO.NET that
ships with .NET Framework 4.0. ADO.NET Entity Framework is included with .NET
Framework 4.0 Service Pack 1 and Visual Studio 2010, released on January 2010. An
Entity Framework Entity is an object which has a key representing the primary key of a
logical datastore entity. A conceptual Entity Data Model (Entity-relationship model) is
mapped to a datastore schema model. Using the Entity Data Model, the Entity
Framework allows data to be treated as entities independently of their underlying
datastore representations.
Entity SQL, a SQL-like language, serves for querying the Entity Data Model
(instead of the underlying datastore). Similarly, LINQ extension LINQ to Entities
provides typed querying on the Entity Data Model. Entity SQL and LINQ to Entities
queries are converted internally into a Canonical Query Tree which is then converted into
a query understandable to the underlying datastore (e.g. into SQL in the case of a
relational database). The entities can use their relationships, with their changes
committed back to the datastore.
Following are five data access scenarios that are more complex than simple Select
queries. Each one is discussed in a succeeding topic. First, an RDO approach to the
problem is shown, followed by the ADO solution so that you can compare how each is
accomplished.
RDO
The procedure below illustrates a method for performing a parameterized Select
query: that is, a SELECT statement that requires one or more parameters. This process is
done in two steps:
1. Build a query that expects a parameter, pass in the first parameter, then perform
the query.
The first time the query is called, RDO attempts to create a new RDO query object.
Since the object is appended to the rdoConnection object’s rdoQueries collection, you can
reference it each time the procedure is called. Each subsequent time the procedure is
called, the Refresh method re-executes the query. This technique builds a temporary
stored procedure (SP) behind the scenes that is referenced by the Requery method. The
temporary SP is dropped when the connection is closed.
ADO
This procedure is designed to perform a table-access query that accepts a
parameter. You use the "?" character (as in the previous RDO example) to indicate where
the parameter is to be placed. In this case, though, you don't create an rdoQuery object
that is kept in a collection off the rdoConnection object; you instead use a stand-alone
ADO Command object created (and scoped) earlier. The first time through, you set up the
Command properties, and each time thereafter, you simply execute the command after
having changed the parameter.
ADO gives you a lot of flexibility here—more, in some cases than RDO. If you tell
ADO everything it needs to know about a query, it won't have to perform informational
queries against the database to get missing information, so queries run faster.
Note You don’t have to build the ADO Parameters collection in code, since it's
automatically created for you just like when you use RDO. However, it is possible to do so,
and doing so can improve performance, at the cost of a little code complexity. If you elect
to do it, make sure that the Command is associated with an open connection so ADO can
query the service provider (and the server) for the parameter's description.
To run the query and create the resultset, use the Execute method on the Command
object.
Cmd.Parameters(0).Value = QueryParam.Text
Set rs = Cmd.Execute()
ADOGrid1.ShowData rs
rs.Close
End Sub
The code below shows the RDO approach to these problems. First, it performs a
simple parameter-based SP and shows the results in the grid. Some accommodations are
made to the subsequent ADO design, and these are noted. It uses the same connections
established in the earlier examples.
Note that the code requires us to include a correct ODBC "Call" statement. Again,
this is not necessary in the UserConnection designer, but it’s essential in the RDO code-
based approach. Here, you use the stand-alone rdoQuery object and assign the already
open Connection to it. The rdoQuery object can then be used in subsequent calls to
handle a parameter query.
Note also that the code does not attempt to refer to the return status argument. This
value is not available until the resultset is fully populated; only then does SQL Server
return this value.
ADO
ADO has a lot of flexibility when it comes to performing stored procedures. But this
flexibility comes at the cost of more code. As with the previous example ("Performing a
Parameter Query"), it's possible to build your own ADODB Parameters collection. In this
case, you’re performing a simple two-argument SP, "AuthorByYearBorn", that returns a
small resultset. Note that although ADO allows you to create your own parameters, it's
not necessary to do so.
Note ADO collections are 0-based to match DAO. RDO collections are 1-based.
Set Qy.ActiveConnection = cn
Qy(0)="1947"
Qy(1)="1948"
Qy.CommandType = adCmdStoredProc
Qy.CommandText = "AuthorByYearBorn"
Set rs = Qy.Execute(ShowRows)
ADOGrid1.ShowData rs
End Sub
RDO
This example illustrates how to perform a query that returns more than one
resultset. It’s common for a stored procedure to return more than a single set of rows or a
resultset that contains results from an action query. As a result, your code must deal with
each of the resultsets individually, or else you won’t be able to use the product of your
query. In RDO, you use the MoreResults method to step through the resultsets one at a
time. Each call to MoreResults closes the current resultset and moves to the next (if there
is one).
ADO
The following code illustrates how to handle SPs that return multiple resultsets in
ADO. ADO’s approach is different from the RDO approach in that ADO uses the
NextRecordset method in which you assign the next recordset in the batch to an ADO
Recordset object. The next recordset read doesn't overwrite the first one, as it does in
RDO. ADO also allows for multiple recordsets, if the data provider supports it.
RDO
In case your application needs to manipulate tables directly, or perform a
maintenance operation (like SQL Server’s DBCC functions), you can use the Execute
method to run the query directly. In this case, you don’t need ODBC or SQL Server to
create a temporary SP to run the query as it’s only being done once. (If this were a
regular operation, it would be more efficient to create an SP to do it.) Note that you can
use the RowsAffected property to find out the number of rows affected by this query.
ADO
When you need to perform an action query, you can take advantage of the Execute
method in ADO. In this case, you have to set a few more properties than you do in RDO,
but these properties improve data access performance. This is because ADO doesn’t have
to poll the server to determine what to do, or how to handle the query. Note that the new
output argument for the Execute method returns the number of rows affected. Generally,
you don’t see Visual Basic using arguments passed back to the application; just
arguments passed to the object interface.
RDO
The following code demonstrates a query that can be used to drive a subsequent
"optimistic batch update" operation. In this case, you fetch a resultset using the
ClientBatch cursor library and save the bookmarks for each row fetched. When the user
chooses a row in the grid (where the rows are displayed), the code prompts the user for a
new value and writes it to the resultset. The changes are not made to the data, however,
until you perform the BatchUpdate method.
The following code demonstrates how to gather user input (in this case, author age),
and then use this information to update the database in a batch update operation:
ADO
In this batch operation, note that the routine used to change the chosen row in the
R/W resultset doesn't require starting an "Edit" session. To achieve the same effect as the
previous RDO example, simply change the contents of a field and use the Update method
to make the changes to the database.
Private Sub BatchOpsButton_Click()
sql = "Select * from Authors where year_born is null"
rs.Open sql, cnB, adOpenStatic, adLockBatchOptimistic
rs.MoveLast: rs.MoveFirst
ReDim bms(rs.RecordCount + 1) As Variant
Do Until rs.EOF
bms(i) = rs.Bookmark
i=i+1
rs.MoveNext
Loop
rs.MoveFirst
ADOGrid1.ShowData rs
rs.Close
End Sub
Disconnected Architectures
According to ADO.net, Dataset is said to be disconnected module and datareader is said to be connected
module.
In disconnected module, the whole data is obtained at one strech and the modification is doen to the local
table. In connected module, Only one row is obtained each time from the database.
ADO and ADO.NET are different in several ways:
· ADO works with connected data. This means that when you access data, such as viewing and updating
data, it is real-time, with a connection being used all the time. This is barring, of course, you programming
special routines to pull all your data into temporary tables.
ADO.NET uses data in a disconnected fashion. When you access data, ADO.NET makes a copy of the data
using XML. ADO.NET only holds the connection open long enough to either pull down the data or to make
any requested updates. This makes ADO.NET efficient to use for Web applications. It's also decent for
desktop applications.
· ADO has one main object that is used to reference data, called the Recordset object. This object basically
gives you a single table view of your data, although you can join tables to create a new set of records. With
ADO.NET, you have various objects that allow you to access data in various ways. The DataSet object will
actually allow you to store the relational model of your database. This allows you to pull up customers and
their orders, accessing/updating the data in each related table individually.
· ADO allows you to create client-side cursors only, whereas ADO.NET gives you the choice of either using
client-side or server-side cursors. In ADO.NET, classes actually handle the work of cursors. This allows the
developer to decide which is best. For Internet development, this is crucial in creating efficient applications.
· Whereas ADO allows you to persist records in XML format, ADO.NET allows you to manipulate your data
using XML as the primary means. This is nice when you are working with other business applications and
also helps when you are working with firewalls because data is passed as HTML and XML.
ASP.NET Security
Figure 2 shows the relationship between IIS and ASP.NET. When IIS receives a request
for a file registered to ASP.NET (for example, an ASPX file), it hands the request off to an
ISAPI DLL named Aspnet_isapi.dll. Aspnet_isapi.dll runs in the same process as IIS—that
is, inside Inetinfo.exe. ASP.NET applications run in a separate process named
Aspnet_wp.exe. Aspnet_isapi.dll forwards requests to Aspnet_wp.exe using a named pipe.
When the request reaches the worker process, it is assigned to a specific application
executing in a specific AppDomain. Once inside an AppDomain, the request travels
through the ASP.NET HTTP pipeline, where it is examined by various HTTP modules and
ultimately processed by the HTTP handler that corresponds to the resource type
requested. Machine.config contains the master list that maps file types to HTTP handlers.
Figure 2 Relationship between IIS and ASP
The architecture in Figure 2 changes somewhat when ASP.NET is paired with IIS 6.0.
Slated for release in 2002 with Windows Server 2003, IIS 6.0 will feature a more robust
security model that gives IIS administrators the ability to segregate applications into
surrogate processes very much like Aspnet_wp.exe. In IIS 6.0, there is no Aspnet_wp.exe;
instead, IIS provides the worker process. At the time of this writing, Microsoft plans to
connect Inetinfo.exe to worker processes using Local Procedures Calls (LPCs) rather than
named pipes.
What does all of this have to do with security? When Aspnet_isapi.dll forwards an
HTTP request to Aspnet_wp.exe, it also forwards the access token that it obtained from
IIS. That access token is typically one of the following: an IUSR_machinename token
representing an unauthenticated user, or a token representing an authenticated security
principal (for example, Bob).
Before processing the request by sending it through the targeted application's HTTP
pipeline, Aspnet_wp.exe does the following:
• It performs an ACL check on the requested resource using the access token
presented to it. If, for example, the request is a GET command asking for Foo.aspx, the
access token represents Bob, and Foo.aspx has an ACL that denies read permission to
Bob, then ASP.NET fails the request with an access denied error. ASP.NET performs this
ACL check regardless of whether impersonation is enabled in ASP.NET.
• It makes the access token available to the application that handles the request so
that, if desired, the application can impersonate the caller and protect resources
guarded by ACLs from code executed during the request.
The importance of these actions cannot be overstated. The ACL check that ASP.NET
performs before processing the request means you can deny Bob access to an ASPX file
simply by tagging that file with an ACL that denies Bob read access. The fact that
ASP.NET makes the caller's access token available for impersonation purposes means
you, the developer, have some latitude in deciding what identity to use when processing
the request. The right choice depends on what the application is designed to do and how
it's designed to do it. I'll provide some background to enrich your understanding.
By default, Aspnet_wp.exe runs as ASPNET, a special account that's set up when
ASP.NET is installed. ASPNET is a member of the Users group, which means it's privileged
enough to perform most of the actions a legitimate application might want to perform,
but restricted enough to prevent certain kinds of attacks. Unless you specify otherwise,
requests executed by ASP.NET use Aspnet_wp.exe's identity. Therefore, by default,
requests run as ASPNET. Among other things, this means that barring configuration
changes, there are certain actions an ASP.NET application can't perform, such as
modifying entries in the HKEY_LOCAL_MACHINE section of the registry.
The other option is to execute the request using the access token provided by IIS, a
technique known as impersonation. Impersonation is enabled by including the following
statement in the <system.web> section of a top-level Web.config file or modifying the
<identity> element already present in Machine.config:
<identity impersonate="true" />
If IIS assigns a request the identity of IUSR_machinename, impersonation won't buy
you much because IUSR_machinename is a weak account that enjoys few privileges on
the host machine. But if Windows authentication is enabled and IIS presents ASP.NET with
a token representing the actual requestor, impersonation ensures that the application
can't do anything on the Web server that the requestor isn't allowed to do.
To further complicate matters, Aspnet_wp.exe can be configured to run as a principal
other than ASPNET. Suppose you write an ASP.NET application that must have wider-
ranging permissions than those afforded ASPNET—for example, the freedom to write to
any part of the registry. You can configure Aspnet_wp.exe to run as SYSTEM by changing
the statement
<processModel userName="machine" ... />
in Machine.config to read:
<processModel userName="SYSTEM" ... />
This enables your application to do almost anything it wants on the host machine, but it
also makes ASP.NET less resistant to attacks. SYSTEM was the default when ASP.NET was
in beta, but that was changed shortly before the product shipped.
Another possible complication arises from the fact that in IIS 6.0, ASP.NET requests
will default to Network Service rather than ASPNET. If you use ACLs to allow access to the
ASPNET account while denying access to other security principals and find that requests
mysteriously fail with access denied errors after you install IIS 6.0, modify your ACLs to
allow access to Network Service rather than ASPNET.
Clearly, the identities assigned to the ASP.NET worker process and to the requests
that it executes play crucial roles in determining how successful an application is in
carrying out its appointed mission. If your head is spinning right now trying to make sense
of it all, don't fret; ASP.NET security will be far easier to grasp once you've experienced it
firsthand. In the meantime, here are some guidelines to help you sort through the options
and figure out which of them really matter for a given deployment scenario:
• If your application requires no special protection—if all of its pages can be freely
browsed by anyone and none are personalized for individual users—you needn't bother
with application-level security. Just grant Everyone access to the application's files and
be done with it.
• If you're building an intranet application or any application whose permissions are
based on mapping incoming requests to Windows accounts on your server, you'll
probably use Windows authentication and ACL authorization. In that case, you'll use
operating system ACLs to restrict access to pages that aren't intended for everyone.
You may or may not enable impersonation, depending on the needs of the application.
• If you're building an Internet application that serves the general public but want to
secure access to certain pages, you'll most likely use forms authentication and URL
authorization. In that case, you'll leave impersonation disabled and rely on credentials
entered in login forms as the basis for authorizations. Many of the aformentioned
issues regarding IIS and access tokens fall by the wayside in this scenario because you
grant Everyone access to the application's files and rely on URL authorizations in
Web.config to protect them.
A final thought to keep in mind is that if you use ACLs to limit access to
files and directories in an ASP.NET application, always grant the ASPNET
account—or whatever account Aspnet_wp.exe runs as—read access to
them. Otherwise, ASP.NET itself will be unable to read them and you'll
experience all kinds of access denied errors that you probably didn't expect.
There are two kind of assemblies in .NET; private and shared. Private
assemblies are simple and copied with each calling assemblies in the calling
assemblies folder. Shared assemblies (also called strong named assemblies) are
copied to a single location (usually the Global assembly cache). For all calling
assemblies within the same application, the same copy of the shared assembly is
used from its original location. Hence, shared assemblies are not copied in the
private folders of each calling assembly. Each shared assembly has a four part
name including its face name, version, public key token and culture information.
The public key token and version information makes it almost impossible for two
different assemblies with the same name or for two similar assemblies with
different version to mix with each other.
An assembly can be a single file or it may consist of the multiple files. In case of
multi-file, there is one master module containing the manifest while other
assemblies exist as non-manifest modules. A module in .NET is a sub part of a
multi-file .NET assembly. Assembly is one of the most interesting and extremely
useful areas of .NET architecture along with reflections and attributes, but
unfortunately very few people take interest in learning such theoretical looking
topics.
What is an assembly?
• The constituent files can include any file types like image files, text files etc. along with
DLLs or EXEs
• When you compile your source code by default the exe/dll generated is actually an
assembly
• Unless your code is bundled as assembly it can not be used in any other application
• When you talk about version of a component you are actually talking about version of
the assembly to which the component belongs.
• Every assembly file contains information about itself. This information is called as
Assembly Manifest.
The assembly which is used only by a single application is called as private assembly.
Suppose you created a DLL which encapsulates your business logic. This DLL will be used by
your client application only and not by any other application. In order to run the application
properly your DLL must reside in the same folder in which the client application is installed.
Thus the assembly is private to your application.
Suppose that you are creating a general purpose DLL which provides functionality which
will be used by variety of applications. Now, instead of each client application having its own
copy of DLL you can place the DLL in 'global assembly cache'. Such assemblies are called as
shared assemblies.
Global assembly cache is nothing but a special disk folder where all the shared
assemblies will be kept. It is located under <drive>:\WinNT\Assembly folder.
As stated earlier most of the assemblies are private. Hence each client application refers
assemblies from its own installation folder. So, even though there are multiple versions of
same assembly they will not conflict with each other. Consider following example :
• You also created a client application which uses Assembly1 say Client1
• You installed the client in C:\MyApp1 and also placed Assembly1 in this folder
• You now created another application Client2 which uses this changed Assembly1
• You installed Client2 in C:\MyApp2 and also placed changed Assembly1 in this folder
• Since both the clients are referring to their own versions of Assembly1 everything goes
on smoothly
Now consider the case when you develop assembly that is shared one. In this case it is
important to know how assemblies are versioned. All assemblies has a version number in the
form:
major.minor.build.revision
If you change the original assembly the changed version will be considered compatible
with existing one if the major and minor versions of both the assemblies match.
When the client application requests assembly the requested version number is matched
against available versions and the version matching major and minor version numbers and
having most latest build and revision number are supplied.
How do I create shared assemblies?
• Sign your DLL/EXE with the private key by modifying AssemblyInfo file
Microsoft now uses a public-private key pair to uniquely identify an assembly. These keys
are generated using a utility called SN.exe (SN stands for shared name). The most common
syntax of is :
sn -k mykeyfile.key
Where k represents that we want to generate a key and the file name followed is the file
in which the keys will be stored.
Before placing the assembly into shared cache you need to sign it using the keys we just
generated. You mention the signing information in a special file called AssemblyInfo. Open the
file from VS.NET solution explorer and change it to include following lines :
[assembly:AssemblyKeyFile("file_path")]
Now recompile the project and the assembly will be signed for you.
Note : You can also supply the key file information during command line compilation
via /a.keyfile switch.
Microsoft has provided a utility called AL.exe to actually place your assembly in shared
cache.
AL /i:my_dll.dll
Hands On...
Now, that we have understood the basics of assemblies let us apply our knowledge by
developing a simple shared assembly.
In this example we will create a VB.NET component called SampleGAC ( GAC stands
for Global Assembly Cache). We will also create a key file named sample.key. We will sign
our component with this key file and place it in Global Assembly Cache.
Here is the code for the component. It just includes one method which returns a string.
imports system
namespace BAJComponents
public class Sample
public function GetData() as string
return "hello world"
end function
end class
end namespace
sn -k sample.key
Now, wee will sign the assembly with the key file we just created.
AL /i:sampleGAC.dll
After hosting the assembly just go to WINNT\Assembly folder and you will find your
assembly listed there. Note how the assembly folder is treated differently that normal folders.
Now, we will create a sample client application which uses our shared assembly. Just
create a sample code as listed below :
imports system
imports BAJComponents
public class SampleTest
shared sub main()
dim x as new sample
dim s as string="x".getdata()
console.writeline(s)
end sub
end class
Now, copy the resulting EXE in any other folder and run it. It will display "Hello World"
indicating that it is using our shared assembly.
2. Write a C# program to perform basic arithmetic operations
answer
a program to store the details of employees. Depending upon the post of the employee,
there would be various fields associated with it. A department head, for example, would
have a property denoting the department he heads, etc. We use conditional branching in
such a scenario.
if .. else
Syntax:-
if ( < condition > )
{
statements
}
else
{
statements
}
The else part is optional and can be omitted. The working of if .. else construct is very
simple and follows the pattern - If this is true I’ll do that or else I’ll do something else.
The statements included within the if block are executed when the condition specified in
if, is true, otherwise the statements inside the else block are executed. In case, there is no
else statement, the execution flow continues to the proceeding statements.
Here’s an example:-
CODE
Console.WriteLine("Enter your age:");
int Age = Convert.ToInt32(Console.ReadLine());
if (Age < 18)
{
Console.WriteLine("You are not permitted in here.");
}
else
{
Console.WriteLine("You may come in.");
}
Lets step through the code. Line 1 displays a message Enter your age. At line 2, the age
entered by the user is read using ReadLine() (as a string) and converted to an integer
using the ToInt32 function. Finally the value is stored in the integer variable Age. When
the execution reaches line 3, the expression inside if is evaluated. If the user supplied an
age less than 18, the execution flow would move to line 5 - Console.WriteLine("You
are not permitted in here."); and the message You are not permitted in here would be
displayed. In the other scenario, when the age would be either equal to or greater than 18,
line 7 would be executed and the message You may come in will be displayed.
The condition inside the if statement can be composed of a complex expression chained
by the logical operators. For Example:-
CODE
Console.WriteLine("Enter your age:");
int Age = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Are you with your guardian? (True/False)");
bool WithGuardian = Convert.ToBoolean(Console.ReadLine());
if ((Age < 18 ) && (WithGuardian = false))
{
Console.WriteLine("You are not permitted in here.");
}
else
{
Console.WriteLine("You may come in.");
}
At line 4 the user's response of whether he/she is with a guardian would be stored inside
the boolean variable WithGuardian. Notice that ToBoolean function is used to convert
the input to boolean (True/False) value. At line 5, the complex expression will be
evaluated. The expression is made up of two sub-expressions: Age < 18 and
WithGuardian = false. These two expressions are joined with the logical AND operator
(&&). Therefore, when both of the expressions amount to true, the entire expression
would evaluate to true and the message - You are not permitted in here will be displayed.
For any other combination, the final expression would be equivalent to false and the
message - You may come in will be displayed.
CODE
Console.WriteLine("Enter your salary");
int Salary = Convert.ToInt32(Console.ReadLine());
if (Salary > 250000)
{
Console.WriteLine("Welcome Mr. CEO");
}
else if (Salary > 200000)
{
Console.WriteLine("Welcome Mr. Chairman");
}
else if (Salary > 0)
{
Console.WriteLine("Welcome Programmer");
}
else
{
Console.WriteLine("Welcome dear Customer");
}
In this case, if the salary supplied by the user is greater than 250000, the message -
Welcome Mr. CEO will be displayed otherwise if the Salary is greater than 2000000 then
the output will be Welcome Mr. Chairman else if the salary is greater than 0, the message
- Welcome Programmer will be displayed. For any other value (Salary less than 1), the
statements inside the else block would be executed and Welcome dear Customer will be
the output.
Syntax:-
switch (< expression >)
{
case Expression_1;
statements
break;
case Expression_2;
statements
break;
….
break is a C# keyword, which is used to exit the body of a switch, for or while loop.
Equivalent to the else construct is the default case. Statements within the default case are
executed when no other condition holds true.
Example:-
CODE
Console.WriteLine("Enter the month (mm)");
int Month = Convert.ToInt32(Console.ReadLine());
switch (Month)
{
case 1:
Console.WriteLine("January");
break;
case 2:
Console.WriteLine("February");
break;
case 3:
Console.WriteLine("March");
break;
case 4:
Console.WriteLine("April");
break;
case 5:
Console.WriteLine("May");
break;
case 6:
Console.WriteLine("June");
break;
case 7:
Console.WriteLine("July");
break;
case 8:
Console.WriteLine("August");
break;
case 9:
Console.WriteLine("September");
break;
case 10:
Console.WriteLine("October");
break;
case 11:
Console.WriteLine("November");
break;
case 12:
Console.WriteLine("December");
break;
default:
Console.WriteLine("There are only 12 Months.");
break;
}
Depending on the value entered by the user (1-12), the appropriate month will be
displayed. For any other value, the default case will be executed and the message There
are only 12 Months. will be displayed.
Multiple Values can be made to lead to the same block of statements by excluding the
break statement.
CODE
Console.WriteLine("Enter a number (1-10)");
int Num = Convert.ToInt32(Console.ReadLine());
switch (Num)
{
case 2:
case 3:
case 5:
case 7:
Console.WriteLine("The number is prime.");
break;
case 1:
case 9:
Console.WriteLine("The number is odd.");
break;
case 4:
case 6:
case 8:
Console.WriteLine("The number is Even");
break;
default:
Console.WriteLine("The number is not in range.");
break;
}
Looping
A Set of instructions that are repeated is called a loop. Suppose you want to print
numbers from 1 - 10. You could do that using Console.WriteLine statement for each of
the 10 numbers. But, what if you had to print numbers from 1 - 1000? Using the
computer’s iterative power is a much better approach.
To print numbers within a range, say 1 - 1000, we declare a counter variable (preferably
single character variable like I), initialize it to the starting number (1) and keep
incrementing its value by 1 until the number exceeds the end point (1000). Off course, we
would have the body of the loop where the operation would be done, in this case,
displaying the numbers on screen.
CODE
for(int I = 1; I <= 1000; I++)
{
Console.WriteLine(I);
}
All the parts here are optional and can be left out. So, you can initialize the variable I,
above the for statement and leave out the initialization block. The code would look like
this (; I <= 1000; I++). Similarly, you could remove the condition part to make the loop
infinite or you can include the increment statement within the body of the for statement
itself (inside the { and } brackets).
Another variation of a for statement is the empty loop which does not contain any body:
for(int I = 1; I <= 1000; I++);
Syntax:-
while(< condition >)
{
statements
}
We don’t have initialization and increment/decrement slot over here. These need to be
implemented additionally. Take a look at the code snippet below.
CODE
bool Continue = true;
while(Continue == true)
{
int A;
Console.WriteLine("Please Enter a Number");
A = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Continue (True/False)");
Continue = Convert.ToBoolean(Console.ReadLine());
}
Anything that can be implemented using for loop, can also be done using the while loop.
Below is the code to print numbers from 1 - 1000 using while.
CODE
int I = 1;
while(I <= 1000)
{
Console.WriteLine(I);
I++;
}
CODE
bool Continue;
do
{
int A;
Console.WriteLine("Please Enter a Number");
A = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Continue (True/False)");
Continue = Convert.ToBoolean(Console.ReadLine());
}
while(Continue == true);
Note: The while part in the do while loop needs to be terminated with the semicolon.
Although, either of the three types of loops can be used to do an iteration, one needs to
use the appropriate loop for the job. Use the for loop for arithmetic operations, while
loop for non-arithmetic ones and the do-while loop when the loop must execute at least
once.
Every thing starts with a use case in Object Oriented Software Engineering. One of
the use cases while we develop web application is that
Now what a deal??? We see every day, every where, consistent web-sites etc., etc�
We see good-looking �sexy� web sites, but we don�t see one thing (well! you can�t
see that), how much maintenance cost is required if we need one change for the whole of
the web site. Look's a big deal now :).
Apart from some CSS style-sheet for consistency, what else we need, a framework,
Master-Page Framework, which should be extendible, easy to use, pluggable and
modifiable visually! (Sounds great! what a wish :)) There is no such thing existing in
ASP.NET (Whidbey, does have one, but still long way to go).
I started looking around the web and found some interesting articles:
• Master Your Site Design with Visual Inheritance and Page Templates by Fritz
Onion.
• ASP.NET Page Templates - Using Inheritance by Peter Provost.
These articles are very good starting points, so I took the entire valuable advises
from them and went further, since, I was looking for something like a reusable/extendible
Framework. I took the responsibility of redesigning the whole wheel that never existed,
in the first place, how is that ;).
The approach I took, what I devised is, Pattern Oriented Architecture and Design
(POAD), not design patterns, they are different. I call it POAD because my application
has a peculiar look and feel that it follows a pattern. POAD means you have entire
prototypic pattern, your application will follow, but will be overridden later for concrete
structure of it (the concept needs a whole article and I would write later, with some
examples, hopefully next month). So the master-page has header, footer, navigator,
menus/submenus, and content place-holders that would be filled in later as needed for
concrete pages, How�s that, sounds good. Let's move further! Here are the steps
involved in designing the POAD based softwares.
Steps Involved:
Draw the whole abstract pattern your framework would provide.
If we decompose this pattern into objects, it�s being clear that we should have
something like skeleton or template for the place holders, i.e., there should be something
like a master-page that is composed of the placeholders, like header, footer, logo, menus,
navigator, and contents etc.
Since our plan is to change these place holders visually, we could safely put these
place holders in a user control (PageUserControlBase) that in turn contains all the place
holders. Call it a Master user-control, where you define your layout for these contents.
Now, our model would have a Master Page that in turn is composed of Master User-
Control (PageUserControlBase) that in turn is composed of placeholders, like this:
Getting closer, great! :) Now the visual part is decided that we provide using user-
control or so. We want this user-control to be pluggable at run time, so we�ll
dynamically load it at run time using web.config like this:
Master Custom-Control:
Every page can have one and only one HTML Form. We put all the server-controls
in this form (part-C). So, what we need is another object that would encapsulate all these
HTML-Rendering stuff shown above, like Part-A, Part-B, Part-C, and Part-D in it. If you
look at the Control class, it has all the functionality we are looking for. The Control is a
composite that means we can put other controls in it. So, it would be a good starting point
to start with a Custom control by extending the Control Object. This extended Custom
Control, we named it PageControlBase, will provide HTML rendering capability as well
as it would have a System.Web.UI.HtmlControls.HtmlForm object. This Form object
would be used to add our famous master-user-control or Part-C in it. Now, our master
page would be composed of some master custom control, and master-user-control. Here
is the UML diagram that demonstrates all these:
What we need is an integrator class that will insert Master User-Control into
Custom control form and attach it to the Master-Page. And that�s the MasterPageBase
class, derived from UI.Page class:-
void HtmlRenderStarts();
void PreHtmlRender();
void HtmlRender();
void PostHtmlRender();
void HtmlRenderEnds();
/// <summary>
/// </summary>
string PageTitle
{
get;
set;
}
/// <summary>
/// </summary>
string MetaInfo
{
get;
set;
}
}
• And here is the other place where the same design pattern is used:
Other patterns that are used are Factory and Composite Design Patterns. The
Factory pattern is used to create classes, and should provide one place; if we have plan to
put some business logic around their creation, we can do it, without breaking the existing
code.
Composite Pattern is built in with the .NET Framework, like Control Class is itself
based on composite pattern. Composite Pattern in its simple form is a list of list of
objects. Instead of reinventing my own containers for objects, I used the Control class as
my starting point.
So that�s it, we are done with the Framework. All you need is to derive your page
from the MasterPage class, and override the stuff you want to change in your concrete
classes. How we do it is shown using UML Diagram here:
Let�s discuss some typical scenarios we�ll come across while doing
implementation:
Here is the not so detailed objects sequence diagram, for the above scenario:-
In Asp.net 1.1 when you create web application with visual studio 2003
editor it will automatically create global.asax file, but this is not the same case
with visual studio 2005, 2008 it will not create global.asax file by default. You
need to explicitly add global.asax file to make use of this.
But here I want to make it clear that all the event and method will fired
according to it nature.
So till here we are clear that in visual studio 2005 and 2008 global.asax file is
default and if you want to add it you have to add manually.
How to create or add global.asax file in Asp.Net 2.0, 3.0 and 3.5?
Its simple , Right click on the solution explorer in visual studio editor -> Add
New Item -> Select "Global Application Class" - > press "Add" Button
Now you have added global.asax file in you web application.
By default you can see that below event method is automatically available in
your global.asax file.
Application_Start
Application_End
Application_Error
Session_Start
Session_End
Like This
view source
print?
01 <%@ Application Language="C#" %>
02 <script runat="server">
03 void Application_Start(object sender, EventArgs e)
04 {
05 // Code that runs on application startup
06 }
07 void Application_End(object sender, EventArgs e)
08 {
09 // Code that runs on application shutdown
10 }
11 void Application_Error(object sender, EventArgs e)
12 {
13 // Code that runs when an unhandled error occurs
14 }
15 void Session_Start(object sender, EventArgs e)
16 {
17 // Code that runs when a new session is started
18 }
19 void Session_End(object sender, EventArgs e)
20 {
21 // Code that runs when a session ends.
// Note: The Session_End event is raised only when
22 the sessionstate mode
// is set to InProc in the Web.config file. If session mode is set
23
to StateServer
24 // or SQLServer, the event is not raised.
25 }
26 </script>
Now we will explore each above listed method and its importance one by
one.
Application_Start - This method will get fired when First time the
application and web server (eg. IIS ) starts, That means If the IIS recycle or
restart again then this event also will be fired.
Session_Start - This event will be fired when a new user request a page
from the server. That means for every user request the page this event will b
fired.
Session_End - This code will be fired when session end for a use. But make
sure this event willl only fired when Session Mode is "InProc" as we know
there are three session state InProc, StateServer, SqlServer mode to store
session. For more information on Session in Asp.net Please Refer this Tutorial
view source
print?
01 public void Application_Start(object sender, EventArgs e)
02 {
03 //Create Application object and assign 0 to it
04 Application["TotalHits"] = 0;
05 }
06 public void Session_Start(object sender, EventArgs e)
07 {
//Lock the Application using Lock method of
08 application
09 Application.Lock();
//Increment by 1 Application object every time when
10 session starts
11 Application["TotalHits"] = Application["TotalHits"] + 1;
//Unlock the Application Object using Unlock() method
12 if Application object
13 Application.UnLock();
14 }
On the In Process Mode, the session variables are maintained within the
ASP.NET process. This is the fastest way, however, in this mode the variables are
destroyed when the ASP.NET process is recycled or shut down. Since the
application is recycled from time to time this mode is not recommended for
critical applications.
In ASPState Mode, ASP.NET runs a separate Windows service that maintains the
state variables. Because the state management happens outside the ASP.NET
process, this has a negative impact on performance, but it allows multiple
ASP.NET instances to share the same state server, thus allowing an ASP.NET
application to be load-balanced and scaled out on multiple servers.
In the SqlServer Mode, the state variables are stored in a database server,
accessible using SQL. Session variables can be persisted across ASP.NET process
shutdowns in this mode as well. The main advantage of this mode is it would
allow the application to balance load on a server cluster while sharing sessions
between servers. Learn more about these with the austin .net developer.
7. Write the basic steps in building Connection Strings from Configuration Files in
ADO.Net applications.
Answer
If certain elements of a connection string are known ahead of time, they can be
stored in a configuration file and retrieved at run time to construct a complete connection
string. For example, the name of the database might be known in advance, but not the
name of the server. Or you might want a user to supply a name and password at run time
without being able to inject other values into the connection string.
One of the overloaded constructors for a connection string builder takes a String as
an argument, which allows you to supply a partial connection string which can then be
completed from user input. The partial connection string can be stored in a configuration
file and retrieved at run time.
Example
This example demonstrates retrieving a partial connection string from a
configuration file and completing it by setting the DataSource, UserID, and Password
properties of the SqlConnectionStringBuilder. The configuration file is defined as
follows.
<connectionStrings>
<clear/>
<add name="partialConnectString"
connectionString="Initial Catalog=Northwind;"
providerName="System.Data.SqlClient" />
</connectionStrings>
Often, in legacy Web applications, users authenticate themselves via a Web form. This
Web form submits the user's credentials to business logic that determines their authorization
level. Upon successful authentication, the application then submits a ticket in the form of a
cookie, albeit a hard cookie or session variable. This ticket contains anything from just a valid
session identification access token to customized personalization values.
name This is the name of the HTTP cookie from which we will store our
authentication ticket and information, respectively.
loginURL This is the URL from which your unauthenticated client will be
redirected. In most scenarios, this would be your login page,
where the client is required to provide their credentials for
authentication.
protection This is used to set the method from which to protect your cookie
data. The following valid values can be supplied:
None: Used for sites that are only using cookies for
personalization and have weaker requirements for security. Both
encryption and validation can be disabled. This is the most
efficient performance wise, but must be used with caution.
timeout This is the amount of time (in integer minutes) that the cookie
has until it expires. The default value for this attribute is 30
(thus expiring the cookie in 30 minutes).
path This is the path to use for the issued cookie. The default value is
set to "/" to avoid issues with mismatched case in paths. This is
because browsers are case-sensitive when returning cookies.
In our web.config file, it's also important to note the value we have for the deny
child element of the authorization section (as highlighted below). Essentially, we set
that value of the users attribute to "?" to deny all anonymous users, thus redirecting
unauthenticated clients to the loginURL.
<configuration>
<system.web>
<authentication mode="Forms">
<forms name=".COOKIEDEMO"
loginUrl="login.aspx"
protection="All"
timeout="30"
path="/"/>
</authentication>
<authorization>
<deny users="?" />
</authorization>
</system.web>
</configuration>
18. Create your login page (as referenced in the loginURL attribute discussed
above). In this case, we should save our login page as login.aspx. This is the page to
where clients without valid authentication cookie will be redirected. The client will
complete the HTML form and submit the values to the server. You can use the
example below as a prototype.
19.
20. <%@ Import Namespace="System.Web.Security " %>
21. <html>
22. <script language="C#" runat=server>
23. void Login_Click(Object sender, EventArgs E)
24. {
25.
26. // authenticate user: this sample accepts only one user with
27. // a name of username@domain.com and a password of 'password'
28. if ((UserEmail.Value == "username@domain.com") &&
29. (UserPass.Value == "password"))
30. {
31. FormsAuthentication.RedirectFromLoginPage(UserEmail.Value,
32. PersistCookie.Checked);
33. }
34. else
35. {
36. lblResults.Text = "Invalid Credentials: Please try again";
37. }
38. }
39. </script>
40. <body>
41. <form runat="server">
42. <h3>Login Page</h3>
43. <hr>
44. Email:<input id="UserEmail" type="text" runat="server"/>
45. <asp:RequiredFieldValidator ControlToValidate="UserEmail"
46. Display="Static"
47. ErrorMessage="*"
48. runat="server"/>
49. <p>Password:<input id="UserPass"
50. type="password"
51. runat="server"/>
52. <asp:RequiredFieldValidator ControlToValidate="UserPass"
53. Display="Static"
54. ErrorMessage="*"
55. runat="server"/>
56. <p>Persistent Cookie:<ASP:CheckBox id="PersistCookie"
57. runat="server" />
58. <p><asp:button id="cmdLogin"
59. text="Login"
60. OnClick="Login_Click"
61. runat="server"/>
62. <p><asp:Label id="lblResults"
63. ForeColor="red"
64. Font-Size="10"
65. runat="server" />
66. </form>
67. </body>
68. </html>
It's important to note that the above page authenticates the client on the click
event of the cmdLogin button. Upon clicking, the logic determines if the username
and password provided match those hard-coded in the logic. If so, the client is
redirected to the requested resource. If not, the client is not authorized, and thus
receives a message depicting this.
You can adjust the logic to fit your needs, as it is very likely that you will not
have your usernames and passwords hard-coded into the logic. It is here at the
Login_Click function that you can substitute the logic with that of your own. It is
common practice to substitute database logic to verify the credentials against a data
table with a stored procedure.
You can also provide authorized credentials in the web.config file. Inside the
forms section, you would append a user element(s), as follows :
<configuration>
<system.web>
<authentication mode="Forms">
<forms name=".COOKIEDEMO"
loginUrl="login.aspx"
protection="All"
timeout="30"
path="/">
<credentials passwordFormat="Clear">
<user name="user1" password="password1"/>
<user name="user2" password="password2"/>
<user name="user3" password="password3"/>
</credentials>
</forms>
</authentication>
<authorization>
<deny users="?" />
</authorization>
</system.web>
</configuration>
Doing so allows you to authenticate against a list of users in your web.config file, easily. You
can append as many users as necessary. To authenticate against that list of users, you would
append the applicable logic in the click event of the cmdLogin button discussed above. Here
is the code :
Client Requirements
To enable forms authentication, cookies must be enabled on the client browser. If the
client disables cookies, the cookie generated by Forms Authentication is lost and the client will
not be able to authenticate.