|
|
asp.net process model
by Satalaj
24. February 2010 07:37
We can configure the Application Pool Recycling in two ways.
1. Reactive application pool process recycling.
2. Proactive application pool process recycling.
Reactive Process Recycling:
It happens when process is not functioning properly or unable to serve requests.
Symptoms: Process deadlocks, access violations, memory leaks, Insufficiant memory and so on, in order to trigger a process recycle.
You can help control the conditions that cause a process restart by using the requestQueueLimit, memoryLimit, and shutdownTimeout configuration attributes.
For more information about these attributes, see the <processModel> Element configuration section of Machine.Config file.
Proactive Process Recycling
Proactive process recycling restarts the worker process periodically even if the process is healthy.
This can be a useful way to prevent denials of service due to conditions the process model is unable to detect.
A process can be restarted after a specific number of requests or after a time-out period has elapsed. You can enable proactive process recycling using the timeout, idleTimeout, and requestLimit configuration attributes. For more information, see the <processModel> Element configuration section of Machine.Config file.
Below are the default settings of Process model found at machine.config file.
<processModel
enable="true"
timeout="Infinite"
idleTimeout="Infinite"
shutdownTimeout="0:00:05"
requestLimit="Infinite"
requestQueueLimit="5000"
restartQueueLimit="10"
memoryLimit="60"
webGarden="false"
cpuMask="0xffffffff"
userName="machine"
password="AutoGenerate"
logLevel="Errors"
clientConnectedCheck="0:00:05"
comAuthenticationLevel="Connect"
comImpersonationLevel="Impersonate"
responseRestartDeadlockInterval="00:09:00"
responseDeadlockInterval="00:03:00"
maxWorkerThreads="20"
maxIoThreads="20"
/>
Satalaj
Connection pooling
by Satalaj
29. January 2010 12:16
Hi, my name is Satalaj. Here, I'm going to explain what is connection pool with solid proof.
Connection pool as name suggest its a pool of Established connections.
When we are closing the connection in finally or in try catch block that doesn't mean we are closing Established connection with your db server.
Closing connection means notifying the application about that connection is free for future request.
Here, I will tell my connection string to use min pool size = 1 and max pool size = 2.
As soon as pool gets initialized it will establish only one connection with SQL server db.
You can use below query to test how many connections are established with your MS SQL db server. I established the connection with asptest DB.
select db_name(dbid) as DataBaseName , count(dbid) as
NoOFConnections , loginame as LoginName
from sys.sysprocesses where dbid > 0 and db_name(dbid) = 'apitest'
group by dbid,loginame
Here is screen shot of Established connection.
I fired a command netstat -b from my command prompt and found that WindowsApplication1.VShost.exe with process ID 6140
Established one connection with MS SQL server IP 192.168.1.1.28 on port 1433.
My application is running and it has processed his task and I have closed the connection. However, you can see the connection is Established
and it will stay established, still the life of application. If I colse the application, I will not see any connection with my DB APITEST.
TCP smartmirror:2096 192.168.1.28:ms-sql-s ESTABLISHED 6140
[WindowsApplication1.vshost.exe]
In my application I have one established connection. What will happen If I get 2 requests simultaniouesly?
Ans. The application will establish another connection to DB server as my Max pool size is 2 and that new connection will serve the request.
What if I get 3 or 4 simultaneous requests?
If there is no free connection available in connection pool the application will throw an error
Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.
What happens when I set Min pool size = 10 in my connection string ?
The application will establish 10 connection with DB.
You can see it by using query above and at client / server side, you can execute netstat -a command to know
which are the ports participates in this communication. You can see how my application is talking to sql server using ports ranging from 3979 to 3988.
TCP smartmirror:3979 192.168.1.28:ms-sql-s ESTABLISHED
TCP smartmirror:3980 192.168.1.28:ms-sql-s ESTABLISHED
TCP smartmirror:3981 192.168.1.28:ms-sql-s ESTABLISHED
TCP smartmirror:3982 192.168.1.28:ms-sql-s ESTABLISHED
TCP smartmirror:3983 192.168.1.28:ms-sql-s ESTABLISHED
TCP smartmirror:3984 192.168.1.28:ms-sql-s ESTABLISHED
TCP smartmirror:3985 192.168.1.28:ms-sql-s ESTABLISHED
TCP smartmirror:3986 192.168.1.28:ms-sql-s ESTABLISHED
TCP smartmirror:3987 192.168.1.28:ms-sql-s ESTABLISHED
TCP smartmirror:3988 192.168.1.28:ms-sql-s ESTABLISHED
It proves that I have 10 Established connections with SQL server and my application.
when I tell the connection object to close the connection, It only notifies the application about that "free connection", which can be used to serve next request.
When I tell connection object to open a connection I get a free connection form connection pool.
To know more about, how clients talks to the server refer http://revenmerchantservices.com/post/2010/01/25/client-server-communication.aspx
You can have multiple pools in applications. Of Course, there is a limit as there is limits on available ports ranging from 0 to 65535.
Its best practice not to have connection string opened in infinite time to serve the request. If you let the connection opened for infinite loop
your application will not be able to serve other requests. you can try it yourself by setting min and max pool size of your connection string.
By default min pool size is 0 and max pool size is 100.
Conclusion: I told connection object to open a connection with SQL DB server means I'm telling connection object to setup actual connection with DB server?
No, I'm telling the connection object to get the already established free connection from connection pool.
I hope you understood the location of Connection Pool and its importance.
Satalaj.
C# html Parser
by Satalaj
22. January 2010 10:44
If you came here by searching for C#.net or VB.net html parser, your search ends here.
While developing screen scrapping with C#.net, I came across very rich open source HtmlParser. Who is capable of parsing entire html document.
Here is a link to download and parse the required fields in html http://www.codeplex.com/htmlagilitypack.
It is very similar to librarys provided by .net to parse or iterate XMLDocuments.
code snippet:
It will give you list of all nodes of type Input. Here str is your actual HTML string that you received in HttpWebResponse object
HtmlAgilityPack.HtmlDocument hd = new HtmlAgilityPack.HtmlDocument();
hd.LoadHtml(str);
HtmlNodeCollection hc = hd.DocumentNode.SelectNodes("//input");
You can use Xpath query to iterate nodes and ChildNodes.
Satalaj
screen scrapping asp.net pages
by Satalaj
22. January 2010 10:19
If you want to crawl asp.net pages using HttpWebRequest and HttpWebResponse, you need to POST the __VIEWSTATE, EVENTARGUMENT and EVENTTARGET
along with your Request.
If that page stores session or cookies you need to pass session cookies and Cookies along with the HttpWebRequest object.
You need to use Post Method.
your post data will look like this
string postData = "__EVENTARGUMENT=" + value + "&_EVENTTARGET="+ targetValue+ "&__VIEWSTATE="+ViewState ;
You first use tools like fiddler to know how your broser post the data to .aspx pages then prepare your post string to post the data.
Satalaj
Server.Transfer vs Response.Redirect
by Satalaj
21. January 2010 10:50
Use Server.Transfer. whereever it is possible, use the Server.Transfer method instead of the Response.Redirect method.
Response.Redirect sends a response header to the client that causes the client to send a new request to the redirected server by using the new URL.
If you have tools installed like fiddler you can easily see what has been posted back inside Header to the clients like IE.
Its a Status code 302 and header contains location of resource.
Server.Transfer avoids this level of redirection by simply making a server-side call.
You cannot always just replace Response.Redirect calls with Server.Transfer calls because Server.Transfer uses a new handler during the handler phase of request processing.
If you need authentication and authorization checks during redirection, use Response.Redirect instead of Server.Transfer because the two mechanisms are not equivalent and
as you know during authontication we check wheather cookie exists in Request or not. There we must use Response.Redirect.
When you use Response.Redirect, ensure you use the overloaded method that accepts a Boolean second parameter, and pass a value of false to ensure an internal exception is not raised.
You can see that exception by simply putting Try catch Blocks in your application. To avoid internal exception pass second parameter as false.
Also note that you can only use Server.Transfer to transfer control to pages in the same application. To transfer to pages in other applications, you must use Response.Redirect.
That means you can't call the pges residing outside of your application domain. like http://bing.com http://google.com www.asp.net can't put inside your server.transfer method.
Satalaj
Configuration Error
by Satalaj
20. January 2010 11:14
How will you fix this error? read more.
Configuration Error
Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately.
Parser Error Message: Unrecognized attribute 'restartOnExternalChanges'.
Line 2: <configuration>
Line 3: <configSections>
Line 4: <section name="tConfigurationSection" type="someapp, someapp.Core" allowDefinition="MachineToApplication" restartOnExternalChanges="true"/>
Line 5: </configSections>
Line 6: <connectionStrings>
Source File: C:\Dot net Project\my.API\some.Web\web.config Line: 4
--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:1.1.4322.2300; ASP.NET Version:1.1.4322.2300
Fix 1. You don;t have installed the .net framework 2.0 on that machine.
Fix 2. You need to tell IIS to use ASP.net 2.0 envirnment and not ASp.net 1.1 to run your asp.net 2.0 web application.
Satalaj
net forms authentication
by Satalaj
8. January 2010 13:27
How quickly, I can set forms authentication to allow access for only one user!
In web.config authentication section you need to add below code
<authentication mode="Forms">
<forms defaultUrl="~/accounts/authuser.aspx" loginUrl="login.aspx" slidingExpiration="true" >
<credentials>
<user name="admin" password="password"></user>
</credentials>
</forms>
</authentication>
You can see here I have added credentials tag and added admin user their with password as password.
Now, I will let him login to system useing below code
if(!FormsAuthentication.Authenticate( txtUserName.Text , txtPassword.Text ))
{
FormsAuthentication.RedirectToLoginPage();
}
else
{
// FormsAuthentication.SetAuthCookie( txtUserName.Text, true);
FormsAuthentication.RedirectFromLoginPage(txtUserName.Text,true)
}
FormsAuthentication.Authonticate will validate the user against Forms credentials stored in web.config file.
If user is not valid, you can redirect him back to LoginPage
FormsAuthentication.RedirectToLoginPage();
FormsAuthentication.RedirectFromLoginPage(txtUserName.Text,true)
It will redirect the user from login page to authorised page and it will set authontication cookie at client side browser.
Satalaj
ms sql slow
by Satalaj
7. January 2010 09:40
If you found that your sql server is slow and almost not responding to the request made by web application and you also observed that
CPU and Memory utilization at normal level. Then.
Here is how you can investigate
Open SQL query analyzer and fire below query to know how many number of connections opened to which database?
SQL query
select db_name(dbid) as DataBaseName , count(dbid) as No_Of_Connections , loginame as LoginName from sys.sysprocesses
where dbid > 0
group by dbid,loginame
By frequently running this query. You observed that the number of connections opened is high then there exist bug in your application
which didn't closed the opened connections. Stop the web application who uses that database and start over, system would run first
and later it suffers slow response then stops responding. In this situation you need to fix your application and not to blame SQL server.
Satalaj
ConnectionStrings or appSettings ?
by Satalaj
5. January 2010 13:42
Though you have shifted to ASP.net 2.0 or later then why in your application you are still storing connection Strings in AppSettings ?
Here is sample code to access connectionStrings.
In web.config
<connectionStrings>
<add connectionString="servr=.;uid=sa;password=pass;database=mydb" name="XYZConnectionString" providerName="System.Data.SqlClient"/>
</connectionStrings>
In code behind you can access it like this.
string connection = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["XYZConnectionString"].ConnectionString;
Benifit of adding connectionString in connectionString section is, you will be able to configure your ASP.net membership provider , custom provider and third party components.
To know which connction string to use for what DB provider, you can refer www.connectionstrings.com
Note*: If you are using Class Library project in your ASP.net project and your library project needs to access connection string,
you need to add refrence of System.Configuration in your class library project.
Satalaj.
ASP.net
by Satalaj
4. January 2010 10:42
What is ASP.Net technology?
well, what I understood about it till today here it is
Asp.net is server side technology, which helps us to render client side output. Any language who targets microsoft .net framework can be used for
scripting the clicnet side out put. Remember, ASP.net is not a programming language. Its a technolgy where we can use languages like C#.Net, VB.Net etc for scripting.
All server side scripting languages like JSP, PHP, PERL etc generates out put (HTML / css ) which would be understood by Browsers running at client side.
|