Você está na página 1de 8

1. Different types of caching in asp .net?

Caching is 3 types
a. Output Caching or Page caching
b. Fragment Caching
c. Data Caching

Caching is a feature that stores data in local memory, allowing incoming requests to be served from memory directly.

ASP.NET provides the following types of caching that can be used to build highly responsive Web applications:

a. Output caching, which caches the dynamic response generated by a request.


b. Fragment caching, which caches portions of a response generated by a request.
c. Data caching, which allows developers to programmatically retain arbitrary data across requests
2. Which are the various modes of storing asp.net session?
Depending on where session data are stored, ASP.NET session state supports five different modes. They are all listed
in SessionStateMode enumeration:
a. Off - Used to disable sessions on website.
b. InProc - Sessions are stored inside of application's process on web server. Depending of IIS version used that
could be aspnet_wp.exe or w3wp.exe.
c. StateServer - Sessions are stored using State Server windows service.
d. SQLServer - SQL Server database is used to store sessions' data
e. Custom - Manage session state using custom session state provider. Storage could be anything you
implement in provider.

To specify session state mode in web.config, select one of these values for SessionState mode parameter:

<sessionState mode="Off|InProc|StateServer|SQLServer|Custom" />

In web.config file, <sessionState > element is located under <configuration>, <system.web> element.

Session State mode: Off

Off mode is used to disable sessions on complete website.

Disabling of Session State will increase performances of ASP.NET application. It is not enough to just not use session state
variables. Every time visitor make request to website, ASP.NET will create new session for that user. This takes some processing
time and uses server's memory. Also, Session_Start procedure is executed. With Session State disabled, application executes
faster and requires less memory.

To disable Session State in complete ASP.NET application, use this markup code in web.config:

<sessionState mode="Off" />

If you need sessions on part of application, but not on all pages, you can disable session state on page level. Use
EnableSessionState parameter of Page directive to disable sessions for certain page. Code could look like this:

<%@ Page EnableSessionState="False" %>

Or, to make session state read only, use Read-only value, like this:

<%@ Page EnableSessionState="ReadOnly" %>

Default value of EnableSessionState parameter is true. If you need to disable sessions or make it read on most, but not all pages,
you can change default behavior in web.config. For example this markup code will change default value for pages to Read-only:
<Configuration>
     <system.web>
       <!--By default, pages will have read only access to session state-->
       <pages enableSessionState="ReadOnly" />
     </system.web>
</configuration>

Session State mode: InProc

InProc is default value. When InProc is used, session data is stored in web server's memory inside of application process.
Because of that, InProc is fastest of all modes.

But, if ASP.NET process restarts or is recycled, all session variables are deleted. This could be serious problem because restart of
ASP.NET application could occur very often due to numerous reasons.

Since session variables are stored inside of process, they can't be used on websites which uses multiple processes. If website is
hosted on multiple servers (web farm) or multiple processors (web garden), every processor will run its own process. So, if
InProc is used, session data can't be shared between servers, although there is an option to use load balancing to direct all requests
from certain IP address to same server.

One more problem with InProc is scalability. Session data are stored in server's memory. If there are a lot of concurrent visitors,
web server could easily run out of physical memory. When this happens, Windows will start paging on disc which slows down
application and decreases performances.

InProc mode works by default and doesn't require any configuration.

Session State mode: StateServer

StateServer mode solves all problems mentioned if InProc mode is used. In StateServer mode, sessions are stored using State
Server windows service, in aspnet_state.exe process. Since session data are stored using Windows service and outside of
ASP.NET application process, session variables are intact when ASP.NET application restarts. But, they will be deleted if State
Server restarts.

State Server could be located on same machine as web server, or on separated computer. If dedicated State Server is used, web
server's memory remains free which is more scalable solution. At last, State Server supports multiple processes. It could be used
on web farms or web gardens.

State Server is implemented as Windows service. File of State Server is aspnet_state.exe. This file is located on
[SystemFolder]\Microsoft.Net\Framework\[.Net Framework Version Number]\aspnet_state.exe. Example location for ASP.NET
4.0 could be:

C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_state.exe

To implement State Server, you need to start State Server service, change few Windows Registry keys, edit web.config and
secure State Server if runs on dedicated machine.

How to use Session State service and web server on same machine

Session State service uses server's memory to store sessions. If both web server and state server are on same machine, you will
not get more scalable solution than InProc is. If there is no enough physical memory, Windows will use disc which drastically
decreases performances. Only benefit in case when web server and state server are on same computer, is that sessions will not be
lost on application restart.

To implement this option, you need to follow two short steps:


First, be sure that State Server windows service is running. Check in Windows Control Panel --> Services and assure that
"ASP.NET State Service" is started. You can also start state service using command prompt with line:

“Net start aspstate”

By default, State Server service is set up to start manually. Change startup type to Automatic so it will run again if computer
restarts.

Second step is to edit <sessionState> element in web.config to configure ASP.NET web application to use State Server. Like this:

<sessionState mode="StateServer" stateConnectionString="tcpip=127.0.0.1:42424" />

That is all. Now you can start ASP.NET application and session data will be stored out of application process, in State Server.

How to use Session State on remote machine

Storing session data on remote machine is more scalable option, since web server's memory stays intact and it's not used for
sessions. By default, Session State service will not allow connections from remote servers. To change this, you need to edit value
of Registry key
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\aspnet_state\Parameters\AllowRemoteConnections.
Default value is zero which means that State Server doesn't allow remove connections. Default value is desirable if you have only
one web server and it is on same computer as state server. To allow remote connections, change its value to 1.

Be aware that, if AllowRemoteConnections registry key is set to 1, State Server will talk to anyone, not just your desired web
server. Due to security reasons, you have to disallow access from any computer except web servers, especially if State Server is
connected to Internet.

Session State mode: SQLServer

SQLServer mode uses SQL Server database to store session data. Like State Server, SQL Server also stores variables outside of
ASP.NET process. This is most reliable of all possible modes. Sessions stored in SQL Server database could survive web server
restart, and also SQL Server restart. As drawback, SQLServer is slowest mode. This loss in speed is often ignored if reliability is
first priority, i.e. when session data are very important.

To use SQL Server as storage for sessions, first step is to create appropriate database schema on SQL Server. One of the ways to
do this is to execute InstallSqlState.sql or InstallPersistSqlState.sql T-SQL scripts against desired SQL Server. Both script files
are located in .Net framework version folder. For example, for .Net 4.0, the address could be:

C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallSqlState.sql

Please notice that you can't use script of ASP.NET 1.0 for use on ASP.NET 2.0 application.

Main difference between InstalSqlState.sql and InstallPersistSqlState.sql is in which database tables are created. For example
when InstallSqlState.sql is executed, SQL Server will create new database named AspState and all needed stored procedures in
it. But, two required tables: ASPStateTempApplications and ASPStateTempSessions tables will be located in tempdb
database.

In the other hand, if we use InstallPersistSqlState.sql, after script is executed, AspState database will contain all procedures and
tables in it.

So, only difference during installation is location where ASPStateTempApplications and ASPStateTempSessions tables will
be created. That is the cause of main difference in run time: if two required tables are stored in AspState database, i.e.
InstallPersistSqlState.sql is used, sessions will not be lost even if SQL Server machine is restarted. But, if tables are in TempDB
database (InstallSqlState.sql is used), sessions will be lost when SQL Server restarts.
Installing Session State schema using aspnet_regsql.exe tool

ASPNET_REGSQL.EXE is a command line program located in .Net Framework version number folder. For example, for .Net
Framework 4.0, path could be:

C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regsql.exe

You don't need to navigate to this folder. Faster way is to open Visual Studio Command Prompt which allows direct access to VS
tools.

ASPNET_REGSQL.EXE supports several parameters:

Parameter Description
-S [Server Name] Sql Server name or IP address, where sessions will be stored
-E Windows authentication is used to access SQL Server
-U [User Name] User name, if SQL authentication is used
-P [Password] Password, if SQL authentication is used
-D [Database Name] Database name. This parameter is used if parameter -sstype is equal to "c", which
means that custom database is used as session storage.
-ssadd Abbreviation of "Session State Add". This option adds session state database.
-ssremove This parameter removes existing session state database.
-sqlexportonly [Script File Name or Full If this parameter is used, program will not execute any SQL, but just create T-
Path] SQL script which can be executed later on server(s). This is useful in shared
hosting scenario.
-sstype [t|p|c] Type of session state storage. There are three possible values:

T: means temporary storage. Tables are created in TempDB database. In this case
session is lost if SQL Server restarts,
P: represents persistent storage. Session state tables are created in AspState
database,
C: custom storage. In this case, you specify database name where sessions will be
stored. Database name is set using -D parameter.

Some example configuration, which uses custom database named "YourCustomDatabaseName" for session storage and uses
windows authentication to connect to SQL Server, would be:

aspnet_regsql -ssadd -sstype c -d YourCustomDatabaseName -E

If you run aspnet_regsql without parameters, it will show wizard as Windows application. If you prefer graphical user interface,
you can use this wizard to specify each parameter and avoid using of command line arguments.

Installing Session State with SQLServer mode on shared web hosting

By default, Session state that uses SQLServer mode requires SQL Server Agent. SQL Server Agent runs job to delete data on
session expiration. In most cases, Agent is not allowed by hosting providers in shared web hosting scenario. Also, on shared web
hosting you are probably not allowed to create new database in code. So, only option to use SQLServer mode on shared web
hosting, is to remove parts in SQL code that create job and create new database.

Like in previous example, we'll use command line tool aspnet_regsql.exe. When -sqlexportonly parameter is used,
aspnet_regsql.exe will not execute SQL. It will just create .Sql script of given name.

For example, to create T-SQL script named "SessionScript", which creates custom database "SessionDb", we'll use:

aspnet_regsql -ssadd -sstype c -d SessionDb -sqlexportonly c:\SessionScript.sql


Generated scripts include part for creating database. But, on shared hosting we'll create database using web hosting control panel
or use some existing predefined databases. Because of that, we need to remove this part from script. T-SQL code which should be
removed is located on top of the script and in our case will look like this:

USE master
GO

/* Create and populate the session state database */

IF DB_ID(N'SessionDb') IS NULL BEGIN


 DECLARE @cmd nvarchar(500)
 SET @cmd = N'CREATE DATABASE [SessionDb]'
 EXEC(@cmd)
END

Since shared hosting providers mostly don't allow SQL Server Agent too, you need to remove parts that create job for deleting of
sessions. After that, script can be executed against database in shared hosting scenario.

But, we have another problem. Since we'll not use SQL Server Agent for deleting sessions, they will remain in database. We need
other mechanism to delete expired session.

Expired sessions are deleted when DeletedExpiredSessions stored procedure is executed. By default, this procedure is called by
Agent. As an alternative, you can call this procedure using line:

Exec [dbo]. [DeletedExpiredSessions]

Possible solution is to add this line to the beginning of procedure TempGetAppID. In this case expired sessions will be deleted
any time session data are requested. On high traffic web sites, this could be too often and possibly overburden SQL Server. Also,
you probably don't need to check expired session so often.

Another option is to create scheduled task which will execute in regular time intervals and call DeletedExpiredSessions
procedure. Scheduled task can be in form of ASP.NET page, web service, console application etc. For example, you can
execute .aspx page every minute. Since this page is executed every 60 seconds, it will not delete sessions exactly on session
timeout. It could be anywhere between 20 and 21 minutes. But, this option is much more scalable and 1 minute tolerance is
usually good enough. You can execute task more or less frequently if needed.

Session State in web farm or web garden scenario

If SQLServer mode is used, Session state will work if website is hosted on multiple servers (web farm) or multiple processors
(web garden). In case of multiple servers, you need to do two additional steps:

- Have same application path on all web servers.

- Use same machine key on all web servers. Machine key is used for encryption/decryption of session cookies. If machine keys
are different, one server can't decrypt session cookie saved by other servers, so sessions could not be read.

Web.config changes to store sessions on SQL Server

After running selected T-SQL script or using aspnet_regsql.exe tool, required database schema is installed. Next step is to edit
<sessionState> element in web.config file. <SessionState> element will tell ASP.NET that we'll use SQLServer mode and will
specify database connection string. Default mode is InProc (inside of ASP.NET process). To store session state on SQL Server,
ASP.NET requires to change mode attribute to "SQLServer" and to specify sqlConnectionString attribute to your SQL Server.
For example:

<sessionState  mode="SQLServer" sqlConnectionString="data source=127.0.0.1;user id=username;password=password" />


That is all you need to do. If you start web application, session data should be visible in ASPStateTempSessions table. You can
read or change data using SQL Server Management Studio or directly using ASP.NET code.

On shared hosting, you need to set allowCustomSqlDatabase parameter to true and add database name in sqlConnectionString
parameter. Possible configuration for sessions stored in "SessionDb" database could look like this:

<sessionState mode="SQLServer" allowCustomSqlDatabase="true" sqlConnectionString="Database=SessionDb; data


source=127.0.0.1;user id=username; password=password" />

3. What is Absolute and Sliding expiration?


Absolute Expiration allows you to specify the duration of the cache, starting from the time the cache is activated. The
following example shows that the cache has a cache dependency specified, as well as an expiration time of one minute.
Cache.Insert ("announcement", announcement, depends, _DateTime.Now.AddMinutes (1), Nothing)

Sliding Expiration specifies that the cache will expire if a request is not made within a specified duration. Sliding expiration
policy is useful whenever you have a large number of items that need to be cached, because this policy enables you to keep
only the most frequently accessed items in memory. For example, the following code specifies that the cache will have a
sliding duration of one minute. If a request is made 59 seconds after the cache is accessed, the validity of the cache would be
reset to another minute:

Cache.Insert ("announcement", announcement, depends, _Date Time. Max Value, _TimeSpan.FromMinutes


(1))

4. Difference between caching and application?


Cache: It’s nothing but a thought kind of memory. In respect to asp.net it’s the memory of the
machine/server from where the source-code is running. It is the one way which allows storing complex data
for reusability.

Now think criteria where clients access an ASP.NET page, there are basically two ways to provide them
with the information they need. The ASP.NET page can either obtain information from server resources,
such as from data that has been persisted to a database, or the ASP.NET page can obtain information from
within the application.

Retrieving information from a resource outside the application will require more processing steps, and will
therefore require more time and resources on the server than if the information can be obtained from within the
application space.

Now, suppose the information’s which sent to browser’s have already been prepared then how faster the process
of web-page.

The ASP.NET 3.5 Framework supports the following types of caching:

1. Page Output Caching:


Page Output Caching caches an entire page.

2. Partial Page Caching:


Partial Page Caching enables you to get around this problem by enabling you to cache only
particular regions of a page.
3. DataSource Caching:
You use DataSource Caching with the different ASP.NET DataSource controls such as the
SqlDataSource and ObjectDataSource controls. When you enable caching with a DataSource
control, the DataSource control caches the data that it represents.

4. Data Caching:
Finally, Data Caching is the fundamental caching mechanism. Behind the scenes, all the other
types of caching use Data Caching. You can use Data Caching to cache arbitrary objects in
memory. For example, you can use Data Caching to cache a DataSet across multiple pages in a
web application.

Note:

The Cache object can also have an expiration which would allow us to reinstitute data into the memory in
intervals. Using the same example as above, we can make the cache expire every two hours, and repopulate the
data. It would do this every 2 hours throughout the day, allowing the most up to date data to be fetched. Below
is an example of how something can be put into the cache.

Application: Its nothing but similar to Session with a bit difference that is Session objects have scope within a
particular session while application objects having scope within entire application.

Creating an application variable is similar to session variables.

Application (“applictionObj”) = “This is an application object”;

ASP.NET provides the following application-state support.

An application-state dictionary that is available to all request handlers invoked within an application. Unlike
Internet Information Services (IIS) and earlier versions of ASP, where only pages can access application state,
all IHttpHandler and IHttpModule instances can store and retrieve global variables within the dictionary.

A simple and intuitive synchronization mechanism that enables developers to easily coordinate concurrent
access to variables stored in the application state.

Application-state values that are accessible only from code running within the context of the originating
application. Other applications running on the system cannot access or modify the values.

Application-state variables are, in effect, global variables for a given ASP.NET application. Like client-side
application developers, ASP.NET programmers should always consider the impact of storing anything as a
global variable.

Application State Synchronization

Multiple threads within an application can simultaneously access values stored in application state.
Consequently, when you create something that needs to access application-state values, you must always ensure
that the application-state object is free-threaded and performs its own internal synchronization or else performs
manual synchronization steps to protect against race conditions, deadlocks, and access violations.

The HttpApplicationState class provides two methods, Lock and Unlock that allow only one thread at a time to
access application-state variables.

Application.Lock();
Application["SomeGlobalCounter"] = (int)Application["SomeGlobalCounter"] + 1;
Application.UnLock();

Calling Lock on the Application object causes ASP.NET to block attempts by code running on other worker
threads to access anything in application state. These threads are unblocked only when the thread that called
Lock calls the corresponding Unlock method on the Application object.

Você também pode gostar