Monday, January 6, 2014
To register ASP .NET to IIS server
start > run > cmd >
cmd> cd C:\Windows\Microsoft.NET\Framework64\v4.0.30319
cmd> aspnet_regiis -i
cmd> iisreset
Tuesday, February 3, 2009
AWStats log analyzer Error
Create/Update database for config "./awstats.site1.test.local.conf" by AWStats version 6.9 (build 1.925) From data in log file "C:\WINDOWS\system32\LogFiles\W3SVC582832298\ex090105.log" ...
Error: Your personalized LogFormat does not include all fields required by AWStats (Add %bytesd in your LogFormat string). Setup ('./awstats.tmp.mydomain.conf' file, web server or permissions) may be wrong. Check config file, permissions and AWStats documentation (in 'docs' directory).
mrcoffee365: AWStats does not read the default IIS log format without some configuration. Put the following Log format in your awstats awstats.model.conf file:
# Use this LogFormat for limited IIS log (default log format from IIS 6)
LogFormat="date time s-sitename s-ip cs-method cs-uri-stem cs-uri-query s-port cs-username c-ip cs(User-Agent) sc-status sc-substatus sc-bytes"
Don't put line break in.
A format like this works well for IIS logs:
LogFile="C:/WINNT/system32/LogFiles/W3SVC3/ex%YY-24%MM-24%DD-24.log"
When you run awstats, you can also specify which file you want it to run on (as long as it is where you specified for the LogFile location above):
perl c:\awstats-6.5\wwwroot\cgi-bin\awstats.pl -config=mymodel -LogFile="C:/WINNT/system32/LogFiles/W3SVC3/ex061123.log" -update
Again, no line breaks.
psimation:Hi Mrcoffee365
Thx alot for that, the first part should definately work.
However, do you perhaps know how I can modify the .conf fil to include ALL the log files I already have on file?
I'd hate to have to run that command 180 time manually ( I've basically got 180 days worth of log files that I need AWSTATS to process...)
mrcoffee365:I don't think there's an AWStats way to run it against multiple files at once. You can write a script file which creates each log file name. Or cut and paste the lines into a big .bat file.
Tuesday, January 27, 2009
Run Running Apache IIS on same machine same port 80 different IP
I use to work both in PHP and ASP and am not able to run ASP pages on Apache webserver. Can I install and run Apache + IIS on the same server/machine? If so what configuration and setting do I need?
Assuming that you want all servers to work on the standard port 80, you need a multihomed machine (i.e. multiple IP addresses) and if you are using IIS6, you need to configure it to listen only on some of these addresses.
J.D.
By default, IIS takes every IPs port 80, even if you've only specified each of the websites to have a single IP. You'll need to do the following:
1) Get httpcfg.exe (it's on the Windows 20003 CD, or google it).
2) Type the following in a command prompt to stop all IIS services: net stop http /y
3) Type the following in a command prompt to stop Apache service: net stop Apache2.2 (you can get the ServiceKeyName for a server by running this command: sc getkeyname "Apache2.2" ( go to compmgmt.msc computer management to find the display name of a service)
4) Use httpcfg to configure IIS to only listen on the IP you want it to (type at a cmd prompt, in the directory httpcfg is in): httpcfg set iplisten -i 192.168.1.8
5) Restart IIS Services: net start w3svc
6) Restart Apache service: net start apache2.2
Should do the trick.
Edit: After step 4, run the following: httpcfg query iplisten
Make sure only the IP address you wanted listed shows up. If others still do, use httpcfg delete iplisten -i 192.168.1.x to delete the entry
I managed to get it working:
In this case the problem was that IIS 6.0 has a feature called Socket Pooling that claims all ports for all loaded IP addresses, even if not configured in IIS.
So, IIS was hogging port 80 on the IP address I'd designated as the Apache address and causing it to not run. I installed Windows 2003 and got IIS running. Then I turned off IIS and installed Apache, associating it with the IP and port that I wanted. Then I turned off the Apache service and restarted IIS.
Then, what I had to do was:
1- Extract the httpcfg.exe utility from the support tools area on the Win2003 CD.
2 - stop all IIS services: net stop http /y
3 - have IIS listen only on the IP address I'd designated for IIS: httpcfg set iplisten -i 192.168.1.253
4 - make sure: httpcfg query iplisten (the ip's listed are the only ip addresses that IIS will be listening on and no other)
5- restart IIS Services: net start w3svc
Voila! Apache is listening on its default ports on 192.168.1.254 and IIS is listening on its default ports on 192.168.1.253.
Originally Posted by peppy
I know you can run them on a different port, but I want to run them both on port 80, is the possible with two network cards
thanks for your reply
You can disable the socket pooling in iis 5.0 to release the ip and port for apache to use. here is how to do it from Microsoft website:
1.Open a command prompt and make sure you are in the X:\Inetpub\Adminscripts folder (where X is the IIS installation drive). To do this, type the following lines at the command prompt: X:
CD\Inetpub\Adminscripts
2.After you open the Adminscripts folder, type the following line at the command prompt: cscript adsutil.vbs set w3svc/disablesocketpooling true
3.The command replies as follows: disablesocketpooling : (BOOLEAN) True
4.Stop and start the IIS Admin service.5.Restart the WWW service.
Good luck!
jscorpion
Thursday, January 8, 2009
SecureIIS web server
SecureIIS web server security delivers integrated multi-layered windows server protection. SecureIIS provides application layer protection via integration with the IIS platform as an ISAPI filter, protecting against known and unknown exploits, zero day attacks, and unauthorized web access.
Sunday, January 4, 2009
Preventing Log Evasion SQL Injection in IIS
By Robert Auger ( rauger (at) spidynamics (dot) com )
SPI Dynamics
Version 1.6
Last Modified: 8/25/2005
[TEXT] size: 8k (MD5 SUM: 12261e1bd161bc85a8563d730e3c6068)
Introduction
One of the most important functions a Web site has is the ability to track who is visiting it, where they are coming from, and what they are doing. While logs themselves may not always be the most accurate measurement of what's going on, they do provide a high level overview useful for tracking common user functions and tasks. There are instances when certain types of data aren't logged such as referrers, cookies, user agents, and POST data. Logging can also be used to track abnormal behavior including malicious requests sent by a potential attacker trying to break into your site. These logs can be extremely valuable in identifying if an attack was successful or not, as well as some of the exact commands that an attacker may have executed.
While performing a security review of Microsoft Internet Information Server (IIS), I started to explore IIS's logging capabilities and how they worked. Months earlier I discovered an issue in Sun One Application server (http://www.spidynamics.com/spilabs/advisories/sun-one.html) that allowed an attacker to evade certain logging functionality by sending a carefully crafted request. With this in mind, I started looking at IIS to see if it had similar issues. I discovered that if an attacker sends more then 4,097 characters to any logged field, IIS will substitute the data within that field with three periods. (I.E., ... )
The Problem
To demonstrate the problem you need access to a tool such as Telnet, or Netcat (http://netcat.sourceforge.net/ ) in order to send the raw HTTP request. Before sending our evasion request we're going to review how normal traffic appears in an IIS log file.
Normal RequestGET /?id=80
User-Agent: Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)
Host: TestServer
Logged Response
2005-08-10 16:35:32 172.16.10.3 - 172.16.10.111 80 GET /Default.asp id=80 200 Mozilla/4.0+(compatible;+MSIE+5.01;+Windows+NT+5.0)
In the example above the query string 'id=80' is logged after the filename. Next we'll send a request with a query string value totaling over 4,097 characters in an effort to evade logging.
Note: "id=" counts as part of the total length.Attack Request
GET /?id=
User-Agent: Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)
Host: TestServer
Logged Response (IIS 5.0 with default logging)
2005-08-10 17:21:29 172.16.10.3 - 172.16.10.111 80 GET /Default.asp ... 200 Mozilla/4.0+(compatible;+MSIE+5.01;+Windows+NT+5.0)
Logged Response (IIS 6.0 with default logging)
2005-08-10 17:09:54 172.16.10.116 GET /Default.asp ... 80 - 172.16.10.3 Mozilla/4.0+(compatible;+MSIE+5.01;+Windows+NT+5.0) 200 0 0
As you can see IIS didn't log the entire query string, but it was processed. This problem isn't limited to simply the query string value, but affects every portion of logging that accepts more than 4,097 characters as input including HTTP header values.
An attacker who wishes to exploit a SQL injection vulnerability for the purpose of stealing customer data will do everything possible to avoid being noticed. Following is an example request that an attacker may send to evade logging:
GET /?test=User-Agent: Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)
If an attacker can partially evade logging, they may be able to mask a particular vulnerability that may be known or unknown.
How-To Prevent IIS Log Evasion with UrlScan
Disclaimer: This information should be used as a guide. The exact configuration mentioned within this document may not be the best solution for your environment. The author assumes no responsibility for any damages or losses that may occur.
Microsoft released a security hardening tool for IIS dubbed "UrlScan" allowing server administrators to set various security lockdown measures including the ability to restrict the size of a user's request. With Urlscan not only can we set request size restrictions (blocking an attackers attempt to thwart IIS's logging capabilities), but we can also log the entire request string sent by the attacker for further analysis.
To start, first download UrlScan from (http://www.microsoft.com/downloads/details.aspx?familyid=23d18937-dd7e-4613-9928-7f94ef1c902a&displaylang=en) and configure it to block long requests. Blocking long requests ensures that the request never reaches the target application, which thwarts an attacker's attempt to mask the attack against a specific application.
Installation Steps:1. After downloading Setup.exe from Microsoft's site, double-click it.
2. If, after carefully reviewing the End User License Agreement, you agree to the installation of UrlScan, click "Yes."
3. When you see a pop-up box stating, "UrlScan has been successfully installed", installation is complete.
Two files (UrlScan.ini and UrlScan.dll) will be installed under %windir%\system32\inetsrv\urlscan, which is usually under
C:\WINNT\system32\inetsrv\urlscan on a Windows 2000 server.
Configuration Steps:
1. Go to the directory created by UrlScan (as stated above) and open the UrlScan.ini file.
2. The default setting "MaxQueryString=2048" is an acceptable default that will prevent query strings longer than 2,048 characters from being passed to the application.
3. Configure any other options you may need.
In URLScan 2.5, Microsoft introduced the "LogLongUrls" option that allows logging up to 128k of a request. This option can be enabled in UrlScan.ini by changing "LogLongUrls=0" to "LogLongUrls=1". By setting this option, you can log any attempts by an attacker who is trying to exploit this issue. You must restart IIS for this change to take effect.
Conclusions
Microsoft's URLScan is a very useful tool that every IIS administrator should take the time to investigate. This document outlines steps to harden your system against a specific threat. Documentation on how to enable length restrictions on request header data can be found at the URLScan homepage (http://www.microsoft.com/technet/security/tools/urlscan.mspx) Readers of this document are encouraged to explore other configuration options in URLScan to further lock down their machine. Microsoft confirms that this behavior works as designed. Previous versions of IIS (version 4.0 and below) were not tested for this vulnerability and may also be affected.
References
UrlScan Information Page:http://www.microsoft.com/technet/security/tools/urlscan.mspx
UrlScan Download Page:
http://www.microsoft.com/downloads/details.aspx?familyid=23d18937-dd7e-4613-9928-7f94ef1c902a&displaylang=en
Using URLScan on IIS
http://support.microsoft.com/default.aspx?scid=kb;[ln];307608
Installing ISAPI Filters (IIS 6.0)
Installing ISAPI Filters (IIS 6.0)
You can install filters for all of the sites on an application server (global filters), and you can install filters for individual Web sites (site filters). If you install both global filters and site filters, the two filter lists are merged for the site.
When several filters have registered for the same event, they are called sequentially. Filters with a higher priority are run before filters with a lower priority. If several filters have the same priority, global filters that are set in the master properties are run before the filters that are set at the site level. Filters with the same priority at the same inheritance level are run in the order in which they were loaded. You can change the filter load order by adjusting the properties for the Web server or the Web site.
Procedures
Important You must be a member of the Administrators group on the local computer to perform the following procedure or procedures. As a security best practice, log on to your computer by using an account that is not in the Administrators group, and then use the runas command to run IIS Manager as an administrator. At a command prompt, type runas /user:Administrative_AccountName "mmc %systemroot%\system32\inetsrv\iis.msc".
To add a filter to a Web server or Web site
1. | In IIS Manager, expand the local computer, right-click the Web server or Web site to which you want to add a filter, and then click Properties. |
2. | Click the ISAPI Filters tab, and then click Add.
If you are adding filters to a Web site, you will not see any global filters inherited from the Web server's master properties. You will see only the filters installed for the Web site, even though both sets of filters are run. |
3. | In the Filter name text box, type the name of the filter. |
4. | In the Executable text box, type the name of the DLL file or click Browse to navigate to it, and then click OK. |
5. | Click the up or down arrow to change the load order of a filter.
You can only change the load order of filters that have the same priority. |
6. | If you have added or changed a global filter, you must stop and restart the Web server to load the new filters into memory. |
Thursday, November 20, 2008
ASP.NET Session State Management Using SQL Server
ASP.NET Session State Management Using SQL Server
Web applications are by nature stateless. Statelessness is both an advantage and a disadvantage. When resources are not being consumed by maintaining connections and state, scalability is tremendously improved. But the lack of state reduces functionality severely. Ecommerce applications require state to be maintained as the user navigates from page to page. ASP.NET's Session object makes it easy for developers to maintain state in a Web application. State can be maintained in-process, in a session state server, or in SQL Server.
In-process state management is the ASP.NET default, and it offers the fastest response time, but does not work in a Web farm. Consequently, it is not practical in high capacity Web applications requiring the load to be spread over multiple servers. A dedicated session state server is shared by all servers in a Web farm, so it provides scalability of the Session objects across all Web servers. It cannot store state persistently. If a dedicated session state server goes down for any reason, all session state data is lost. SQL Server is another alternative for storing session state for all of the servers in a Web farm. Since SQL Server is a database, there is a popular misconception that ASP.NET session state maintained in SQL Server is stored persistently. By default, it is not. If the SQL Server is stopped, the session state data is lost. By making a few simple changes, state can be stored persistently. It is important to understand that persistent is not the same thing as permanent. ASP.NET places a time limit (timeout in web.config) on how long a session's state is maintained. If the SQL Server is configured to store state persistently and it is down for longer than the ASP.NET session timeout interval, the session state data is lost.
Configuring ASP.NET Session State Management
Use the sessionState section of the web.config file to configure an ASP.NET Web application to use a SQL Server for session state management. The session state timeout interval is specified by using the timeout parameter.
<!-- SESSION STATE SETTINGS
By default ASP .NET uses cookies to identify which requests
belong to a particular session.
If cookies are not available, a session can be tracked by
adding a session identifier to the URL.
To disable cookies, set sessionState cookieless="true".
-->
<sessionState
_ mode="SQLServer"
_ stateConnectionString="tcpip=127.0.0.1:42424"
_ sqlConnectionString="data source=127.0.0.1; integrated security=true"
_ cookieless="false"
_ timeout="20"
/>
Configure the SQL Server to store Session objects by running a script to create the ASPState database. Version 1.0 of the .NET Framework provides a state database configuration script in %SYSTEMROOT%\Microsoft.NET\Framework\v1.0.3705\InstallSqlState.sql. If you open the file, you will see a statement to create a database called ASPState. This probably adds to the confusion about state being persistent. The ASPState database contains stored procedures that create tables in tempdb. The tables in tempdb are where session state is actually stored. Thus, when the SQL Server is shutdown, all session state is lost. This raises an important question: If the SQL Server is never shutdown, will tempdb eventually become 100 percent full and run out of space? Recall that ASP.NET connections automatically time out and their resources are freed up after the timeout duration is exceeded. The InstallSqlState.sql script creates a job called ASPState_Job_DeleteExpiredSessions to delete expired sessions from tempdb. Recall that ASP.NET does not keep session resources alive indefinitely. To support this feature when a SQL Server is used to maintain state, the SQL Server Agent must be running so that the expired session deletion job runs as needed. By default, the job is scheduled to run every minute. It deletes session state rows with an Expires value less than the current time. The account under which the SQL Server Agent runs must have the privilege to execute the DeleteExpiredSessions stored procedure.
ASPState database scripts come in pairs. InstallSqlState.sql creates the database and supporting objects. UninstallSqlState.sql drops the database and all supporting objects (e.g., the job to delete expired sessions). You cannot drop a database if it is in use, so if the UninstallSqlState.sql script fails with this error message:
Server: Msg 3702, Level 16, State 4, Line 4
Cannot drop the database 'ASPState' because it is currently in use.
Microsoft Knowledge Base article 311209 says to stop the Web server service to overcome this error. An 「uninstallation」 failure can still occur even if the Web server service is stopped. Additionally, you might not want to stop the Web server service because that will cause all Web applications on the server to stop. Instead, use the SQL Server Enterprise Manager. Find the processes accessing the ASPState database and delete them. If users are still accessing the application and causing new processes to be created faster than you can delete them, go to the IIS console and select the Properties for the Web application. On the Directory tab, click the Remove button. This will prevent access to the Web application and allow you to kill any remaining processes accessing the ASPState database. Once the processes are gone, uninstallation should completely successfully. Be sure to go back to the IIS console and click the Create button to restore the Web application to normal working order if you previously clicked the Remove button.
Version 1.0 of the .NET Framework does not provide a script for creating an ASPState database that maintains state persistently. However, Microsoft Knowledge Base article 311209 does provide a link for downloading InstallPersistentSqlState.sql and UninstallPersistentSqlState.sql. The InstallPersistentSqlState.sql script causes the session state data to be stored in permanent tables in ASPState instead of temporary tables in tempdb.
Version 1.1 of the .NET Framework provides both InstallPersistentSqlState.sql and InstallSqlState.sql. The Framework Version 1.1 scripts are found in the %SYSTEMROOT%\Microsoft.NET\Framework\v1.1.4322 folder. Although the 1.0 and 1.1 versions of InstallPersistentSqlState.sql accomplish the same thing, they are different. For SQL Server 2000 and above, the 1.1 version creates the ASPState stored procedures using GETUTCDATE instead of GETDATE. The 1.0 version always uses GETDATE. You can use the Framework version 1.1 script to create a database for an application using the Framework version 1.0.
If you specify integrated security in the web.config file, you will have to create a server login for the ASPNET user and then make the login a user in the ASPState database. You will also have to grant permissions to the ASPNET user to use database objects. If you do not store state persistently, the ASPNET user must be granted permissions to use state management objects in tempdb. The prudent approach is to grant no more permissions than are absolutely necessary. Here are the permissions I granted after executing the Version 1.0 InstallSqlState.sql script:
USE masterGOEXECUTE sp_grantlogin [DBAZINE\ASPNET]GO
USE ASPState
GO
EXECUTE sp_grantdbaccess [DBAZINE\ASPNET]
GRANT EXECUTE on TempGetAppId to [DBAZINE\ASPNET]
GRANT EXECUTE on TempGetStateItemExclusive to [DBAZINE\ASPNET]
GRANT EXECUTE on TempInsertStateItemShort to [DBAZINE\ASPNET]
GO
USE tempdb -- remove this if using persistent state
GO -- remove this if using persistent state
EXECUTE sp_grantdbaccess [DBAZINE\ASPNET] -- remove this if persistent state
GRANT SELECT on ASPStateTempApplications to [DBAZINE\ASPNET]
GRANT INSERT on ASPStateTempApplications to [DBAZINE\ASPNET]
GRANT SELECT on ASPStateTempSessions to [DBAZINE\ASPNET]
GRANT INSERT on ASPStateTempSessions to [DBAZINE\ASPNET]
GRANT UPDATE on ASPStateTempSessions to [DBAZINE\ASPNET]
GO
If you use the InstallPersistentSqlState.sql, remove the three lines as indicated above.
Consider the grants shown above as a starting point for creating your own script appropriate for your environment.
Conclusion
ASP.NET offers two simple solutions to session state management in a Web farm. Only SQL Server offers persistent state management. A dedicated session state server does not offer persistent state management, but does not require the creation of a database (one more thing for the DBA to administer). The value of persistent state has to be weighed carefully. Maintaining session state persistently is useful only if the SQL Server can be brought back up within the session state timeout specified in the web.config. For those situations where using a SQL Server as a state server makes sense, ASP.NET makes it easy.
--
John Paul Cook is a database and .NET consultant. He also teaches .NET, XML, SQL Server, and Oracle courses at Southern Methodist University's location in Houston, Texas.
Contributors : John Paul Cook
Last modified 2005-04-12 06:21 AM
Session state management
If session stors in out-proc then where session stores in state server.
If possible for you please reply me.
Thanks and regards
Vishal
Replies to this comment
How to read the session id from other web aplication
regards,
jegan
SQL Server Version
I am running VS2005 full version along with a local copy of SQL Server developer's version.
I have configured everything correctly to store session state in SLQ server, which includes,
1. Web Config file entrees
2. Running the script in Query Analyzer and ensuring creation of ASPState database
3. Creation of ASPNET user, granting rights
4. configuring IIS to use SQL server for session State
but I keep getting error which I am pasting below,
Server Error in '/Database' Application.
--------------------------------------------------------------------------------
Unable to use SQL Server because ASP.NET version 2.0 Session State is not installed on the SQL server. Please install ASP.NET Session State SQL Server version 2.0 or above.
Can you please shed some light on it. I would appreciate
Using SQL Server for ASP.Net session state
Using SQL Server for ASP.Net session state
What is session state?
A session is defined as the period of time that a unique user interacts with a Web application. Session state is a collection of objects, tied to a session are stored on a server.
Why use SQL?
Once you start running multiple web servers for the same web site, the default asp.net session state, InProc, is no longer useful, as you cannot guarantee that each page request goes to the same server. It becomes necessary to have a central state store that every web server accesses.
SQL Server offers you centralized storage of a session state in a Web farm. It also offers the transactional capabilities that provide reliability to most relational database systems. You can use SQL Server to save a session. This process is not as efficient as InProc and StateServer mode, because you must store the information in a different process or on a different server. However, this option may be more efficient than using the aspnet_state service, depending on the actual workload and the database configuration. Once you start saving session state to a SQL database it will also persist through web server restarts and reboots.
For reliability you should consider storing session state for a web farm on a SQL cluster.
Creating the database
- Start Query Analyzer, connected to the server you want to use for state storage.
- Open and execute InstallSqlState.sql script file. By default, InstallSqlState.sql is located in one of the following folders;
system drive\ Windows\ Microsoft.NET\ Framework\version\ - If you are using trusted connections to connect to your server, you must change ownership of the state database to sa after creation. In Query Analyzer run
use ASPState
exec sp_changedbowner 'sa','true' - If you are using SQL authentication create a user and password for session state to use. At a minimum this user should havepermissions to execute the stored procedures in the ASPState database. You will have to manually set these, or if you're feeling dangerous, give the state user dbo rights to ASPState.
Configuring ASP.Net
To switch ASP.Net to use SQL you must update the <sessionState> element of your application's Web.config file as follows;
- Set the mode attribute of the <sessionState> element to SQLServer.
- Set the sqlConnectionString attribute to specify the connection string to your SQL Server
For example
<sessionState
mode="SQLServer"
sqlConnectionString="data source=server;user id=uid;password=pwd"
cookieless="false" timeout="20" />
If you specify integrated security/trusted connections in the database connection string (ie. "trusted_connection=true", or "integrated security=sspi"), you cannot use impersonation in asp.net, as your database connection will then run the context of the impersonated user, which will not have rights to the state database. You can, of course grant connections to that user context. KB 326606 has more details.
If you are configuring session state to be stored on a cluster you must manually override the .net machine keys on each server. KB 323262 has more details.
Configuring SQL2000 SP3
So, you have created the database, you've created the user, given it rights to all the stored procedures in the ASPState database, you've up to date with patches, Windows, IIS SQL, and you connect to your web site...
SELECT permission denied on object 'ASPStateTempApplications', database 'tempdb', owner 'dbo'.
INSERT permission denied on object 'ASPStateTempApplications', database 'tempdb', owner 'dbo'.
SELECT permission denied on object 'ASPStateTempApplications', database 'tempdb', owner 'dbo'.
SP3 for SQL 2000 adds a new security feature, disabled by default, cross-database ownership chaining (see KB 810474 for details). When this feature is disabled, ASP.Net session state stops working.
To reconfigure SQL 2000 SP3 for ASP.net session state you must run
use master
go
EXEC sp_configure 'Cross DB Ownership Chaining', '0';
RECONFIGURE
GO
Now restart your SQL server, then run
use master
go
EXEC sp_dboption 'ASPState', 'db chaining', 'true'
go
Timeouts under heavy load
If your web servers are under heavy load it may be useful to increase the time out for session state access. You can add the stateNetworkTimeout attribute to the sessionState settings in web.config and machine.config
<sessionState stateNetworkTimeout="15" />
If a Web server or a state server is under stress and cannot complete session accesses on time, event ID 1072 and event ID 1076 may be logged in the event log.
Caveats when using SQL session state
Using SQL is slower than using InProc session state. When storing basic data types (string, int, etc), ASP.Net can take 10%-25% longer to store their values. Complex types take even longer. Of course because you are connecting to a separate server it does use bandwidth on your network.
When using SQL Server mode, objects stored in session state are serialised and deserialised when a request is processed. So any objects which do not support serialisation cannot be stored in session state. In ASP.Net v1.0 a bug means that attempting to store a non-serialisable object does not throw an error, and so will probably pass unnoticed.
For session state to be maintained across different web servers in a web farm (the main reason for moving session state to SQL), the Application Path of the website (For example \LM\W3SVC\2) in the IIS Metabase should be identical in for all the web servers in the web farm. Microsoft's KB 325056 details this problem.
If you wish to persist session state through SQL server reboots you must follow the instructions in KB 311209 to move the session state tables from tempdb to the ASPState database.
Other resources
Peter Bromberg's Session State FAQ
KB 317604 HOW TO: Configure SQL Server to Store ASP.NET Session State
Sunday, December 31, 2006 7:07 PM
How a session id is generated for an aspx page in .net framework 1.1
How a session id is generated for an aspx page in .net framework 1.1
In this blog, I just wanted to write about the method within the .net framework which is responsible for generating the session id when a client requests an aspx page for the first time. This article doesn't talk about the various scenarios under which the session id is created.
I was curious to know which class/method within the .net framework is used to generate the session id when a request for an aspx page comes in. I was looking at the SessionStateModule class under the System.Web.SessionState namespace using the .net reflector written by Lutz Roeder - http://www.aisto.com/roeder/dotnet/
Inside this class, there is a method with the following signature
private IAsyncResult BeginAcquireState(object source, EventArgs e, AsyncCallback cb, object extraData)
{
}
Within this method, there is an if else statement which checks if the private string rqId is null or not. This is the string which actually stores the session id.
if (this._rqId != null)
{
sessionStateItem = this.GetSessionStateItem();
}
else
{
this._rqId = SessionId.Create(ref this._randgen);
if (!s_config._isCookieless)
{
HttpCookie cookie = CreateSessionCookie(this._rqId);
if (!this._rqContext.Response.IsBuffered())
{
throw new HttpException(HttpRuntime.FormatResourceString("Cant_write_session_id_in_cookie_because_response_was_flushed"));
}
this._rqContext.Response.Cookies.Add(cookie);
this._rqAddedCookie = true;
}
else
{
this._rqContext.Response.SetAppPathModifier(AppPathModifierFromSessionId(this._rqId));
HttpRequest request = this._rqContext.Request;
string url = request.Path;
string queryStringText = request.QueryStringText;
if ((queryStringText != null) && (queryStringText.Length > 0))
{
url = url + "?" + queryStringText;
}
this._rqContext.Response.Redirect(url, false);
this._rqAr.Complete(true, null, null);
IAsyncResult result = this._rqAr;
application.CompleteRequest();
return result;
}
}
In the above code snippet, if the rqId string is null, then the Session.Create method is called.
Session is an internal class within the System.Web.SessionState namespace which has a static method Create with the following definition
internal static string Create(ref RandomNumberGenerator randgen)
{
if (randgen == null)
{
randgen = new RNGCryptoServiceProvider();
}
byte[] data = new byte[15];
randgen.GetBytes(data);
return Encode(data);
}
Once the session id is generated, depending on how the cookieless attribute is set in the web.config (set to true or false) file; the session id is either added to the cookies collection or added to the URL.
Scenario 1 : Cookieless attribute set to false
If the cookieless attribute is set to false, then the session id is added to the cookies collection by making a call to the CreateSessionCookie method
private static HttpCookie CreateSessionCookie(string id)
{
HttpCookie cookie = new HttpCookie("ASP.NET_SessionId", id);
cookie.Path = "/";
return cookie;
}
After the cookie is created, it is added to the Response.Cookies collection. I was able to check the request and response headers using the fiddler tool (www.fiddlertool.com).
HTTP Request Header :
GET /webapplication1/webform1.aspx HTTP/1.1
Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-shockwave-flash, */*
Accept-Language: en-us
UA-CPU: x86
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; InfoPath.2; .NET CLR 2.0.50727)
Host: win2k3-6114
Proxy-Connection: Keep-Alive
HTTP Response Header :
HTTP/1.1 200 OK
Date: Tue, 29 May 2007 07:44:27 GMT
Server: Microsoft-IIS/6.0
MicrosoftOfficeWebServer: 5.0_Pub
X-Powered-By: ASP.NET
X-AspNet-Version: 1.1.4322
Set-Cookie: ASP.NET_SessionId=iddajxme35irfr45tcynode1; path=/
Cache-Control: private
Content-Type: text/html; charset=utf-8
Content-Length: 662
Notice the name of the cookie in the response header. You will also see this in the IIS log, once you enable the Cookie field for the specific web site and access the aspx page.
IIS Log:
#Fields: date time s-sitename s-ip cs-method cs-uri-stem cs-uri-query s-port cs-username c-ip cs(User-Agent) cs(Cookie) sc-status sc-substatus sc-win32-status
2007-05-28 05:04:03 W3SVC1 65.52.76.126 GET /webapplication1/webform1.aspx - 80 - 65.52.76.126 Mozilla/4.0+(compatible;+MSIE+7.0;+Windows+NT+5.2;+.NET+CLR+1.1.4322;+InfoPath.2;+.NET+CLR+2.0.50727) ASP.NET_SessionId= iddajxme35irfr45tcynode1 200 0 0
Scenario 2 - Cookieless attribute set to true
If the cookieless attribute is set to true, then the session id is added to the url. In this case, two trips are made to the server. First time, when the page is requested, the server responds with status code 302 (object moved) and in the next request, the server responds with status code 200 (OK. The client request has succeeded). This is because once the session id is added to the url, the Response.Redirect method is called. Notice the request and the response headers below.
HTTP Request Header :
GET /webapplication1/webform1.aspx HTTP/1.1
Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-shockwave-flash, */*
Accept-Language: en-us
UA-CPU: x86
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; InfoPath.2; .NET CLR 2.0.50727)
Host: win2k3-6114
Proxy-Connection: Keep-Alive
HTTP Response Header :
HTTP/1.1 302 Found
Date: Tue, 29 May 2007 08:06:19 GMT
Server: Microsoft-IIS/6.0
MicrosoftOfficeWebServer: 5.0_Pub
X-Powered-By: ASP.NET
X-AspNet-Version: 1.1.4322
Location: /webapplication1/(n2xrh3452rylcuevsv103cep)/webform1.aspx
Cache-Control: private
Content-Type: text/html; charset=utf-8
Content-Length: 662
HTTP Request Header :
GET /webapplication1/(n2xrh3452rylcuevsv103cep)/webform1.aspx HTTP/1.1
Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-shockwave-flash, */*
Accept-Language: en-us
UA-CPU: x86
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; InfoPath.2; .NET CLR 2.0.50727)
Host: win2k3-6114
Proxy-Connection: Keep-Alive
HTTP Response Header :
HTTP/1.1 200 OK
Date: Tue, 29 May 2007 08:06:19 GMT
Server: Microsoft-IIS/6.0
MicrosoftOfficeWebServer: 5.0_Pub
X-Powered-By: ASP.NET
X-AspNet-Version: 1.1.4322
Cache-Control: private
Content-Type: text/html; charset=utf-8
Content-Length: 662
You will not see the cookie being set in the response headers.
If you check the URL, it will look something like this
http://
In the IIS log, you will see two entries for webform1.aspx page, one with status code 302 and the next one with status code 200. However, the cookie value will be empty.
IIS Log:
#Fields: date time s-sitename s-ip cs-method cs-uri-stem cs-uri-query s-port cs-username c-ip cs(User-Agent) cs(Cookie) sc-status sc-substatus sc-win32-status
2007-05-29 08:06:19 W3SVC1 65.52.76.126 GET /webapplication1/webform1.aspx - 80 - 65.52.76.126 Mozilla/4.0+(compatible;+MSIE+7.0;+Windows+NT+5.2;+.NET+CLR+1.1.4322;+InfoPath.2;+.NET+CLR+2.0.50727) - 302 0 0
2007-05-29 08:06:19 W3SVC1 65.52.76.126 GET /webapplication1/webform1.aspx - 80 - 65.52.76.126 Mozilla/4.0+(compatible;+MSIE+7.0;+Windows+NT+5.2;+.NET+CLR+1.1.4322;+InfoPath.2;+.NET+CLR+2.0.50727) - 200 0 0
I hope you enjoyed reading this article.
Comments
# re: How a session id is generated for an aspx page in .net framework 1.1
Hi Karthic's
I have configured my website session as Outproc in SQL Server. I am handling a case for Outage. If in case my SQL Server is down for some reason. My website has one Public Error.aspx page whoes EnableSessionState is set to False.
When I Open the page directly its work fine but when i request a page whoes EnableSessionState=true and then when i redirect to Error.aspx page in case of SQL Server is down ; page doesn't open. I get the SQLException "Unable to connect..."
I wonder why a page set as EnableSessionState=false; ASP.NET tries to retrieve the session data. I also looked the code in SessionStateModule. While calling
GetSessionStateItem() checks are made if it is read-only/ Write which seems to suggest that in case when EnableSessionState =false , no calls are made.
I get a different behavior when i Override Session_Start() method. If in case you know something more abt the problem could help me it would be gr8.
-Debugger
HOW TO: Configure SQL Server to Store ASP.NET Session State
HOW TO: Configure SQL Server to Store ASP.NET Session State
On This Page
SUMMARYThis step-by-step article demonstrates how to configure Microsoft SQL Server fo...
Requirements
The following list outlines the recommended hardware, software, network infrastructure, and service packs that you need:- Microsoft Windows 2000 Professional, Microsoft Windows 2000 Server, Microsoft Windows 2000 Advanced Server, or Microsoft Windows XP
- Microsoft .NET Framework
- Microsoft Internet Information Services (IIS)
- Microsoft SQL Server
Configure SQL Server for ASP.NET SQL Server Session State
The following steps describe how to run the InstallSqlState.sql and the UninstallSqlState.sql script files to configure SQL Server mode session state management.- In SQL Query Analyzer, on the File menu, click Open.
- In the Open Query File dialog box, browse to the InstallSqlState.sql script file, and then click Open. By default, InstallSqlState.sql is located in one of the following folders:system drive\WINNT\Microsoft.NET\Framework\version\
system drive\Windows\Microsoft.NET\Framework\version\ - After InstallSqlState.sql opens in SQL Query Analyzer, click Execute on the Query menu to run the script.
- Before you run the UninstallSqlState.sql script file to uninstall SQL Server mode session state management configuration, you must stop the w3svc process. To do this, follow these steps:
- On the Windows Start menu, click Run, type cmd, and then click OK to open a command prompt.
- At the command prompt, type net stop w3svc. You receive confirmation that the w3svc process is stopped.
- In SQL Query Analyzer, on the File menu, click Open.
- In the Open Query File dialog box, browse to the UninstallSqlState.sql script file, and then click Open. By default, UninstallSqlState.sql is located in one of the following folders:system drive\WINNT\Microsoft.NET\Framework\version\
system drive\Windows\Microsoft.NET\Framework\version\ - After UninstallSqlState.sql opens in SQL Query Analyzer, click Execute on the Query menu to run the script.
- After you uninstall SQL Server mode session state management configuration, you must restart the w3svc service. To restart the w3svc process, type net start w3svc at a command prompt.
Modify the Web.config File of Your Application
To implement ASP.NET SQL Server mode session state management, you must modify the- Set the mode attribute of the
element to SQLServer to indicate that session state is stored in SQL Server. - Set the sqlConnectionString attribute to specify the connection string for SQL Server. For example:
sqlConnectionString="data source=MySQLServer;user id=
;password= "
Note The user,, must have permissions to perform this operation on the database.
The modifiedelement should appear as follows: Note Ensure that you use the correct case when you specify themode="SQLServer"
sqlConnectionString="data source=127.0.0.1;user id=;password= "
cookieless="false"
timeout="20"
/>
element and the associated attribute values. This code is case sensitive.
Troubleshooting
- If you do not stop the w3svc process before you run the UninstallSqlState.sql script file, you receive the following error message:Cannot drop the database 'ASPState' because it is currently in use
- If entries in the ASPStateTempSessions table are not removed after the related sessions expire, make sure that the SQL Server agent is running. You can implement this functionality through stored procedures that are scheduled through jobs in SQL Server. The SQL Server agent manages these jobs.
- When you use the default InstallSqlState.sql and UninstallSqlState.sql script files to configure ASP.NET SQL Server mode session state management, note that these files add the ASPStateTempSessions and the ASPStateTempApplications tables to the tempdb database in SQL Server by default. Furthermore, if you restart SQL Server, you lose the session state data that was stored in the ASPStateTempSessions and the ASPStateTempApplications tables.For additional information about how to run alternative scripts to configure persistent SQL Server session state management so that the session data is not lost when you restart the server, click the article number below to view the article in the Microsoft Knowledge Base: 311209 (http://support.microsoft.com/kb/311209/EN-US/ ) HOW TO: Configure ASP.NET for Persistent SQL Server Session State Management
REFERENCESFor additional information, click the article numbers below to view the articles...
http://msdn2.microsoft.com/en-us/library/87069683(vs.71).aspx (http://msdn2.microsoft.com/en-us/library/87069683(vs.71).aspx)
Cutting Edge: Using Session and Application Objects in ASP.NET (an MSDN Magazine article)
http://msdn.microsoft.com/msdnmag/issues/01/11/cutting/default.aspx (http://msdn.microsoft.com/msdnmag/issues/01/11/cutting/default.aspx)
APPLIES TO
- Microsoft ASP.NET 1.1
- Microsoft ASP.NET 1.0
- Microsoft SQL Server 2000 Standard Edition
- Microsoft SQL Server 7.0 Standard Edition
- Microsoft SQL Server 2000 64-bit Edition
which cannot be easily readable
by persons having
semi-blind eye-sights!!!!
why!!!
The page has some design problems. In the T-SQL code, some of the text is black, just like the page background! Highlighting the T-SQL reveals the hidden text.
<sessionState mode="SQLServer" sqlConnectionString="data source=server;user id=sa;password=sa" cookieless="false" timeout="20" ></sessionState>
It showing error
Parser Error Message: It is an error to use a section registered as allowDefinition='MachineToApplication' beyond application level. This error can be caused by a virtual directory not being configured as an application in IIS.
How cud I sort it out.
My application uses a SQL Session State Server in a load balanced environment with heavy loads. My application is called very often (Aprox. 7000 users simultaneously). I sparatically get a timeout problem with the application and have to restart IIS. The w3wp.exe preocess is using up a lot of memory and 100% CPU. Would this be a problem with the SQL State Server?
Thanks in advance....
This might help resolve your problem..
http://msmvps.com/blogs/greglow/archive/2007/02/04/improving-asp-net-session-state-database-performance-by-reducing-blocking.aspx#544414
You can find some good articles at
http://chiragrdarji.wordpress.com/2007/04/20/aspnet-session-state-management-using-sql-server/
PLZ tell me how can i done this job.
http://www.faqfront.com/document/sql-server-session-state
Simple and easy to understand.
Simple; objects have to be serialised before they pass out of process to either the asp.net session server or the database, this takes time.
And if you're using a database then that database round trip introduces another set of processing. Database calls aren't cheap!
I doubt it, the provider only takes a server name, so it will assume a database name of ASPSTATE; I'm not sure you'd want to either; littering your own database with the session tables strikes me as messy!
Interesting once. Yes, you could put a global exception handler at the global.asax, there's an Application_Error event you could handle inside that, as an exception handler of last resort.
I don't think that you see a session state specific exception, you'd just see normal SQL exceptions; but it's probably enough to get you going.
I want to share session to another web application in same server. do you know how to do that ?
0. Make sure all your classes/objects being added to the session are serialized.
1. Create your own ASPState database
2. Give ownership to system adminstrator
2. Run the install....sql
3. May receive 1 error saying an object existis. Ignore that.
4. Create another user
5. Give dbo setting and add to ASPState
6. Use this user's login to connect through sqlConnectionstring in sessionState under web.config
Check it out http://www.alachisoft.com.