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 4.0 Hosting :: SOLVING an error message: “Unrecognized attribute targetFramework”

clock September 22, 2011 07:32 by author Administrator

I recently upgraded from Visual Web Developer 2008 to Visual Web Developer 2010 and have run into an issue, I started seeing a configuration error. In two cases I had been working on web applications in Visual Web developer 2010.


Case 1 appeared after I had opened an existing application and when prompted, do I want to configure the site for use with ASP.NET 4.0, I must have said yes.

Case 2 came when I created a new application and my system is setup to use Framework ASP.NET 4.0

In both situations I got the following error <compilation debug="true" targetFramework="4.0" /> pointing to my web.config file. I like working in Visual Web Developer 2010, but my hosting server is not yet setup for .Net Framework 4.0, so I needed to find out how to down-grade from 4.0 to 3.5 framework.



The following is what I did to change the target Framework from ASP.NET 4.0 to ASP.NET 3.5.

1) Ensure IIS and the ASP.NET properties are configured for Framework 2.0. Note: Framework 3.5 will not show up in the list of installed options due to the fact that framework 3.5 is an extension of 2.0 and not a stand alone release


 2) Configure you web application to use target Framework 4.0 by right clicking your website in the solution explorer >> Property Pages >> Build >> Change "Target Framework" to .NET Framework 3.5.

T



ASP.NET 4 Hosting :: The Difference between Response.Redirect and Response.RedirectPermanent

clock September 20, 2011 07:46 by author Administrator

In ASP.NET 4.0 there are new features that enable developer to make SEO friendly websites very easily. And if you google out, you will find plenty of article which explain this feature. But I am more interested in Response.RedirectPermanent. As the name suggest it is used to redirect permanently moved resources to new location. And most of all articles on the net just explain this with some example. But how can we visualize that whether resource is redirected permanently or not. So here is the answer for that. I have used FireBug to examine the same


Whenever we redirect with Response.Redirect, we can see following activity in FireBug console



As we can see that page which issues Response.Redirect its response status code 302(Found) which means requested url(default.aspx) is found but it is temporarily moved to about.aspx. More information on HTTP status code can be found here.

Now whenever we redirect with Response.RedirectPermanent, we can see following activity in FireBug console



As we can see that page which issues Response.RedirectPermanent its response status code 301(Moved Permanently) which means requested url(default.aspx) is moved Permanently to about.aspx. 301 status code is used by search engine crawler to update search index to new moved information.

I hope information provided here would be more helpful to distinguish between Response.Redirect and Response.RedirectPermanent



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();
  }
}

 



ASP.NET 4 Hosting :: Main Differences of Custom Control and User Control

clock August 23, 2011 07:57 by author Administrator

If you are thinking to build a control and apply the same to more than one place, you can take two kinds of approaches. Either you can create an User control inheriting from UserControl and adding a XAML for your control or use CustomControl to write yourself. Either one of them you choose they have their own pros and cons. Here in this post I will define what are the differences between the two approaches so that you can choose either one of them based on your requirement.

Before we start lets define both the terms:

UserControl : A usercontrolis a reusable chunk of user interface that is built up as a composition of other UIElement in the same style the main UI is built. In other words, a user control is just like a normal application block that can be used as Reusable component, and can be defined both using XAML and code together. It gives you a fresh UI canvas where you can define your custom reusable component that can be used widely in the application. In WPF, UserControl acts as a base class for any reusable component, but if you are looking for inheriting some other base, you can look into this.

Limitation of UserControl :

1. Appearance of an UserControl cannot be changed using a Template. Even though it has a property for Template, but it is of no use, as you cannot change the appearance of UserControl through this property.

2. UserControl is derived from ContentControl, thus if you change the Content of an usercontrol the entire UI will be replaced with that content.

3. As UserControl has both XAML and code behind. But as XAML can be used only once for entire inheritance hierarchy, you cannot use XAML for any class that inherits from your userControl. This is actually because Application.LoadComponent loads up the XAML once and is incompatible with inheritance. Thus when loading the XAML, the IComponentConnector interface is used to hook events and fields from XAML, hence you cannot replace XAML from your base class.

Custom Control: A customcontrol is a User interface element that has a distinct behaviour. A CustomControl is just a class that has one default appearance defined in Generic.xaml style which can be replaced by Template and Style at runtime but the behaviour you define for the control remains the same. So choose a CustomControl only when you need a certain kind of behaviour which is not there with the existing controls you have.

Note: Please don’t create a new custom control just to change the UI appearance as you can do this with any control available using custom Template

Limitation :

1. You have to define each behaviour for your control using Code. So it is hard way of achieving a behaviour.

2. Generic style is needed to be defined with your custom control to ensure that your control has a default look and feel.

Hence, based on your own requirement, if you are looking for a new behaviour which is different from existing userinterfaces available with WPF, you go for a Custom Control. A customControl can be styled and templated and best suited for a situation when you are building a Control Library.

On the contrary, a UserControl gives you an easy way to define reusable chunk of XAML which can be reused widely in your application and when you don’t need to use it as a Control Library.

I hope this gives you a brief idea on the differences between the two.

Happy Coding.



ASP.NET 4 Hosting :: How to Register HTTP Module at Runtime without Editing web.config?

clock July 4, 2011 08:35 by author Administrator

The ASP.NET pipeline allows HTTP modules to be plugged-in to a request and intercept or modify each individual request. Modules can be used for processes like caching, authentication etc. However a basic requirement for an HTTP module to function, is that it must be registered in your config file. This leads to editing the Web.Config whenever you have to add/remove modules. I hate fudging with my config file too often!

Not known to many developers, ASP.NET 4.0 provides the PreApplicationStartMethodAttribute which allows you to run code even before any app_start event gets fired or any dynamic compilation occurs (App_code).

So how do I register an HTTP Module at Runtime using PreApplicationStartMethodAttribute and DynamicModuleUtility.RegisterModule?

It’s a simple 3 process step!

Step 1: Implement your Module. In the code shown below, we are implementing the IModule interface and subscribing to the BeginRequest event of the HttpApplication object. The OnBeginRequest method hooks up to the BeginRequest event.



Step 2: Register the Module dynamically using the DynamicModuleUtility.RegisterModule method. Write this code in the same class you created above



Step 3: The final step is to use the PreApplicationStartMethod attribute. Just add this  attribute at the assembly level in the AssemblyInfo file or as shown below:

There you go! You have just registered an HTTP module into the ASP.NET pipeline without making any changes to web.config file.

 

 

 

 



ASP.NET 4.0 Hosting :: Questions on .NET 4 New GAC Locations/GacUtil

clock March 25, 2011 09:22 by author Administrator

This is what I know, let me know if you know otherwise.  There are now 2 distinct GAC locations that you have to manage as of the .NET 4 Framework release.

The GAC was split into two, one for each CLR (2.0, 3.5 AND 4.0).  The CLR version used for both .NET Framework 2.0 and .NET Framework 3.5 is CLR 2.0. To avoid issues between CLR 2.0 and CLR 4.0 , the GAC is now split into private GAC’s for each runtime.  The main change is that CLR v2.0 applications now cannot see CLR v4.0 assemblies in the GAC.

In previous .NET versions, when I installed a .NET assembly into the GAC (using gacutil.exe or even drag and drop to the c:\windows\assembly directory), I could find it in the ‘C:\Windows\assembly’ path.

With .NET 4.0, GAC is now located in the 'C:\Windows\Microsoft.NET\assembly’ path.

In order to install a dll to the .NET 4 GAC it is necessary to use the gacutil found C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\GacUtil.exe  In addition, you can no longer use the drag n' drop (in reality the drag n' drop really executed the gacutil via a windows explorer extension).

After you use the gacutil.exe -i {path to dll} you can view that it is indeed in the gac via gacutil -l (which will list all dlls in the gac).  I used this command and piped the results to a text file via > out.txt which made it easier to find the recently added component.

I was not able to see my gac object in the directory for .net 4 (i.e. c:\windows\microsoft.net\assembly path).  I am not sure why just yet.  Ideas?

At this point, the object is in the local gac however if you are using vs.net 2010 it will still not show up in the list of references. To get the component to show up in the VS.NET list of references can add a registry entry to HKLM\SOFTWARE\WOW6432Node\Microsoft\.NETFramework\v4.0.30319\AssemblyFoldersEx  At this point, the component is in the local GAC and is in the list of references to be used by vs.net.

Note, I did find that if I just added the path to the registry without adding it to the gac it was available to vs.net.  So, because the component is listed via vs.net add references it does not necessarily mean it is in the gac.

What still confuses me is that I am still unable to view my recently added component in the .NET 4 directories above.  Ideas?



ASP.NET 4.0 Hosting :: Working with Error Logging and Error Handling in ASP.NET 4.0

clock October 22, 2010 10:01 by author Administrator

Logging exceptions is important for controlling your application when they are deployed. You can opt for using one of the available libraries on the market or your own way of storing this information. Both sides have their own pros and cons. Using a third-party code lets you implement the task in less time.

Writing your own code is probably a win situation if you do not want to include reference to gigantic libraries in order to only use a small part of their features. Handling errors the right way is crucial from the security point of view: the less your attacker sees, the more secure your application. In this article, you will learn how to protect your error from others and, at the same time, log it for tracking purposes

Error logging with Enterprise Library and log4Net

If you decide to use custom libraries to handle logs, you will probably choose between Microsoft Enterprise Library and Apache Foundation log4net. Microsoft Enterprise Library, at the time of writing, is available in version 4.1 at http://msdn.microsoft.com/en-us/library/cc467894.aspx. This library is free and contains a lot of functionalities; logging is only a small part of it. It is diffused among enterprise applications because even though it is not part of the .NET Framework BCL, developers tend to trust external class libraries coming from Microsoft.log4net is a project from Apache Software Foundation and it is available under the Apache License at http://logging.apache.org/log4net/index.html.   

Both libraries provide great flexibility; you can log information (and errors) to a file, a database, a message queue, or the event log or just generate an e-mail.

If you are trying to choose one over the other, you have to consider these points:

- Enterprise Library has a GUI tool to configure its Logging Application Block
- log4net supports hierarchical log maintenance

The choice is based mainly on the features you need to address because, from the performance point of view, they are very similar.

Enterprise Library is often considered because of its capabilities so, if you are already using it in your project (for example, because of the Cache Application Block), you may find it very similar, and using it is the right move because you already have a dependency on the main library

On the other hand, log4net is preferred by developers searching.

only for a simple and very complete library to perform this task and nothing more

If you prefer to write code, however, and your logging needs are only related to exceptions, you'll probably find easier to just handle and store this information with your custom code


Intercepting and handling errors with a custom module


Exposing errors to end users is not a good idea from both the usability and the security point of view. Error handling implemented the right way will help the administrators to inspect the complete error and provide a courtesy page to the users.

Problem


We want to avoid full error disclosure to normal users and display the full error to the administrators. This will preserve security and help the administrators to inspect errors without accessing the error logging tool while they’re running the page causing the error. We want to provide also an entry point to add more powerful exception logging capabilities in the future

Solution


ASP.NET gives you control over errors, letting you choose from among three options:

- Always show the errors
- Never show the errors.
- Show the error only when the request is coming from the same machine running the application

The following code comes from a typical web.config and lists the options:



These settings are flexible enough to cover your needs while developing the application; the reality is that, when you put your application in production, you will probably not make requests from the same machine running the page and you need to be the only one accessing error details


It is very important to not show sensitive information to users: errors are considered very dangerous. HttpApplication has a useful Error event, used to intercept exceptions not blocked at a higher level, such as in a try/catch block. This event can be handled to combine authorization and authentication from ASP.NET so you can show the error only to a specific group of people, thanks to Roles API available on ASP.NET

The code is really simple: you just have to handle the event, verify user permissions given the current roles, and then show a personalized error page or just let ASP.NET do the magic, using the values specified in web.config

We need to configure web.config to register our module as in listing 1

Listing 1: The custom authorization module to modify the response flow



When an error occurs, the exception is handled by our event handler, and we will display an error message similar to the one in figure 1

Figure 1: Using our custom error system we can add further information to the error page or simply decide to show the error to given clients.



To implement such a personalized view, we need to write a custom HttpModule like the one in listing 2



This code can be easily adapted to integrate further logging instrumentations, like form variables or application status. To register the module, you have to place this configuration in your web.config:

Error event handler is the right place to add your code. You can use MailMessage class from System.Net.Mail to compose a notification email
and send it to your address. If you want to use something that’s readily available, take a look at Health Monitoring in the MSDN documentation.

It is important to remark that TrySkipIisCustomErrors property from HttpResponse class is used to modify the default behavior of IIS 7.x when dealing with custom errors. By default, in fact, IIS 7 will bypass the local error handling and, instead, use the configuration applied in the system.webServer section. By setting this property, you can control IIS 7.x behavior too; the behavior of IIS 6.0 is not affected by this change

Discussion

HttpModules enable global event handling and are very useful in such a situation. This approach is very simple, centralized, and open to further improvements. It is also showing you how easy it is to tweak ASP.NET behavior and to avoid security concerns: the less an attacker sees the better it is for your application security. Error logging can be done with many different approaches. What we showed in these examples is a starting point. To meet your more complex needs, you can use the libraries we mentioned

Summary

Remember that ASP.NET is built with flexibility. This characteristic reflects how many incredible things you can do using extreme techniques. ASP.NET offers the right entry points to add your own custom mechanisms to implement simple things like logging errors. ASP.NET is so powerful that you can literally do anything you may need; you just have to write code and unleash your imagination!



ASP.NET 4.0 Hosting :: ASP.NET GridView UI Tips and Tricks by using jQuery

clock September 27, 2010 14:52 by author Administrator

This article demonstrates how to create simple UI effects in an ASP.NET GridView control using jQuery. These tips have been tested in IE 7 and Firefox 3.

Set up an ASP.NET GridView as you usually do, binding it to a datasource. For demonstration purposes, here’s some sample markup where we are using the Northwind database and a GridView bound to the SQLDataSource to pull data from the database.

<form id="form1" runat="server">

<div>

    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"

        SelectCommand="SELECT [CustomerID], [CompanyName], [ContactName], [Address], [City] FROM [Customers]">

    </asp:SqlDataSource>   

    <br />          

    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="CustomerID"

        DataSourceID="SqlDataSource1" AllowPaging="False" AllowSorting="True" >

        <Columns>                          

            <asp:BoundField DataField="CustomerID" HeaderText="CustomerID" ReadOnly="True" SortExpression="CustomerID" />

            <asp:BoundField DataField="CompanyName" HeaderText="CompanyName" SortExpression="CompanyName" />

            <asp:BoundField DataField="ContactName" HeaderText="ContactName" SortExpression="ContactName" />

            <asp:BoundField DataField="Address" HeaderText="Address" SortExpression="Address" />

            <asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />

        </Columns>

    </asp:GridView>

</div>

</form>

The <connectionStrings> element in the web.config will look similar to the following:

      <connectionStrings>

            <add name="NorthwindConnectionString" connectionString="Data Source=(local);Initial Catalog=Northwind;Integrated Security=True" providerName="System.Data.SqlClient"/>

      </connectionStrings>

Note: In most of the tips shown here, we are using a complex jQuery row ‘filter’ suggested by Karl Swedberg to a user in a jQuery forum. This filter is required due to the fact that a GridView does not render (accessibility tags) a <thead> and a <tfoot> by default. For the header, the GridView generates <th>’s inside <tr>. Similarly for the footer, the GridView generates a <table> inside a <tr> and so on. Hence it is required to use additional filters to exclude header and footer rows while adding UI effects on the GridView. These tips have been tried out on a GridView where paging is not enabled. When the paging is enabled, the pager however gets highlighted. We are still working on a solution to prevent the UI effects from being applied on the pager. We will update this article, once we find a solution. If you have a solution that works cross browser, please share it with us.

The link to download the code for all these samples can be found at the end of this article. Let’s see some tips.


1. Highlight an ASP.NET GridView row by clicking on it     

This tip lets you highlight a row when you click anywhere on the row. Clicking back on a highlighted row, removes the highlight.

<head id="Head1" runat="server">

<title>Highlight Row on Click</title>

<script src="Scripts/jquery-1.3.min.js" type="text/javascript"></script>

<script type="text/javascript">

    $(document).ready(function() {

        $("tr").filter(function() {

            return $('td', this).length && !$('table', this).length

        }).click(function() {

            $(this).toggleClass('currRow');

        });

    });

</script>

<style type="text/css">

    .currRow

    {

        background-color:Gray;

        cursor:pointer;

    }   

</style>

</head>

After applying the filter on the rows (to prevent the user from highlighting the Header and Footer row), we use the toggleClass to highlight/remove highlight on the row.

Output:

2. Remove/Hide the Highlighted rows of an ASP.NET GridView

If you want to remove/hide the highlighted rows from the GridView, then here’s how to do so. We have added a HTML button control (Button1) to the form

<input id="Button1" type="button" value="Remove Rows" />

The jQuery is as shown below:

<head id="Head1" runat="server">

    <title>Hide Highlighted Rows>/title>

    <script src="Scripts/jquery-1.3.min.js" type="text/javascript"></script>

    <script type="text/javascript">

        $(document).ready(function() {

            $("tr").filter(function() {

                return $('td', this).length && !$('table', this).length

            }).click(function() {

                $(this).toggleClass('currRow');

            });

            $("#Button1").click(function() {               

                var hideRows = $("tr").hasClass("currRow");

                if (hideRows == true) {                   

                    $("tr.currRow").remove();

                }

            });

        });

    </script>

    <style type="text/css">

        .currRow

        {

            background-color:Gray;

            cursor:pointer;

        }   

    </style>

</head>

Here the user first highlights the rows and then clicks on the ‘Remove Rows’ button to remove the highlighted rows

3. Remove/Hide ASP.NET GridView Rows on Mouse Click     

In our previous sample, we were following a two step process of first highlighting multiple rows and then removing them. Let’s say if we want to remove the rows as the user clicks on them, then follow this approach:

    <script type="text/javascript">

        $(document).ready(function() {

                $("tr").filter(function() {

                    return $('td', this).length && !$('table', this).length

                }).click(function() {

                    $(this).remove();

                });

        });       

    </script>

4. Highlight an ASP.NET GridView row on Mouse Hover     

In case you do not want to define a separate style for the row and want to highlight a row on mouse over (instead of the click), follow this tip:

<head id="Head1" runat="server">

    <title>Highlight Row on Hover</title>

    <script src="Scripts/jquery-1.3.min.js" type="text/javascript"></script>

    <script type="text/javascript">

        $(document).ready(function() {

            $("tr").filter(function() {

                return $('td', this).length && !$('table', this).length

            }).css({ background: "ffffff" }).hover(

                function() { $(this).css({ background: "#C1DAD7" }); },

                function() { $(this).css({ background: "#ffffff" }); }

                );

        });

    </script>

</head>

Output:

5. Drag and Drop Rows of an ASP.NET GridView

 

 

 

 

This tip comes very handy when you are presenting a set of data in a GridView and want to rearrange rows at runtime. We are using the Table Drag and Drop Plugin for this example and it’s as simple as calling tableDnD() on the table. This plugin enables drag/drop on a table.

<head runat="server">

    <title>Drag Drop Rows</title>

    <script src="Scripts/jquery-1.3.min.js" type="text/javascript"></script>

    <script src="Scripts/jquery.tablednd_0_5.js" type="text/javascript"></script>

    <script type="text/javascript">

        $(document).ready(function() {

            $("#GridView1").tableDnD();

        });

</script>

</head>

Output:

Before Drag

After Drop - dragging row with Customer ID ‘ANATR’ below ‘BLONP’

That’s it for now. We saw some UI tips that can be applied to an ASP.NET GridView using jQuery. Stay tuned to see some more in the forthcoming articles. We are also planning to write an article to store these UI changes when the user paginates through the Grid or a postback occurs

 

 

 

 



ASP.NET MVC Hosting :: ASP.NET MVC Model Binder for Repositories

clock September 21, 2010 08:11 by author Administrator

How do you take the values posted by an HTML form and turn them into a populated domain entity? One popular technique is to bind the POST values to a view-model and then map the view-model values to an entity. Since your action method’s argument is the view-model, it allows you to decide in the controller code if the view-model is a new entity or an existing one that should be retrieved from the database. If the view-model represents a new entity you can directly create the entity from the view-model values and then call your repository in order to save it.  In the update case, you can directly call your repository to get a specific entity and then update the entity from the values in the view-model

However, this method is somewhat tedious for simple cases. Is a view-model always necessary? Wouldn’t it be simpler to have a model binder that simply created the entity for you directly? Here’s our attempt at such a binder:

public class EntityModelBinder : DefaultModelBinder, IAcceptsAttribute
{   
readonly IRepositoryResolver repositoryResolver;
    EntityBindAttribute declaringAttribute;

    public EntityModelBinder(IRepositoryResolver repositoryResolver)
    {
        this.repositoryResolver = repositoryResolver;
    }

    protected override object CreateModel(
        ControllerContext controllerContext,
        ModelBindingContext bindingContext,
        Type modelType)
    {
        if (modelType.IsEntity() && FetchFromRepository)
        {
            var id = GetIdFromValueProvider(bindingContext.ValueProvider, modelType);
            if (id != 0)
            {
                var repository = repositoryResolver.GetRepository(modelType);
                object entity;
                try
                {
                    entity = repository.GetById(id);
                }
                finally
                {
                    repositoryResolver.Release(repository);
                }
                return entity;
            }
        }

        // Fall back to default model creation if the target is not an existing entity
        return base.CreateModel(controllerContext, bindingContext,
odelType);
    }

    private static int GetIdFromValueProvider(IValueProvider valueProvider, Type modelType)
    {
        var result = valueProvider.GetValue(modelType.GetPrimaryKey().Name);
        return (result == null) ? 0 : (int)result.ConvertTo(typeof(Int32));
    }

    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var model = base.BindModel(controllerContext, bindingContext);
        ValidateEntity(bindingContext, controllerContext, model);
        return model;
    }

    protected virtual void ValidateEntity(
        ModelBindingContext bindingContext,
        ControllerContext controllerContext,
        object entity)
    {
        // override to provide additional validation.
    }

    private bool FetchFromRepository
    {
        get
        {
            // by default we always fetch any model that implements IEntity
            return declaringAttribute == null ? true :
declaringAttribute.Fetch;
        }
    }

    public virtual void Accept(Attribute attribute)
    {
        declaringAttribute = (EntityBindAttribute)attribute;   
    }

    // For unit tests

    public void SetModelBinderDictionary(ModelBinderDictionary modelBinderDictionary)
    {
        Binders = modelBinderDictionary;
    }
}


We have simply inherited ASP.NET MVC’s DefaultModelBinder and overriden the CreateModel method. This allows us to check if the type being bound is one of our entities and then grabs its repository and gets it from the database if it is.

Now, We are most definitely not doing correct Domain Driven Development here despite our use of terms like ‘entity’ and ‘repository’. It’s generally frowned on to have table-row like settable properties and generic repositories. If you want to do DDD, you are much better off only binding view-models to your views

 



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

<<  April 2024  >>
MoTuWeThFrSaSu
25262728293031
1234567
891011121314
15161718192021
22232425262728
293012345

View posts in large calendar

Sign in