ASP.NET 4.5 and ASP.NET Core 1 Hosting BLOG

Tutorial and Articles about ASP.NET 4.0 and the latest ASP.NET 4.5 Hosting

ASP.NET 4.5 Hosting - Security Improvement in ASP.NEt 4.5

clock March 18, 2013 08:21 by author andy_yo

The .NET 4.5 framework was released a couple of months ago and it included several improvements in the security area. To benefit from these improvements you need to do a few changes to you application's configuration file.
There are some important improvement in ASP.NET 4.5:

  • There are changes to the ASP.NET request validation, it now supports deferred (lazy) validation, as well as giving the option to fetch data unvalidated.
  • The AntiXSS library is included in the framework.
  • There are significant Cryptographic Improvements in ASP.NET 4.5.
  • Windows Identity Foundation is now included in the framework, referred to as WIF 4.5.

About ASPHostPortal.com

ASPHostPortal.com is Microsoft No #1 Recommended Windows and ASP.NET Spotlight Hosting Partner in United States. Microsoft presents this award to ASPHostPortal.com for ability to support the latest Microsoft and ASP.NET technology, such as: WebMatrix, WebDeploy, Visual Studio 2012, ASP.NET 4.5, ASP.NET MVC 4.0, Silverlight 5 and Visual Studio Lightswitch. Click here for more information

To take advantage of these new bits you'll have to do a bit of configuration, we'll get into that right away:

Switching to 4.5
While retargeting a couple of MVC applications to the new framework version, I learned that it's not enough to install the 4.5 framework and change the "Target framework" accordingly. You'll find that a comment appears in the web.config file:
<!--
    For a description of web.config changes for .NET 4.5 see http://go.microsoft.com/fwlink/?LinkId=235367.       
    The following attributes can be set on the <httpRuntime> tag.      
     <system.Web>
        <httpRuntime targetFramework="4.5" />
     </system.Web>

-->
It's important that you set the targetFramework in your configuration file, else your application will run in "4.0" mode.

Enabling AntiXss
You'd want to set the AntiXss library as the default encoder — that can easily be done in the httpRuntime configuration element:

<httpRuntime targetFramework="4.5" encoderType="System.Web.Security.AntiXss.AntiXssEncoder,System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />

Note that there can be side effects to this, as AntiXSS takes a white list approach to encoding. That means that there may be characters that weren't encoded before, that will be encoded by AntiXSS.

Request validation
Lazy validation was introduced in ASP.NET 4.5, I just did some testing on it and it seems that lazy validation is the enabled regardless of how you set the "requestValidationMode", after you've installed the 4.5 framework. However, if you need access to any request parameters unvalidated, you'll need to set the validation mode to "4.5", as such:
<httpRuntime targetFramework="4.5" requestValidationMode="4.5" />
This will give you access to the unvalidated collections of parameters, e.g.:

Request.Unvalidated.QueryString["lastName"];
This is a much better approach than disabling request validation altogether. But use it with care, as always you should throroughly validate the input.

WIF 4.5
WIF is now part of the framework — that meant some breaking changes. It shouldn't take to much time to upgrade though,  particularly if you're concerned with RP's. There's a great article on MSDN with Guidelines for Migrating an Application Built Using WIF 3.5 to WIF 4.5.
There's two apparent changes I'd like to point out. First, you no longer need to set the "requestValidationMode" to "2.0" to cope with the request validation exceptions on the SignInResponseMessage's posted from an STS. WIF 4.5 plays nicely with the 4.5 request validation. Second, WIF now includes a MachineKeySessionSecurityTokenHandler which encrypts and MAC's WIF cookies based on the machine key. You'll find everything you need to set it up in: WIF and Web Farms.

 

 



ASP.NET 4 Hosting - ASPHostPortal :: Deploying ASP.NET Web Application on server

clock April 19, 2012 11:19 by author Jervis

Hello, in this article i have tried to explain, how a web application is deployed on to web server. We can deploy ASP.NET Application in 3 different ways

1. xCopy Deployment

2. Precompiled Deployment
3. Web Setup Project

The choice of best deployment alternative depends upon particular need of each application. Xcopy deployment is the most easiest, and it is often used during development to create copies of an application n different servers for testing purpose. For small application xcopy deployment may be the best choice.


Precompiled deployment has several advantages over XCopy deployment. Eg. Precompiled deployment is always gives better performance for the first users of the site at the same time it is more secure as we don’t need to copy our source code files on to server. If our application deployed on one or few servers then precompiled deployment is usually best choice.


When we are going to deploy our application on number of servers then creating a setup program is a very handy tool. Although creating this setup program is much tedious and involves considerable working, the deployment from this setup program becomes very easier.


xCopy Deployment

To manually copy the files of an asp.net web site to a server. We can use the xcopy command from a command prompt. Then we can use IIS’s (Internet Information Serve management console t o create a virtual directory that’s mapped to the directory that you copied the web site to.


It is easier to create a batch file for the xcopy command. Then after we can run that batch file at given time we make changes to the application and want to deploy the updated code.


We can also perform xcopy deployment from visual studio by using copy website command.

To perform xcopy we use copy web site command. This command lets us to copy website to file system, local IIS, FTP or remote IIS website. At the same time we can copy all or selected files.

How to use this command


1. In visual studio open the website to be deployed and choose the website copy web site command.

2. Then click the connect button to display an open website dialog box that lets to choose the destination to copy the web site to.
3. Click the arrow buttons to copy the files from the source web site to remote web site.

Publish Web Site

The publish web site command lets us to precompile an asp.net application and copy the precompiled assemblies to a target server. This is the easiest way to use the precompiled deployment feature.


1. Deploys precompiled assemblies to the specific server
2. Lets us to deploy the web site without source code files
3. It is done either from publish web site command or from command prompt using the aspnet_compiler command

Advantages

1.Avoids delays caused by compiling web pages when they are first accessed by a user.
2. Finds compile errors before the site is deployed.
3. Can copy just executable files and not the source files to the server.

The build -> publish web site command compiles all of the files makes up an asp.net application, and then deploys the compiled assemblies to the location we specify.

If we check allow precompiled site to be updatable box, the source files are deployed along with the executable files. If we uncheck then source code files aren’t deployed.


The syntax of aspnet_compiler command
The aspnet_compiler command is located in the asp.net framework directory,

c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727

aspnet_compiler –v virtual-directory [-u] [-d] [-f] [target-directory]

where

· -v name of virtual directory of existing web site

·  -u precompiled website will be updated

·  -d debug information is included in compiled assemblies

·  -f overwrite target directory if exist

Eg.
Precomplies existing website
Aspnet_compiler –v test d:\test

In same place

Aspnet_complier –v test

With debugging information

Aspnet_compiler –v test –u –d d:\test

If we specify target directory the precompiled web site is stored in the specified directory else the website is precompiled in place


Setup Deployment


1. It uses a web setup project to build a windows setup program used to deploy website onto server.

2. Useful for deployment on multiple servers.
3. Can be used to deploy precompiled assemblies and can be configured to include or omit the source code.
4. The installed application can be removed by using add or remove programs dialog box from control panel

How to create a setup


Choose the file -> add -> new project command to display the add new project dialog box. Then, choose setup and deployment. Select web setup project as template, enter a name for websetup project click ok.
 

In the solution explorer right click the web setup project and choose the add-> project output command to display the add project output group dialog box, then click ok to add the content files from you website to the web setup project


Use the buttons that are displayed at the top of the solution explorer when web setup project is selected to access setup editors that lets us to customize various aspects of the web setup project.

 
Visual studio creates files named setup.exe and setup.msi. setup.exe is the file we will run to install the application and setup.msi contains all of the files to be installed.


The setup.exe and setup.msi files are stored in the web setup project’s debug or release folder.

Reasons why you must trust ASPHostPortal.com

Every provider will tell you how they treat their support, uptime, expertise, guarantees, etc., are. Take a close look. What they’re really offering you is nothing close to what ASPHostPortal does. You will be treated with respect and provided the courtesy and service you would expect from a world-class web hosting business.

You’ll have highly trained, skilled professional technical support people ready, willing, and wanting to help you 24 hours a day. Your web hosting account servers are monitored from three monitoring points, with two alert points, every minute, 24 hours a day, 7 days a week, 365 days a year. The followings are the list of other added- benefits you can find when hosting with us:

- DELL Hardware
Dell hardware is engineered to keep critical enterprise applications running around the clock with clustered solutions fully tested and certified by Dell and other leading operating system and application providers.
- Recovery Systems
Recovery becomes easy and seamless with our fully managed backup services. We monitor your server to ensure your data is properly backed up and recoverable so when the time comes, you can easily repair or recover your data.

- Control Panel
We provide one of the most comprehensive customer control panels available. Providing maximum control and ease of use, our Control Panel serves as the central management point for your ASPHostPortal account. You’ll use a flexible, powerful hosting control panel that will give you direct control over your web hosting account. Our control panel and systems configuration is fully automated and this means your settings are configured automatically and instantly.

- Excellent Expertise in Technology
The reason we can provide you with a great amount of power, flexibility, and simplicity at such a discounted price is due to incredible efficiencies within our business. We have not just been providing hosting for many clients for years, we have also been researching, developing, and innovating every aspect of our operations, systems, procedures, strategy, management, and teams. Our operations are based on a continual improvement program where we review thousands of systems, operational and management metrics in real-time, to fine-tune every aspect of our operation and activities. We continually train and retrain all people in our teams. We provide all people in our teams with the time, space, and inspiration to research, understand, and explore the Internet in search of greater knowledge. We do this while providing you with the best hosting services for the lowest possible price.

- Data Center

ASPHostPortal modular Tier-3 data center was specifically designed to be a world-class web hosting facility totally dedicated to uncompromised performance and security
- Monitoring Services
From the moment your server is connected to our network it is monitored for connectivity, disk, memory and CPU utilization – as well as hardware failures. Our engineers are alerted to potential issues before they become critical.

- Network
ASPHostPortal has architected its network like no other hosting company. Every facet of our network infrastructure scales to gigabit speeds with no single point of failure.

- Security
Network security and the security of your server are ASPHostPortal’s top priorities. Our security team is constantly monitoring the entire network for unusual or suspicious behavior so that when it is detected we can address the issue before our network or your server is affected.

- Support Services
Engineers staff our data center 24 hours a day, 7 days a week, 365 days a year to manage the network infrastructure and oversee top-of-the-line servers that host our clients’ critical sites and services.

 

 



ASP.NET 4 Hosting - ASPHostPortal :: Few Important Tips that You Should Know While Using ASP.NET Session

clock March 6, 2012 07:33 by author Jervis

While working with ASP.NET web application you must be familiar with one of most important state management technique “Session”.

ASP.NET Session State is on by default, hence you are paying for memory even if you don’t use it. There are several ways to optimize it.


Tip #1
: Not using Session State at all ? Then turn it off completely in web.config



Tip #2
: Session is only required for few pages not all over the application



then enable it for a specific page where you required the session




Tip #3
: If you are using Session for Reading Purpose, use Session State as “ReadOnly”

If you are a beginner, you must be wondering what is EnableSessionState=”Readonly” . Well, if you look at your web application, not all the pages using Session or some of the pages is using session data for reading purpose. If there is no write operation happaning on session, then it’s always better to use session State is “
ReadOnly



The session request pass through different httpModule with in HTTPPipeline. Know more details on how session state ReadOnly works , please read the article
Read Only Session State in ASP.NET.

You can also set ReadOnly SessionState in web.config as well




Tip #4
: Programmatically Change Session State Behavior when required (ASP.NET 4.0)

We can enable or disabled session state either in web.config or using @Page directive’s EnableSessionState attributes. But there was no provision to change the session state at runtime till date in ASP.NET. But using ASP.NET 4.0, we can change the session state programmatically . The .NET 4.0 framework adds a new method SetSessionStateBehavior to the HttpContext class for ASP.NET. This method required SessionStatebehavior value to set the current session mode. To call SetSessionStateBehavior simply create a new HttpModule by Implementing IHttModule and hook the BeginRequest event. Most important you can only use the SetSessionStateBehavior until the AcquireRequestState event is fired, because
AcquireRequestState Occurs when ASP.NET acquires the current state that is associated with the current request

While calling SetSessionStatebehavior, You can pass the following values as SessionStatebehavior :


-
Default: This is default setting which means everything works as before
- Disabled: Turned of Session Sate for Current Request.
- ReadOnly: Read only access to Session State;
- Required: Enabled session state for both Read and Write Access



Tip #5
: Compress Session Data while using OutProc Session mode based on Requirements (AP.NET 4.0)

ASP.NET 4.0 comes with a new option for compressing the Session data with Out Process Session mode. To enabling this functionality we need to add “
compressionEnabled=”true” attribute with the SessionMode in web.config.



When Compression mode is enabled is web.config, ASP.NET compress the serialized session data and passed it to session storage and during retrieval same deserialization and decompression happens in server side.
ASP.NET 4.0 used System.IO.Compression.GZStream class to compress the session mode.



Tip#6
: Use HttpContext.Current.Items for very short term storage instead of Session

You can use HttpContext.Current.Items for very short term storage. By Short term storage means, this data is valid for a single HTTP Request. There are many confusion around regarding storing data in HttpContext.Current.Items and storing data in Session variable. Items collections of HttpContext is and IDictionary key-value collections and that are shared across a single HTTPRequest. Yes, HttpContext.Current.Items valid for a single HTTPRequest.




Hope the above tips helps you.


Reasons why you must trust ASPHostPortal.com


Every provider will tell you how they treat their support, uptime, expertise, guarantees, etc., are. Take a close look. What they’re really offering you is nothing close to what
ASPHostPortal does. You will be treated with respect and provided the courtesy and service you would expect from a world-class web hosting business.

You’ll have highly trained, skilled professional technical support people ready, willing, and wanting to help you 24 hours a day. Your web hosting account servers are monitored from three monitoring points, with two alert points, every minute, 24 hours a day, 7 days a week, 365 days a year. The followings are the list of other added- benefits you can find when hosting with us:


-
DELL Hardware
Dell hardware is engineered to keep critical enterprise applications running around the clock with clustered solutions fully tested and certified by Dell and other leading operating system and application providers.
- Recovery Systems
Recovery becomes easy and seamless with our fully managed backup services. We monitor your server to ensure your data is properly backed up and recoverable so when the time comes, you can easily repair or recover your data.

- Control Panel
We provide one of the most comprehensive customer control panels available. Providing maximum control and ease of use, our Control Panel serves as the central management point for your ASPHostPortal account. You’ll use a flexible, powerful hosting control panel that will give you direct control over your web hosting account. Our control panel and systems configuration is fully automated and this means your settings are configured automatically and instantly.

- Excellent Expertise in Technology
The reason we can provide you with a great amount of power, flexibility, and simplicity at such a discounted price is due to incredible efficiencies within our business. We have not just been providing hosting for many clients for years, we have also been researching, developing, and innovating every aspect of our operations, systems, procedures, strategy, management, and teams. Our operations are based on a continual improvement program where we review thousands of systems, operational and management metrics in real-time, to fine-tune every aspect of our operation and activities. We continually train and retrain all people in our teams. We provide all people in our teams with the time, space, and inspiration to research, understand, and explore the Internet in search of greater knowledge. We do this while providing you with the best hosting services for the lowest possible price.

- Data Center

ASPHostPortal modular Tier-3 data center was specifically designed to be a world-class web hosting facility totally dedicated to uncompromised performance and security
- Monitoring Services
From the moment your server is connected to our network it is monitored for connectivity, disk, memory and CPU utilization – as well as hardware failures. Our engineers are alerted to potential issues before they become critical.

- Network
ASPHostPortal has architected its network like no other hosting company. Every facet of our network infrastructure scales to gigabit speeds with no single point of failure.

- Security
Network security and the security of your server are ASPHostPortal’s top priorities. Our security team is constantly monitoring the entire network for unusual or suspicious behavior so that when it is detected we can address the issue before our network or your server is affected.

- Support Services
Engineers staff our data center 24 hours a day, 7 days a week, 365 days a year to manage the network infrastructure and oversee top-of-the-line servers that host our clients’ critical sites and services.





ASP.NET 4 Hosting - ASPHostPortal :: How to use RangeValidator control in ASP.NET 4.0

clock February 29, 2012 07:15 by author Administrator

If you want to understand how RangeValidator works, by example, you can develop a simple test web page. This page uses a single Button web control, two TextBox controls and a RangeValidator control that validates the first text box. If validation fails, the RangeValidator control displays an error message, so you should place this control immediately next to the TextBox it’s validating. The second text box does not use any validation.

The next picture shows the appearance of the page after a failed validation attempt.




The markup for this page defines a RangeValidator control, sets the error message, identifies the control that will be validated, and requires an integer from 32 to 78. These properties are set in the .aspx file, but they could also be configured in the event handler for the Page.Load event. The Button automatically has its CauseValidation property set to true, because this is the default.


A number (32 to 78):


<asp:TextBox id=”validatedBox” runat=”server” />
    <asp:RangeValidator id=”RangeValidator” runat=”server”
    ErrorMessage=”This Number Is Not In The Range”
    ControlToValidate=”validatedBox“
    MaximumValue=”78” MinimumValue=”32“
    ForeColor=”Red” Font-Bold=”true”
    Type=”Integer” />

<br /><br />


Not validated:


<asp:TextBox id=”notValidatedBox” runat=”server” /><br /><br />
<asp:Button id=”cmdOK” runat=”server” Text=”OK” OnClick=”cmdOK_Click” />
<br /><br />
<asp:Label id=”lblMessage” runat=”server” EnableViewState=”False” />


An additional Label control is used to report when the page has been posted back and the event handling code has executed. Its EnableViewState property is disabled to ensure that it will be cleared every time the page is posted back.


The next code lines manage responds to the button click:


protected void cmdOK_Click(Object sender, EventArgs e)
{
lblMessage.Text = “cmdOK_Click event handler executed.”;
}


When you open the page for the first time in modern browsers, the error message is is hidden. But if you type an invalid number (validation will succeed for an empty value) and press the Tab key to move to the second text box, an error message will appear automatically next to the offending control. This is because ASP.NET adds a special JavaScript function that detects when the focus changes. The actual implementation of this JavaScript code is somewhat complicated, but ASP.NET handles all the details for you automatically. As a result, if you try to click the OK button with an invalid value in validatedBox, your actions will be ignored, and the page won’t be posted back.


In case if you want to see what will happen on a browser which does not support client-side validation (i.e. down-level browser), you should set the RangeValidator.EnableClientScript property to false, and rerun the page. Now error messages won’t appear dynamically as you change focus. However, when you click the OK button, the page will be returned from the server with the appropriate error message displayed next to the invalid control.


If you want to ensure that your web page behaves the same in modern and older browsers, you must specifically abort the event code if validation hasn’t been performed successfully. The next code lines correct this problem:


protected void cmdOK_Click(Object sender, EventArgs e)
{
// Abort the event if the control isn’t valid.
if (!RangeValidator.IsValid) return;
lblMessage.Text = “cmdOK_Click event handler executed.”;
}


When the page page contains multiple validation controls, you should follow different approach. In ASP.NET world every web form provides its own IsValid property. This property will be false if any validation control has failed. It will be true if all the validation controls completed successfully. If validation was not performed (for example, if the validation controls are disabled or if the button has CausesValidation set to false), you’ll get an HttpException when you attempt to read the IsValid property. In this case the next code is better:


protected void cmdOK_Click(Object sender, EventArgs e)
{
// Abort the event if any control on the page is invalid.
if (!Page.IsValid) return;
lblMessage.Text = “cmdOK_Click event handler executed.”;
}


Reasons why you must trust ASPHostPortal.com


Every provider will tell you how they treat their support, uptime, expertise, guarantees, etc., are. Take a close look. What they’re really offering you is nothing close to what
ASPHostPortal does. You will be treated with respect and provided the courtesy and service you would expect from a world-class web hosting business.

You’ll have highly trained, skilled professional technical support people ready, willing, and wanting to help you 24 hours a day. Your web hosting account servers are monitored from three monitoring points, with two alert points, every minute, 24 hours a day, 7 days a week, 365 days a year. The followings are the list of other added- benefits you can find when hosting with us:


-
DELL Hardware
Dell hardware is engineered to keep critical enterprise applications running around the clock with clustered solutions fully tested and certified by Dell and other leading operating system and application providers.
- Recovery Systems
Recovery becomes easy and seamless with our fully managed backup services. We monitor your server to ensure your data is properly backed up and recoverable so when the time comes, you can easily repair or recover your data.

- Control Panel
We provide one of the most comprehensive customer control panels available. Providing maximum control and ease of use, our Control Panel serves as the central management point for your ASPHostPortal account. You’ll use a flexible, powerful hosting control panel that will give you direct control over your web hosting account. Our control panel and systems configuration is fully automated and this means your settings are configured automatically and instantly.

- Excellent Expertise in Technology
The reason we can provide you with a great amount of power, flexibility, and simplicity at such a discounted price is due to incredible efficiencies within our business. We have not just been providing hosting for many clients for years, we have also been researching, developing, and innovating every aspect of our operations, systems, procedures, strategy, management, and teams. Our operations are based on a continual improvement program where we review thousands of systems, operational and management metrics in real-time, to fine-tune every aspect of our operation and activities. We continually train and retrain all people in our teams. We provide all people in our teams with the time, space, and inspiration to research, understand, and explore the Internet in search of greater knowledge. We do this while providing you with the best hosting services for the lowest possible price.

- Data Center

ASPHostPortal modular Tier-3 data center was specifically designed to be a world-class web hosting facility totally dedicated to uncompromised performance and security
- Monitoring Services
From the moment your server is connected to our network it is monitored for connectivity, disk, memory and CPU utilization – as well as hardware failures. Our engineers are alerted to potential issues before they become critical.

- Network
ASPHostPortal has architected its network like no other hosting company. Every facet of our network infrastructure scales to gigabit speeds with no single point of failure.

- Security
Network security and the security of your server are ASPHostPortal’s top priorities. Our security team is constantly monitoring the entire network for unusual or suspicious behavior so that when it is detected we can address the issue before our network or your server is affected.

- Support Services
Engineers staff our data center 24 hours a day, 7 days a week, 365 days a year to manage the network infrastructure and oversee top-of-the-line servers that host our clients’ critical sites and services.



ASP.NET Hosting - ASPHostPortal :: Using IIS7 URL Rewrite Module with ASP.Net Routing

clock February 21, 2012 08:18 by author Jervis

Short, simple URLs improve a site’s search engine optimization, usability, and security.  URL rewriting and routing can be used to accomplish this.  URL rewriting/routing improves SEO by distilling URLs down to a set of keywords that search engines can easily parse.  It improves usability by abstracting the file structure of the site, which may change, and presenting a simplified site structure.  It improves security by hiding the details of how a site is implemented by removing querystring and file suffixes.

Before the release of IIS7 and .Net 3.5, most ASP.Net developers implemented URL rewriting by one of the following methods:

1.       Implementing ISAPI filters for IIS

2.       Developing their own HttpModule

3.       Licensing a configurable third party ISAPI filters like ISAPI Rewrite, or HttpModule like UrlRewriter.Net.

With the introduction of IIS7, Microsoft released an add-on module that implements URL rewriting.  The URL Rewrite module works similarly to ISAPI filter based URL rewriting, but has the advantage of being more closely integrated to the web server.  The configuration is XML driven by settings added to the web.config.  The module can map URLs based on regex pattern matching, or by a list of 1-to-1 URL mappings.  In addition, configuration can be done through the IIS7 GUI.

The diagram below shows how URL rewriting using the URL Rewrite Module for IIS7 works.



Pros:

·         Easy to implement

·         Mapping changes do not require a recompile and code deployment

·         Management through IIS7 UI

Cons:

·         Can’t be integrated with a CMS or database driven URL maps

·         No built-in functionality for reverse lookups

·         Locks you in to using IIS7

.Net 3.5 introduced ASP.Net routing, a new way of mapping URLs to HttpHandlers.  ASP.Net routing works differently from any form of URL rewriting.  URL rewriters change an incoming request’s URL and then hands off the request.  ASP.Net doesn’t change the request URL.  Instead, it loads HttpHandlers directly based on its mapping logic.

The following diagram shows how ASP.Net rewriting fits into the request processing pipeline.



Pros:

·         Easier to integrate with CMS or database driven URL mappings

·         Reverse mapping is easier if you build for it

·         Custom implementation offers greater flexibility – like giving developers a neat way of doing A/B testing

Cons:

·         Easy to turn into spaghetti code

·         Changes to mapping logic often require a recompile and code redeploy

·         Takes more effort to implement

For more explanation about the differences between these two methods, read this article.

These two methods can be combined to get some of the advantages of each.  The following example involves an ASP.Net site that contains pages managed by a content management system.  We’d like to have some of the ease of implementation, and maintenance from the IIS module, but we also need to allow some URL mappings to be controlled by the CMS.

The following shows the web.config settings for the IIS Rewrite Module.  The first rule applies the 1-to-1 mappings in the Custom Mappings rewriteMap section.  The second rule routes page requests to four main categories within the site to paths that the ASP.Net URL rewriter module will handle later on in the request lifecycle.

<rewrite>
       <clear />
       <rule name="Apply Custom Rewrite Map" enabled="true" stopProcessing="true">
              <match url="(.*)" />
              <conditions logicalGrouping="MatchAll">
                     <add input="{Custom Mappings:{PATH_INFO}}" pattern="(.+)" />
              </conditions>
              <action type="Rewrite" url="{C:0}" appendQueryString="true" />
       </rule>
       <rule name="Product Type Pages" stopProcessing="true">
              <match url="^(Music|Movies|Games|Accessories)(/)?$" />
              <conditions logicalGrouping="MatchAll" />
              <action type="Rewrite" url="Pages/{R:1}" />
       </rule>
       <rule name="All Other Pages" enabled="true" stopProcessing="true">
              <match url="^([_0-9a-z-]+)(/)?$" />
              <conditions logicalGrouping="MatchAll" />
              <action type="Rewrite" url="Pages/{R:1}.aspx" />
       </rule>
       <rewriteMaps>
              <rewriteMap name="Custom Mappings">
              <add key="/Home" value="Pages/Default.aspx" />
              <add key="/Search" value="Pages/Search/Default.aspx" />
              <add key="/Admin" value="Pages/Admin/SiteAdmin.aspx" />
       </rewriteMap>
       </rewriteMaps>
</rewrite>

The following shows the web.config setting for ASP.Net routing.

<addassembly="System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>


… 

<httpModules>
       <addname="UrlRoutingModule"type="System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</httpModules>

In ASP.Net routing, we don't explicitly implement the HttpModule. Instead we create a class that implements the IRouteHandler interface and load this class in the Application_Start() event handler of the global.asax.

Here is our implementation of the IRouteHandler interface:

public class RouteHandler<T> : IRouteHandler where T : IHttpHandler, new()
       {
              public string VirtualPath { get; set; } 

              public RouteHandler(string virtualPath)
              {
                     this.VirtualPath = virtualPath;
              } 

              public IHttpHandler GetHttpHandler( RequestContext requestContext )
              {
                     IHttpHandler ret = null;
                     foreach ( var value in requestContext.RouteData.Values )
                     {
                           requestContext.HttpContext.Items[ value.Key ] = value.Value;
                     } 

                     ret = ( VirtualPath != null )
                           ? (IHttpHandler)BuildManager.CreateInstanceFromVirtualPath(
                           VirtualPath, typeof( T ) )
                           : new T(); 

                     return ret;
              }
       }

Most of this code is boiler plate to load an HttpHandler based on the mappings that you load up in the Application_Start() handler.

Our example site uses URL mappings defined in an XML file exported by a CMS. So we call a method in the Application_Start() handler in the global.asax that loads this XML file and creates a route for each entry. We do a bit of hand waving here by excluding the code for the CMS.Common.GetRoutes() method because it's probably unnecessary to go over the details parsing an XML.

void Application_Start(object sender, EventArgs e)
{
       RegisterRoutes(RouteTable.Routes);


public static void RegisterRoutes(RouteCollection routes)
{
       CMS.Route[]cmsRoutes = CMS.Common.GetRoutes(); 

       foreach (CMS.Route iCmsRoute in Booking cmsRoutes)
       {
              routes.Add(iCmsRoute.Name, new Route
              (
                      iCmsRoute.RequestPath,
                      new CustomRouteHandler(iCmsRoute.HandlerPath)
              ));
       }
}

Custom mapping URLs to HttpHandlers allows us to create websites with improved SEO, usability and security. The IIS7 URL Rewrite module and ASP.Net routing are two useful tools to map URLs. Each has its advantages and disadvantages, but can be used together to meet various URL mapping requirements.



ASP.NET 4 Hosting - ASPHostPortal :: How to Fix Login failed for user 'IIS APPPOOL\ASP.NET v4.0' error in IIS7

clock February 16, 2012 06:08 by author Jervis

After running a ASP.NET website on IIS 7.5 for the first time on a Windows 7 computer, sometimes you will face this problem:

Login failed for user 'IIS APPPOOL\ASP.NET v4.0'.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.


Exception Details: System.Data.SqlClient.SqlException: Login failed for user 'IIS APPPOOL\ASP.NET v4.0'.

To fix this issue, try changing the (Process Model) Identity of your website's Application Pool to use the NetworkService account (or the less secure LocalSystem account).  By default, IIS7 seems to set the Application Pools Identity to 'ApplicationPoolIdentity', instead of NetworkService or LocalSystem. 

Here's a step-by-step guide for determining your websites Application Pool, then changing its Process Model Idenitty in IIS7: 

1.       Open Internet Information Services (IIS) Manager.

2.       In the Connections sidebar, drill down into Default Web Site and click on your website.

3.       Now in the Actions sidebar (on right side), click on Advance Settings... In the popup box, under General you will see your Application Pool listed for your website (in my case the app pool is: ASP.NET V4.0).

4.       Click Cancel...  If you choose, you can change the Application Pool here, but for the sake of this example we just wanted to find out what the website's App Pool was.

Now that we know the Application Pool that is configured for your website, we now want to change the app pool's (Process Model) Identity to 'NetworkService', here's how:

1.       Open Internet Information Services (IIS) Manager.

2.       In the Connections sidebar, click on Application Pools.

3.       Now right-click on theApplication Pool that your website is using (in this case my site is using the ASP.NET v4.0 application pool), and select Advanced Settings... from the menu.

4.       In the Advanced Settings pop-up box, locate the Process Model -> Identity section and click on the Application Pool Identity. 

5.       In the Application Pool Identity pop-up box, change the Built-in account to NetworkService (or if you want LocalSystem), then click OK, and click OK again to save your Advanced Settings changes.

After changing the Application Pool's Identity to NetworkService (or LocalSystem) you should now be able to get your ASP.NET site to run successfully on an IIS7 web server. Good luck!!



ASP.NET Hosting - ASPHostPortal :: Dynamically Add Controls to ASP.NET Page

clock January 18, 2012 07:26 by author Jervis

Think of ASP.Net web page as a container control containing a set of controls that will render themselves in response to a page request. Here, I'll show you different approaches to add controls (a control can be HTML or server side or System.Web.UI.Control) to ASP.Net web page programmatically at runtime.

Let's quickly create ASP.Net web site and add a new Webform named 'dynamically-add-controls-to-aspnet-page.aspx', say. Set it as 'Start up page' and hit the run button. The page will render with five invisible controls i.e. form1, title and some LiteralControls etc and shows no content.

To add Controls after the </HTML> (at the page bottom): Paste the following code in code behind:

1 public partial class dynamically_add_controls_to_aspnet_page : System.Web.UI.Page 
2 { 
3     protected void Page_Load(object sender, EventArgs e) 
4     { 
5         Label dynamicControl = new Label(); 
6         dynamicControl.Text = "Server side label control"; 
7         Page.Controls.Add(dynamicControl); 
8     } 
9 } 

To add Controls at some index in Controls collection: In the first approach the controls added would be stacked down in the rendering order and placed at page end. You can verify this by running the page and clicking the browser's 'View Source', check out the <span>dynamically added Server side label control</span> at the end. Now we'll see how to add controls dynamically at some place. Let's Paste the following code in code behind:


01 public partial class dynamically_add_controls_to_aspnet_page : System.Web.UI.Page 
02 { 
03     protected void Page_Load(object sender, EventArgs e) 
04     { 
05         Label dynamicControl = new Label(); 
06         dynamicControl.Text = "dynamically added Server side label control"; 
07         // it will dynamically add control right after <body> but before <form>: Check the browser's View Source code 
08         Page.Controls.AddAt(3, dynamicControl);         
09     } 
10 }
 

Dynamically adding Controls asp:PlaceHolder control: Drag asp:PlaceHolder control from toolbox onto the webform. For reference see the following markup code:

01 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="dynamically-add-controls-to-aspnet-page.aspx.cs" Inherits="dynamically_add_controls_to_aspnet_page" %> 
02   
03 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
04 <html xmlns="http://www.w3.org/1999/xhtml"> 
05 <head id="Head1" runat="server"> 
06     <title>dynamically add controls to asp.net page</title> 
07 </head> 
08 <body> 
09     <form id="form1" runat="server"> 
10         <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder> 
11     </form> 
12 </body> 
13 </html>  

1 public partial class dynamically_add_controls_to_aspnet_page : System.Web.UI.Page 
2 { 
3     protected void Page_Load(object sender, EventArgs e) 
4     { 
5         Label dynamicControl = new Label(); 
6         dynamicControl.Text = "dynamically added Server side label control"; 
7         PlaceHolder1.Controls.Add(dynamicControl); 
8     } 
9 } 

Note that we've added PlaceHolder1 inside the form1 control and in the code behind we're adding dynamicControl to it. Ultimately the set of control(s), that we might added to this PlaceHolder1, will get placed in place of PlaceHolder1. Verify via browser's View Source code.

Dynamically adding asp:Button Control to HTML DIV: Here we'll see how to add a button control to HTML DIV tag at runtime. For this add a DIV inside form tag named 'divHtmlControl' ,say and assign it runat="server" attribute. Paste in the following code in code behind:

01 protected void Page_Load(object sender, EventArgs e) 
02 { 
03     Button dynamicButtonControl = new Button(); 
04     dynamicButtonControl.Text = "dynamically adding asp:Button control to HTML DIV"; 
05     dynamicButtonControl.Click += new EventHandler(dynamicButtonControl_Click); 
06   
07     divHtmlControl.Controls.Add(dynamicButtonControl); 
08 } 
09   
10 protected void dynamicButtonControl_Click(object sender, EventArgs e) 
11 { 
12     Button button = sender as Button; 
13     button.Text = "Click event fired"; 
14



ASP.NET Hosting - ASPHostPortal :: How to Improve your ASP.NET Site with Caching

clock January 11, 2012 05:53 by author Jervis

Introduction

In this article, I would like to share my experience and knowledge about ASP.NET Caching and how it can improve your website performance. As you all might know that performance is key requirement for any application or piece of code that you develop.  For mission critical website, Caching is the way to go to significantly enhance your web response times.  Caching is the process of storing frequently used data on the server to fulfill subsequent requests.You will discover that grabbing data or objects from memory is much faster than recreating the web pages or items contained in them from scratch.


When and Why use Caching

A Proper use and fine tune of caching approach of caching will result on better performance and scalability of your site. However improper use of caching will actually slow down and consume lots of your server performance and memory usage.

Good candidate to use caching is if you have infrequent chance of data or static content of web page.

For example, Stock market website displaying 20 minutes delay data can actually use data caching to store the data, so that it can reduce database call every time the user refresh the page.

Another good example would be using Partial page caching to store some of the infrequent or static content. If you have websites that show lots of information or features, you can actually group the static or infrequent change content into user controls and then set the Caching for that particular user controls. You can set the amount of time when the caching expires so that it will load new data from database


Type of Caching

1. Output Caching (Page Caching)

The most easiest and simple caching that you can implement. Good for caching the static page that is accessed frequently. You can copy and paste the code below on your ASP.NET page.

<%@ OutputCache Duration="60" VaryByParam="None" %>

Duration attribute specifies how long in seconds that the page will be held in the memory. When the cache expired, the asp.net engine will automatically reload and refreshes the page again. If the page never change, you can actually set the duration to very long period.

Valid Parameters for OutputCaching


- VaryByParam

The VaryByParam attribute is for caching different type of page based on the HTTP Post or HTTP Get Protocol e.g You can cache dynamic content based on different query string provided.

<%@ OutputCache Duration="60" VaryByParam="CategoryID" %>

In this case, asp.net engine will cache the dynamic page based on the different query string provided. If your page is generating different content based on the query string, then  you need to put that in the output cache directive or else all your users will see the same content.

If you want to cache a new version of the page based on any differences in the Query String parameters, use VaryByParam = "*" as in the following code.


<%@ OutputCache Duration="60" VaryByParam="*" %>

- VaryByControl

VaryByControl can be used to cache the usercontrol inside your page. For example you can cache a user control that contains ComboBox that render all the country name in the world. And perhaps those country data is retrieved from database, this will make significant performance for page loading time.

- VaryByCustom

To make the Cache object even more flexible, Microsoft built in the ability to cache the page based on a string, which is then controlled from the actual code of the application

It does have one "out of the box" property, Browser. When VaryByCustom is set to Browser the page is cached every time a different browser agent and major version number requests the page.


<%@ OutputCache Duration="60" VaryByCustom="browser" %>

If you like to have your own set of Caching rule ,then you might need to tweak some of the code in global .aspx. For e.g You might need to differentiate caching content for different set of users based on cookies called Language. Then you need to copy and paste the following code in your global.asax file.

Code in VB.NET


Overrides Function GetVaryByCustomString(ByVal context as HttpContext,_ByVal arg as String) As String
If arg.ToLower() = "cookies" Then
Dim cookie as HttpCookie = context.Request.Cookies("Language")
If cookie isNot nothing Then
Return cookie.Value
End if
End If
Return MyBase.GetVaryByCustomString(context,arg)
End Function

Code in C#

public override string GetVaryByCustomString(HttpContext context, string arg)
{
if (arg.ToLower() == "cookies")
{
HttpCookie cookie = context.Request.Cookies["Language"];if (cookie != null)
{
return cookie.Value;
}
}
return base.GetVaryByCustomString(context, arg);
}

After that , set the VaryByCustom attribute to "cookies" in your OutputCache directives.
By doing that you will generate different set of caching based on the Client languages cookies. This is just one of the example of doing VaryByCustom caching, you can actually create your own set of caching rules by differentiating caching based on user logged on, and etc.

- VaryByHeader

Varies cache entries based on variations in a specified header

2. Partial Page (UserControl) Caching.

Similar to output Caching, partial page caching allows you to cache certain blocks of your website.You can for example only cache the center of the page. Partial page is achieved with the caching of the user controls.  You can build your ASP.NET pages consisting of numerous user controls and then apply output caching on the user controls you select.  This will caches only parts of the page that you want and leaving other parts of page outside the reach of caching.
This is very nice feature and if it done correctly, it can lead to pages that perform better.

Note :
Typically UserControls are placed on multiple pages to maximize reuse. However, when these UserControls (ASCX Files) are cached with  the @OutputCache Directive , they are cached on per page basis.That means even if a User Control outputs the identical HTML when placed on pageA.aspx as it does placed on pageB.aspx,its output is cached twice.
You can prevent this to happen by adding Shared = true in the output cache directive.


<%@ OutputCache Duration="300" VaryByParam="*" Shared="true" %>

By putting Shared attributed, the memory savings can be surprisingly large.
If you have an ASCX User control using the OutputCache directive,remember that User Control exists only for the first request.

3. Data Caching

Output Caching and Partial Page caching is useful if you want to cache the output of the page. However if you like to cache DataSet object or any Collections object, you can use Data Caching to implement that.

ASP.NET has one class called Cache Object to start caching specific data items for later use on particular page or group of pages. The cache object enables you to store everything from simple name/value pairs to more complex objects like datasets and entire .aspx pages.

VB.NET


Cache("MyDataSet") = myDataSet;

C#

Cache("MyDataSet") = myDataSet;

To retrieve the data from the cache, you can use the code below.

VB.NET 


<strong>Dim ds as New DataSet
ds = CType(Cache("MyDataSet"),DataSet)
</strong>

C#

<strong>DataSet ds = new DataSet();
ds = (DataSet) Cache["MyDataSet"];
 

Conclusion

As we've just seen, caching Web pages with ASP.NET is amazingly easy, accomplished with a simple line. With this glimpse of ASP.NET's caching abilities, you can improve your Web application's performance. But remember Caching in ASP.net is a trade off between CPU and memory. How hard is it to make this page versus whether you can afford to hold 200 versions of it. If it's only 5KB of HTML, a potential megabyte of memory could pay off handsomely versus thousands and thousands of database access. Every page of request served from the cache saves you a trip to the database.

Reasons why you must trust ASPHostPortal.com

Every provider will tell you how they treat their support, uptime, expertise, guarantees, etc., are. Take a close look. What they’re really offering you is nothing close to what ASPHostPortal does. You will be treated with respect and provided the courtesy and service you would expect from a world-class web hosting business.

You’ll have highly trained, skilled professional technical support people ready, willing, and wanting to help you 24 hours a day. Your web hosting account servers are monitored from three monitoring points, with two alert points, every minute, 24 hours a day, 7 days a week, 365 days a year. The followings are the list of other added- benefits you can find when hosting with us:

-
DELL Hardware
Dell hardware is engineered to keep critical enterprise applications running around the clock with clustered solutions fully tested and certified by Dell and other leading operating system and application providers.
- Recovery Systems
Recovery becomes easy and seamless with our fully managed backup services. We monitor your server to ensure your data is properly backed up and recoverable so when the time comes, you can easily repair or recover your data.
- Control Panel
We provide one of the most comprehensive customer control panels available. Providing maximum control and ease of use, our Control Panel serves as the central management point for your ASPHostPortal account. You’ll use a flexible, powerful hosting control panel that will give you direct control over your web hosting account. Our control panel and systems configuration is fully automated and this means your settings are configured automatically and instantly.
- Excellent Expertise in Technology
The reason we can provide you with a great amount of power, flexibility, and simplicity at such a discounted price is due to incredible efficiencies within our business. We have not just been providing hosting for many clients for years, we have also been researching, developing, and innovating every aspect of our operations, systems, procedures, strategy, management, and teams. Our operations are based on a continual improvement program where we review thousands of systems, operational and management metrics in real-time, to fine-tune every aspect of our operation and activities. We continually train and retrain all people in our teams. We provide all people in our teams with the time, space, and inspiration to research, understand, and explore the Internet in search of greater knowledge. We do this while providing you with the best hosting services for the lowest possible price.
- Data Center
ASPHostPortal modular Tier-3 data center was specifically designed to be a world-class web hosting facility totally dedicated to uncompromised performance and security
- Monitoring Services
From the moment your server is connected to our network it is monitored for connectivity, disk, memory and CPU utilization – as well as hardware failures. Our engineers are alerted to potential issues before they become critical.
- Network
ASPHostPortal has architected its network like no other hosting company. Every facet of our network infrastructure scales to gigabit speeds with no single point of failure.
- Security
Network security and the security of your server are ASPHostPortal’s top priorities. Our security team is constantly monitoring the entire network for unusual or suspicious behavior so that when it is detected we can address the issue before our network or your server is affected.
- Support Services
Engineers staff our data center 24 hours a day, 7 days a week, 365 days a year to manage the network infrastructure and oversee top-of-the-line servers that host our clients’ critical sites and services.



ASP.NET 4 Hosting - ASPHostPortal :: How to Resolve It is an error to use a section registered as allowDefinition='MachineToApplication' beyond application level

clock December 12, 2011 05:42 by author Jervis

You may get this error when trying to browse an asp.net application.

Server Error in '/' Application



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: 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.

Source Error:

Line 17:     <compilation debug="false" strict="false" explicit="true" targetFramework="4.0" />
Line 18:
Line 19:     <authentication mode="Forms">
Line 20:       <forms loginUrl="~/Account/Login.aspx" timeout="2880" />
Line 21:     </authentication>

It is caused by a virtual directory not being configured as an application in IIS.

However, this error occurs primarily out of 2 scenarios.

1. When you create an new web application using visual studio.net, it automatically creates the virtual directory and configures it as an application. However, if you manually create the virtual directory and it is not configured as an application, then you will not be able to browse the application and may get the above error. The debug information you get as mentioned above, is applicable to this scenario.

To resolve it, Right Click on the virtual directory - select properties and then click on "Create" next to the "Application" Label and the textbox. It will automatically create the "application" using the virtual directory's name. Now the application can be accessed.

2. When you have sub-directories in your application, you can have web.config file for the sub-directory. However, there are certain properties which cannot be set in the web.config of the sub-directory such as authentication, session state (you may see that the error message shows the line number where the
authentication or sessionstate is declared in the web.config of the sub-directory). The reason is, these settings cannot be overridden at the sub-directory level  unless the sub-directory is also configured as an application (as mentioned in the above point).

Mostly we have the practice of adding web.config in the sub-directory if we want to protect access to the sub-directory files (say, the directory is admin and we wish to protect the admin pages from unathorized users).

But actually, this can be achieved in the web.config at the application's root level itself, by specifing the location path tags and authorization, as follows:-

<location path="Admin">
<system.web>
<authorization>
<allow roles="administrators" />
<deny users="*" />
</authorization>
</system.web>
</location>

However, if you wish to have a web.config at the sub-directory level and protect the sub-directory, you can just specify the Authorization mode as follows:-

<configuration>
<system.web>
<authorization>
<allow roles="administrators" />
<deny users="*" />
</authorization>
</system.web>
</configuration>


Thus you can protect the sub-directory from unauthorized access. Good luck…

Reasons why you must trust ASPHostPortal.com

Every provider will tell you how they treat their support, uptime, expertise, guarantees, etc., are. Take a close look. What they’re really offering you is nothing close to what ASPHostPortal does. You will be treated with respect and provided the courtesy and service you would expect from a world-class web hosting business.

You’ll have highly trained, skilled professional technical support people ready, willing, and wanting to help you 24 hours a day. Your web hosting account servers are monitored from three monitoring points, with two alert points, every minute, 24 hours a day, 7 days a week, 365 days a year. The followings are the list of other added- benefits you can find when hosting with us:

-
DELL Hardware
Dell hardware is engineered to keep critical enterprise applications running around the clock with clustered solutions fully tested and certified by Dell and other leading operating system and application providers.
- Recovery Systems
Recovery becomes easy and seamless with our fully managed backup services. We monitor your server to ensure your data is properly backed up and recoverable so when the time comes, you can easily repair or recover your data.
- Control Panel
We provide one of the most comprehensive customer control panels available. Providing maximum control and ease of use, our Control Panel serves as the central management point for your ASPHostPortal account. You’ll use a flexible, powerful hosting control panel that will give you direct control over your web hosting account. Our control panel and systems configuration is fully automated and this means your settings are configured automatically and instantly.
- Excellent Expertise in Technology
The reason we can provide you with a great amount of power, flexibility, and simplicity at such a discounted price is due to incredible efficiencies within our business. We have not just been providing hosting for many clients for years, we have also been researching, developing, and innovating every aspect of our operations, systems, procedures, strategy, management, and teams. Our operations are based on a continual improvement program where we review thousands of systems, operational and management metrics in real-time, to fine-tune every aspect of our operation and activities. We continually train and retrain all people in our teams. We provide all people in our teams with the time, space, and inspiration to research, understand, and explore the Internet in search of greater knowledge. We do this while providing you with the best hosting services for the lowest possible price.
- Data Center
ASPHostPortal modular Tier-3 data center was specifically designed to be a world-class web hosting facility totally dedicated to uncompromised performance and security
- Monitoring Services
From the moment your server is connected to our network it is monitored for connectivity, disk, memory and CPU utilization – as well as hardware failures. Our engineers are alerted to potential issues before they become critical.
- Network
ASPHostPortal has architected its network like no other hosting company. Every facet of our network infrastructure scales to gigabit speeds with no single point of failure.
- Security
Network security and the security of your server are ASPHostPortal’s top priorities. Our security team is constantly monitoring the entire network for unusual or suspicious behavior so that when it is detected we can address the issue before our network or your server is affected.
- Support Services
Engineers staff our data center 24 hours a day, 7 days a week, 365 days a year to manage the network infrastructure and oversee top-of-the-line servers that host our clients’ critical sites and services.



ASP.NET 4 Hosting - ASPHostPortal :: How to Encrypt Connection String in Web.Config

clock December 4, 2011 05:57 by author Jervis

The most sensitive information stored in web.config file can be the connection string. You do not want to disclose the information related to your database to all the users where the application is deployed. Every time it is not possible to have a private machine for your sites, you may need to deploy the site in shared host environment. To encrypt the connection string in above situation is advisable.

ASP.NET 2.0 provides in built functionality to encrypt few sections of web.config file. The task can be completed using Aspnet_regiis.exe. Below is the web.config file and <connectionStrings> section.   

   1: <connectionStrings>
   2:   <add name="cn1"
   3:           connectionString="Server=DB SERVER;
   4:                             database=TestDatabase;
   5:                             uid=UID;
   6:                             pwd=PWD;" />
   7:  </connectionStrings>

To encrypt the connection string section follow the steps,

1. Go to Start -> Programm Files -> Microsoft Visual Studio 2005 -> Visual Tools -> Microsoft Visual Studio 2005 Command Prompt

2. Type following command,

aspnet_regiis.exe -pef “connectionStrings” C:\Projects\DemoApplication

-pef indicates that the application is built as File System website.  The second argument is the name of configuration section needs to be encrypted. Third argument is the physical path where the web.config file is located.

If you are using IIS base web site the command will be,

 aspnet_regiis.exe -pe “connectionStrings” -app “/DemoApplication”

 -pe indicates that the application is built as IIS based site. The second argument is the name of configuration section needs to be encrypted. Third argument “-app” indicates virtual directory and last argument is the name of virtual directory where application is deployed.   

If everything goes well you will receive a message “Encrypting configuration section…Succeeded!”

Open your web.config file and you can see that connection string is encrypted,

   1: <connectionStrings configProtectionProvider="RsaProtectedConfigurationProvider">
   2:   <EncryptedData Type=http://www.w3.org/2001/04/xmlenc#Element
   3:    xmlns="http://www.w3.org/2001/04/xmlenc#">
   4:    <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#tripledes-cbc" />
   5:    <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
   6:     <EncryptedKey xmlns="http://www.w3.org/2001/04/xmlenc#">
   7:
      <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa
1_5"
/>

   8:      <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
   9:       <KeyName>Rsa Key</KeyName>
  10:      </KeyInfo>
  11:      <CipherData>
  12:       <CipherValue>Ik+l105qm6WIIQgS9LsnF8RRxQtj2ChEwq7DbHapb440GynFEoGF6Y3EM3Iw/lyDV8+P8bIsketi5Ofy9gpZlCBir7n315Q6RPbdclUo79o/LKadhX4jHFpnSIQNIF/LhwjwkLFC0=</CipherValue>
  13:      </CipherData>
  14:     </EncryptedKey>
  15:    </KeyInfo>
  16:    <CipherData>
  17:     <CipherValue>JsLrQ5S8Pq3U72nQzmSl/XlLX72GM0O3EbPLaHRNvjTDgG9seDflGMjTfO10M1s7/mPh//3MhA7pr0dNHUJ143Svhu5YXODRC6z9CkR0uyE4H7uDvTKJ8eR3m9APhXoo1sT1K3tCLHD6a2BM+gqSk9d8PzCfbM8Gmzmpjz1ElIaxu62b4cg9SNxp8o86O9N3fBl2mq</CipherValue>
  18:    </CipherData>
  19:   </EncryptedData>
  20:  </connectionStrings>

You do not have to write any code to decrypt this connection string in your application, dotnet automatically decrypts it. So if you write following code you can see plaintext connection string.

   1: Response.Write(ConfigurationManager.ConnectionStrings["cn1"].ConnectionString);

Now to decrypt the configuration section in web.config file use following command,

For File System Application,

aspnet_regiis.exe -pdf “connectionStrings” C:\Projects\DemoApplication

For IIS based Application

aspnet_regiis.exe -pd “connectionStrings” -app “/DemoApplication” 

If you want to encrypt any nested section in web.config file like <pages> element within <system.web> you need to write full section name as shown below,

aspnet_regiis.exe -pef “system.web/Pages” C:\Projects\DemoApplication

You can encrypt all the sections of web.config file except following using the method I displayed in this article,

<processModel>
<runtime>
<mscorlib>
<startup>
<system.runtime.remoting>
<configProtectedData>
<satelliteassemblies>
<cryptographySettings>
<cryptoNameMapping>
<cryptoClasses>


To encrypt these section you needed to use Aspnet_setreg.exe tool.  For more detail about Aspnet_setreg.exe tool search Microsoft Knowledge Base article 329290, How to use the ASP.NET utility to encrypt credentials and session state connection strings. 

Happy Programming !!!

Need ASP.NET 4 hosting? Please visit our site at
http://www.asphostportal.com. Just with only $5.00/month to get ASP.NET 4 hosting. If you have any further questions, please feel free to email us at [email protected].

Reasons why you must trust ASPHostPortal.com

Every provider will tell you how they treat their support, uptime, expertise, guarantees, etc., are. Take a close look. What they’re really offering you is nothing close to what ASPHostPortal does. You will be treated with respect and provided the courtesy and service you would expect from a world-class web hosting business.

You’ll have highly trained, skilled professional technical support people ready, willing, and wanting to help you 24 hours a day. Your web hosting account servers are monitored from three monitoring points, with two alert points, every minute, 24 hours a day, 7 days a week, 365 days a year. The followings are the list of other added- benefits you can find when hosting with us:

-
DELL Hardware
Dell hardware is engineered to keep critical enterprise applications running around the clock with clustered solutions fully tested and certified by Dell and other leading operating system and application providers.
- Recovery Systems
Recovery becomes easy and seamless with our fully managed backup services. We monitor your server to ensure your data is properly backed up and recoverable so when the time comes, you can easily repair or recover your data.
- Control Panel
We provide one of the most comprehensive customer control panels available. Providing maximum control and ease of use, our Control Panel serves as the central management point for your ASPHostPortal account. You’ll use a flexible, powerful hosting control panel that will give you direct control over your web hosting account. Our control panel and systems configuration is fully automated and this means your settings are configured automatically and instantly.
- Excellent Expertise in Technology
The reason we can provide you with a great amount of power, flexibility, and simplicity at such a discounted price is due to incredible efficiencies within our business. We have not just been providing hosting for many clients for years, we have also been researching, developing, and innovating every aspect of our operations, systems, procedures, strategy, management, and teams. Our operations are based on a continual improvement program where we review thousands of systems, operational and management metrics in real-time, to fine-tune every aspect of our operation and activities. We continually train and retrain all people in our teams. We provide all people in our teams with the time, space, and inspiration to research, understand, and explore the Internet in search of greater knowledge. We do this while providing you with the best hosting services for the lowest possible price.
- Data Center
ASPHostPortal modular Tier-3 data center was specifically designed to be a world-class web hosting facility totally dedicated to uncompromised performance and security
- Monitoring Services
From the moment your server is connected to our network it is monitored for connectivity, disk, memory and CPU utilization – as well as hardware failures. Our engineers are alerted to potential issues before they become critical.
- Network
ASPHostPortal has architected its network like no other hosting company. Every facet of our network infrastructure scales to gigabit speeds with no single point of failure.
- Security
Network security and the security of your server are ASPHostPortal’s top priorities. Our security team is constantly monitoring the entire network for unusual or suspicious behavior so that when it is detected we can address the issue before our network or your server is affected.
- Support Services
Engineers staff our data center 24 hours a day, 7 days a week, 365 days a year to manage the network infrastructure and oversee top-of-the-line servers that host our clients’ critical sites and services.



Cheap ASP.NET 4.5 Hosting

We’re a company that works differently to most. Value is what we output and help our customers achieve, not how much money we put in the bank. It’s not because we are altruistic. It’s based on an even simpler principle. "Do good things, and good things will come to you".

Success for us is something that is continually experienced, not something that is reached. For us it is all about the experience – more than the journey. Life is a continual experience. We see the Internet as being an incredible amplifier to the experience of life for all of us. It can help humanity come together to explode in knowledge exploration and discussion. It is continual enlightenment of new ideas, experiences, and passions


Author Link


 

Corporate Address (Location)

ASPHostPortal
170 W 56th Street, Suite 121
New York, NY 10019
United States

Tag cloud

Sign in