ASP.NET 4.0 Hosting & ASP.NET 4.5 Hosting BLOG

BLOG about ASP.NET 4.5 Hosting, ASP.NET 4.0 Hosting and .NET 4.5 Framework and its Capabilities

ASP.NET 4.0 Hosting :: The Reasons Application Pool Recycle

clock October 31, 2011 07:43 by author Administrator

If your ASP.NET application crashes, has an unhandled exception, hangs or otherwise becomes brain-dead, it will cause the application pool to recycle. Sometimes your application pool recycles for no obvious reason. This is usually a configuration issue or it may be caused by your app performing file system operations in the application directory. Many times developers incorrectly set up SqlConnections so that they aren't properly closed and returned to the connection pool, and this can also cause your AppPool to recycle unexpectedly. When your AppPool recycles, you can kiss your InProc Sessions - and everything else -- goodbye.

Application pool settings

Looking at the properties for the application pool in IIS, you'll see the settings for "on purpose" recycling. In IIS6 these are:

- Recycle worker processes (in minutes)
- Recycle worker process (in requests)
- Recycle worker processes at the following times
- Maximum virtual memory
- Maximum used memory

If you're running IIS5 or the IIS5 isolation mode you must look at the processModel element of machine.config. The properties you should pay attention to are:

- memoryLimit
- requestLimit
- timeout

In IIS 7.o, you have Fixed Interval or Fixed # Requests, or Specific Times for recycling. Also, there are Memory -based Maximums for Virtual and Private Memory, and additional items for Configurable and Runtime recycling events including "unhealthy ISAPI".

When an application pool recycles, HTTP.SYS holds onto the client connection in kernel mode while the user mode worker process recycles. After the process recycle, HTTP.SYS transparently routes the new requests to the new worker process. Consequently, the client never "loses all connectivity" to the server; the TCP connection is not lost -- only state is lost (Application, Session, Cache, etc.).

memoryLimit
The default value of memoryLimit is 60. This value is only useful if you have a small amount memory on a 32 bit machine. "60" means 60% of total system memory. So if you have 1 GB of memory your IIS worker process will automatically restart once it hits memory usage of 600 MB.

requestLimit
This setting is "infinite" by default, but if it is set to 8000 for example, then ASP.NET will launch a new worker process once it has handled 8000 requests.

timeout
The default timeout is "infinite". This is where you set the lifetime of the worker process. Once the timeout is reached ASP.NET launches a new worker process, so setting this to "00:30:00" would recycle your application every 30 minutes.

Other properties
Another property within the processModel element that will cause your application pool to recycle is responseDeadlockInterval. If you have a deadlock then that's your main "fix" that you need to worry about -- changing the responseDeadlockInterval setting won't do much to resolve the problem. You need to deal with the deadlock itself, find out why it's happening, and change your code.

File Change Notification

ASP.NET 2.0 depends on File Change Notifications (FCN) to see if the application has been updated, and depending on the magnitude of change the application pool will recycle. If you or your application are adding and removing directories to the application folder, then you will be restarting your application pool every time.

Altering the following files also causes an immediate restart of the application pool:
- web.config
- machine.config
- global.asax
- Any file in the /bin directory or subfolders

Updating .aspx files, etc. causing a recompile eventually triggers a restart of the application pool also. There is a property of the compilation element under system.web called numRecompilesBeforeAppRestart. The default value is 20, meaning that after 20 recompiles the application pool will recycle.

Workaround for the sub-directory issue

If your application actually requires adding and removing sub-directories you can use linkd to create what's called a directory junction:

Create a directory you'd like to exclude from FCN, e.g. c:\inetpub\wwwroot\MyWebApp\MyFolder
Create a separate folder somewhere outside the wwwroot, e.g. c:\MyExcludedFolder
Use linkd to link the two: linkd c:\inetpub\wwwroot\MyWebApp\MyFolder c:\MyExcludedFolder
Now any changes made in the c:\inetpub\wwwroot\MyWebApp\MyFolder will now actually occur in c:\MyExcludedFolder so they will not be sensed by FCN.

Linkd only comes with the Windows XX Resource Kit, which is a pretty big download. But Mark Russinovitch has "junction" which could be even better:
http://www.microsoft.com/technet/sysinternals/FileAndDisk/Junction.mspx  

Is recycling the application pool good or bad?


If your app is coded properly, you shouldn't have to recycle the application pool. However, if you're dealing with a memory leak in your app and you need to buy time to fix it, then recycling the application pool could be a good idea. It's important to understand, though, that's not a "Fix" - it's just a "Band-Aid" until you find out what's causing the problem and fix your code. Unlike as with ASP.NET 1.1, in ASP.NET 2.0 if your app generates an unhandled exception the AppDomain will unload causing an application pool recycle. Consequently it is extremely important to ensure that your code is "best practices" and doesn't generate unhandled exceptions except under the most extreme and unusual conditions



ASP.NET Hosting :: How to send email via .NET Application

clock October 10, 2011 11:16 by author Administrator

 

.NET 2.0 has included System.Net.Mail code namespace for supporting email programming with .NET

Following is the code snippets for how to send mail from .NET application

 




ASP.NET Hosting :: Things to AVOID in JSON serialization

clock September 13, 2011 06:59 by author Administrator

If you’ve spent much time working with the .NET platform, ASP.NET’s simple, convention-based approach to exposing JSON endpoints seems just about too good to be true. After years of fiddling with manual settings in XML configuration files, it’s understandable to assume that working with JSON in ASP.NET would require a similar rigmarole, yet it does not.

Unfortunately, this unexpected ease-of-use isn’t obvious if you don’t already know about it, which has led some developers to build needlessly complicated solutions to problems that don’t actually exist. In this post, I want to point out a few ways not to approach JSON in ASP.NET and then show you a couple examples of leveraging the frame work to do it “right”.

A couple examples of what NOT to do

To show you exactly what I’m talking about, let’s start by looking at a few concrete examples of ways that you should not handle sending and receiving JSON in your ASP.NET services.

For all the examples, we’re going to be trying to send and/or receive instances of this Person class:

public class Person
{
  public string FirstName { get; set; }
  public string LastName { get; set; }
}

Once you progress beyond simple scalar types, sending objects (and collections of them) back and forth is a pretty logical next step, and that’s also the point where this manual serialization trouble seems to begin. So, working with this simple Person class should serve as a realistic example, without being overly complex.

Manual serialization, using JavaScriptSerializer

The most common variant of this mistake that I’ve seen is using JavaScriptSerializer to manually build a JSON string and then returning that string as the result of a service method. For example, if you didn’t know better, you might do this to return an instance of the Person class:

[ScriptService]
public class PersonService : WebService
{
  [WebMethod]
  public string GetDave()
  {
    Person dave = new Person();
 
    dave.FirstName = Dave;
    dave.LastName = Ward;
 
    JavaScriptSerializer jss = new JavaScriptSerializer();
 
    // Results in {"FirstName":"Dave","LastName":"Ward"}
    string json = jss.Serialize<Person>(dave);
 
    return json;
  }
}

This may look sensible enough on the surface. After all, the json variable does end up containing a nicely serialized JSON string, which seems to be what we want. However, you should not do this.

What actually happens

Part of the beauty of using ASP.NET’s JSON-enabled services is that you rarely have to think much about the translation between JSON on the client-side and .NET objects on the server-side. When requested with the proper incantations, ASP.NET automatically JSON serializes your service methods’ responses, even if their result is an object or collection of objects.

Unfortunately, that automatic translation also makes it easy to end up with doubly-serialized responses if you aren’t aware that ASP.NET is already handling the serialization for you, which is exactly what would happen in the preceding example. The end result is that the Person object is serialized twice before it gets back to the browser – once as part of the method’s imperative code and then a second time by convention.

In other words, it’s understandable to expect the previous code example would return this response:

{"FirstName":"Dave","LastName":"Ward"}

But, what it actually returns is this:

// All the quotes in the manually generated JSON must be escaped in 
//  the second pass, hence all the backslashes.
{"d":"{\"FirstName\":\"Dave\",\"LastName\":\"Ward\"}"}

What a mess. That’s probably not what you had in mind, is it?

Using DataContractJsonSerializer or Json.NET is no better

This may seem obvious, but I want to point out that using a different manual serialization tool, like WCF’s DataContractJsonSerializer or Json.NET, in place of JavaScriptSerializer above does not remedy the underlying problem. I only mention it because I’ve seen those variations of the mistake floating around too.

If anything, in the case of DataContractJsonSerializer, it’s even worse. DCJS’ handling of Dictionary collections and Enums makes life unnecessarily tedious at times, and the code to manually invoke it is even more verbose than that for JavaScriptSerializer.

The impact this mistake has on the client-side

If it weren’t bad enough to add extra computational overhead on the server-side, cruft up the response with escaping backslashes, and increase the size of the JSON payload over the wire, this mistake carries a penalty on the client-side too.

Most JavaScript frameworks automatically deserialize JSON responses, but (rightfully) only expect one level of JSON serialization. That means that the standard functionality provided by most libraries will only unwrap one level of the doubly serialized stack of JSON produced by the previous example.

So, even after the response comes back and your framework has deserialized it once, you’ll still need to deserialize it a second time to finally extract a usable JavaScript object if you’ve made the mistake of manually serializing. For example, this is code you might see to mitigate that in jQuery:

$.ajax({
  type: 'POST',
  dataType: 'json',
  contentType: 'application/json',
  url: 'PersonService.asmx/GetDave',
  data: '{}',
  success: function(response) {
    // At this point, response is a *string* containing the
    //  manually generated JSON, and must be deserialized again.
 
    var person;
 
    // This is a very common way of handling
    //  the second round of JSON deserialization:
    person = eval('(' + response + ')');
 
    // You'll also see this approach, which
    //  uses browser-native JSON handling:
    person = JSON.parse(response);
 
    // Using a framework's built-in helper 
    //  method is another common fix:
    person = $.parseJSON(person);
  }
});

Regardless of which approach is used, if you see code like this running after the framework has already processed a response, it’s a pretty good indication that something is wrong. Not only is this more complicated and verbose than it needs to be, but it adds additional overhead on the client-side for absolutely no valid reason.

Flipping the script (and the JSON)

Redundant JSON serialization on responses is definitely one of the most common variations of this problem I’ve seen, but the inverse of that mistake also seems to be an alluring pitfall. Far too often, I’ve seen service methods that accept a single JSON string as their input parameter and then manually parse several intended inputs from that.

Something like this to accept a Person object form the client-side and save it on the server-side, for example:

[ScriptService]
public class PersonService : WebService
{
  [WebMethod]
  public void SavePerson(string PersonToSave)
  {
    JavaScriptSerializer jss = new JavaScriptSerializer();
 
    Person p = jss.Deserialize<Person>(PersonToSave);
 
    p.Save();
  }
}

Just as ASP.NET automatically JSON serializes responses on its JSON-friendly services, it also expects that the input parameters will be in JSON format and automatically deserializes those on the way in. So, in reverse order, the approach above makes a mistake similar to the ones shown earlier.

To make this work, we’d need to pass in JSON that looks something like this, obfuscating the actually desired input parameters inside a single, doubly-serialized string parameter.

{"PersonToSave":"{\"FirstName\":\"Dave\",\"LastName\":\"Ward\"}"}

Through the convenience of JSON.stringify(), it’s not even terribly hard to stumble onto a process for cobbling that double-JSON structure together on the client-side and making this approach work. I strongly recommend against it though. Even if the double-JSON didn’t carry extra overhead in several aspects, having a single input parameter of type string on this method is misleading. A year from now, will anyone realize what type of parameter that method accepts without looking down into the manual parsing code? Probably not.

Doing it right

Briefly, here are what I suggest as better ways to handle passing our Person object in and out of ASP.NET services.

Returning an object

Returning a .NET object from ASP.NET services is incredibly easy. If you let go and just trust the service to handle JSON translation for you, “it just works”:

[ScriptService]
public class PersonService : WebService
{
  [WebMethod]
  public Person GetDave()
  {
    Person dave = new Person();
 
    dave.FirstName = Dave;
    dave.LastName = Ward;
 
    // So easy!
    return dave;
  }
}

As long as you call that service method through a ScriptManager’s service proxy or using the correct parameters when using a library like jQuery, ASP.NET will automatically serialize the Person object and return it as raw, unencumbered JSON.

Accepting an object from the client-side

Accepting a Person object from the client-side works identically, in reverse. ASP.NET does a great job of matching JSON-serialized request parameters to .NET’s types, collections, and even your own custom objects.

For example this is how you could accept a Person object, which would even then allow you to call that object’s custom methods:

[ScriptService]
public class PersonService : WebService
{
  [WebMethod]
  public void SavePerson(Person PersonToSave)
  {
    // No, really, that's it (assuming Person has a Save() method).
    PersonToSave.Save();
  }
}

 



.NET Hosting :: Working with GMail SMTP Server to send Email

clock January 27, 2011 05:28 by author Administrator

So you (or your client) moved your email to Google Apps and now you want to use Google SMTP server to send emails from ASP.NET ? It is pretty straight forward. Read on…

The System.Net contains the class SmtpClient which can be used to send the email from your ASP.NET page. Let us jump in the code (C#)

SmtpClient mailSender = new SmtpClient(“smtp.gmail.com”);

You can pass the smtp server location in the SmtpClient class’ constructor.

Next specify the port:
mailSender.Port = 587;

You can send the email using Google’s SMTP only by using authentication. So we will need to send the user name and password for the account from which you want to send the email (i.e your “From” email address):

System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(emailUserName, emailPassword);

where emailUserName is obviously your email address and emailPassword its password. Next use these credentials to send the email :

mailSender.Credentials = credentials ;

Next tell the SMTP server NOT to use the default credentials and to use SSL

mailSender.EnableSsl = true;
mailSender.UseDefaultCredentials = false;

Now send the email as you would normally in ASP.NET:

MailAddress toAddress = new MailAddress(“[email protected]”);
MailAddress fromAddress = new MailAddress(“[email protected]”);
MailMessage message= new MailMessage(fromAddress , toAddress );
message.Subject = “Email Subject”;
message.Body = “Email Message”;
mailSender .Send(message);

Of course as always recommend putting the smtp client (“smtp.gmail.com”) , port number. emailUserName and emailPassword in some kind of configuration (ASP.NET web.config file, app.config , SQL Server database etc)

This means you need to know the email user name and password of the account that the email is sent from. I have not found any other solution than physically creating this email account and using it. If anyone has found a better solution for this, please let me know

 



ASP.NET 4.0 & ASP.NET 4.5 Hosting

 

ASPHostCentral is a premier web hosting company where you will find low cost and reliable web hosting. We have supported the latest ASP.NET 4.5 hosting and ASP.NET MVC 4 hosting. We have supported the latest SQL Server 2012 Hosting and Windows Server 2012 Hosting too!

 

Calendar

<<  March 2024  >>
MoTuWeThFrSaSu
26272829123
45678910
11121314151617
18192021222324
25262728293031
1234567

View posts in large calendar

Sign in