European ASP.NET 4.5 Hosting BLOG

BLOG about ASP.NET 4, ASP.NET 4.5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

European ASP.NET 4 Hosting :: How to Redirect From domain.com to www.domain.com in ASP.NET

clock February 21, 2012 07:35 by author Scott

If you want to redirect from domain.com to www.domain.com in asp.net application, then you can do it through IIS settings, but you can do it through code file also. You can write the code in the global.asax file in the Application_BeginRequest method.

void Application_BeginRequest(object sender, EventArgs e)
    {
        string FromHomeURL = "http://yourdomain.com";
        string ToHomeURL = "http://www.yourdomain.com";


       if (HttpContext.Current.Request.Url.ToString().ToLower().Contains(FromHomeURL))
        {
            HttpContext.Current.Response.Status = "301 Moved Permanently";
            HttpContext.Current.Response.AddHeader("Location",
            Request.Url.ToString().ToLower().Replace(FromHomeURL, ToHomeURL));
        }
}



European ASP.NET 4 Hosting - Amsterdam :: Call ASP.NET Page Methods using your own AJAX

clock February 17, 2012 07:18 by author Scott

Microsoft has introduced JQuery as a primary javascript development tool for client end application. Even though there is a number of flexibility in ASP.NET AJAX applications, many developers do seek place to actually call a page using normal AJAX based application. In this post I will cover how you can invoke an ASP.NET page method directly from your own AJAX library.

What are page methods?

A Page method is a method that is written directly in a page. It is generally called when the actual page is posted back and some event is raised from the client. The pageMethod is called directly from ASP.NET engine.


What is a WebMethod?

A WebMethod is a special method attribute that exposes a method directly as XML service. To implement PageMethod we first need to annotate our method as WebMethod.

Steps to Create the application :

1. Start a new ASP.NET Project.
2. Add
JQuery to your page. I have added a special JQuery plugin myself which stringify a JSON object. The post looks like below :


(function ($) {
$.extend({
toJson: function (obj) {
var t = typeof (obj);
if (t != "object" || obj === null) {
// simple data type
if (t == "string") obj = '"' + obj + '"';
return String(obj);
}
else {
// recurse array or object
var n, v, json = [], arr = (obj && obj.constructor == Array);
for (n in obj) {
v = obj[n]; t = typeof (v);
if (t == "string") v = '"' + v + '"';
else if (t == "object" && v !== null) v = JSON.stringify(v);
json.push((arr ? "" : '"' + n + '":') + String(v));
}
return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
}
}
});
// extend plugin scope
$.fn.extend({
toJson: $.toJson.construct
});
})(jQuery);

The code actually extends JQuery to add a method called toJSON to its prototype.


3. Add the server side method to the Default.aspx page. For simplicity we actually return the message that is received from the client side with some formatting.

[WebMethod]
public static string DisplayTime(string message)
{
// Do something

return string.Format("Hello ! Your message : {0} at {1}", message,
DateTime.Now.ToShortTimeString());
}

Remember : You should make this method static, and probably should return only serializable object.

4. Add the following Html which actually puts one TextBox which takes a message and a Button to call server.

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<h2>
Welcome to ASP.NET!
</h2>
<p>
Write Your message Here : <input type="text" id="txtMessage" />
</p>
<p>
<input type="button" onclick="javascript:callServer()" value="Call Server" />
</p>
</asp:Content>

Once you add this html to your default.aspx page, add some javascript to the page. We add the JQuery and our JSONStringify code to it.

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

<script type="text/javascript">
function callServer() {
var objdata = {
"message" : $("#txtMessage").val()
};
$.ajax({
type: "POST",
url: "Default.aspx/DisplayTime",
data: $.toJson(objdata),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
},
error: function (xhr, ajaxOptions) {
alert(xhr.status);
}
});
}
</script>

The above code actually invokes a normal AJAX call to the page. You can use your own library of AJAX rather than JQuery to do the same. On success, it returns the serializable object to msg.d.



European ASP.NET 4 Hosting - Amsterdam :: Application pool identity of IIS 7.x as a SQL Server login to use

clock February 15, 2012 07:46 by author Scott

If we develop an ASP.NET (MVC) Web site using the ASP.NET Development Server and SQL Server database in use does, at first everything easily.

If, however, for the development of a "real" IIS 7.x, eg Windows 7, we obtain the database access, the following exception:



The solution is pretty simple - you have the Application Pool Identity "IIS AppPool \ mvcapp" assign to the users in the database.

Unfortunately, this does not do this with the SQL Server Management Studio.

Although you can insert the name of the Application Pool Identity



and be validated by "Check Names"



After clicking "OK", but you get the error message that the user was not found:



A solution to generate the login via script:

CREATE LOGIN [IIS AppPool \ MyPool] FROM WINDOWS WITH  DEFAULT_DATABASE = [master] USE [mydatabase] CREATE USER [IIS AppPool \ MyPool] FOR LOGIN [IIS AppPool \ MyPool]  

Then you can assign the SQL Server Management Studio, the permissions so that the website works with the Application Pool Identity.



European Ajax Hosting - Amsterdam :: 3 Mistakes to Avoid when Using jQuery with ASP.NET AJAX

clock February 7, 2012 08:16 by author Scott

In this post, I’m going to detail three of the problems that were discovered as a result of those previous two posts:

-          An extra requirement when making a read-only request to IIS6+.

-          An oddity in Internet Explorer 7′s XmlHttpRequest class.

-          A common mistake when passing JSON parameters through jQuery.

Finally, I’ll suggest what I now believe to be a best practice usage, taking all of these issues into account.

Security requirements when POSTing to IIS

This error message was the most common problem that was reported:

Length Required

The underlying issue is that most installations of IIS6+ require a content-length be provided with all POST requests, even if there is no content (POST data).

The content-length for a request with no data should be 0, but jQuery doesn’t set that header automatically unless there is a data parameter. Since ASP.NET AJAX’s JSON serialized services require a POST request, this becomes a stumbling block for read-only requests.

The easiest way I’ve found to work around this is to use an empty JSON object as a parameter on read-only requests. For example, if you were calling a page method:

$.ajax({
  type: "POST",
  url: "PageMethod.aspx/PageMethodName",
  data: "{}",
  contentType: "application/json; charset=utf-8",
  dataType: "json"
});

This will cause jQuery to correctly set a content-length of 2, while your web service or page method will happily ignore the empty parameter and treat the request as read-only.

A problem with Internet Explorer and XmlHttpRequest

Previously, to call ASP.NET AJAX services with jQuery, I suggested this usage:

$.ajax({
  type: "POST",
  url: "WebService.asmx/WebMethodName",
  beforeSend: function(xhr) {
    xhr.setRequestHeader("Content-type",
                         "application/json; charset=utf-8");
  },
  dataType: "json"
});

The reason for the beforeSend delegate is due a quirk in jQuery which causes it to send a specified content-type only if there is also a data parameter specified.


For security reasons, ASP.NET AJAX will not provide a JSON serialized response unless the proper content-type is provided. By using the beforeSend delegate as shown, the content-type will be manually set on the XmlHttpRequest object, before the request.

However, the new XmlHttpRequest class in Internet Explorer 7 doesn’t implement setRequestHeader very intuitively. Instead of setting the specified header, it appends the value.

This becomes a problem when you make a request that includes a data parameter. When POST data is provided, jQuery will automatically set the content-type to its default of application/x-www-form-urlencoded. In the beforeSend delegate, the required application/json; charset=utf-8 will be appended after jQuery’s default.

End result? Because this amalgamation of content-types isn’t what ASP.NET AJAX expects, the web service will not return JSON serialized content and jQuery will be unable to parse it.

Solution? If you’re sending data in your request, use jQuery’s contentType parameter to set the content-type, so that the default is never added:

$.ajax({
  type: "POST",
  url: "WebService.asmx/WebMethodName",
  data: "{'fname':'dave', 'lname':'ward'}",
  contentType: "application/json; charset=utf-8",
  dataType: "json"
});

JSON, objects, and strings

ASP.NET AJAX script services and page methods understand and expect input parameters to be serialized as JSON strings. These parameters are parsed out of the POST data and used as arguments to the method you’ve called.

However, if you directly provide a JSON object as the data parameter for an $.ajax call, jQuery will attempt to URL encode the object instead of passing it on to your web service.

Take this sample request, for example:

$.ajax({
  type: "POST",
  url: "WebService.asmx/WebMethodName",
  data: {'fname':'dave', 'lname':'ward'},
  contentType: "application/json; charset=utf-8",
  dataType: "json"
});

Because that data parameter is a valid object literal, calling the web service this way won’t throw any JavaScript errors on the client-side. Unfortunately, it won’t have the desired result either. Instead of passing that object through to the web service as JSON, jQuery will automatically URL encode it and send it as:

fname=dave&lname=ward

To which, the server will respond with:

Invalid JSON primitive: fname.

This is clearly not what we want to happen. The solution is to make sure that you’re passing jQuery a string for the data parameter, like this:

$.ajax({
  type: "POST",
  url: "WebService.asmx/WebMethodName",
  data: "{'fname':'dave', 'lname':'ward'}",
  contentType: "application/json; charset=utf-8",
  dataType: "json"
});

It’s a small change in syntax, but makes all the difference. Now, jQuery will leave our JSON object alone and pass the entire string to ASP.NET for parsing on the server side.

Taking these three caveats into account, I think this is the best practice for calling read-only ASP.NET AJAX web services via jQuery:

$.ajax({
  type: "POST",
  url: "ServiceName.asmx/WebMethodName",
  data: "{}",
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function(msg) {
    // Do interesting things here.
  }
})
;

When consuming web services that require parameters, the usage is similar. Just make sure that you’re passing a JSON object in a string:

$.ajax({
  type: "POST",
  url: "ServiceName.asmx/WebMethodName",
  data: "{'fname':'dave','lname':'ward'}",
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function(msg) {
    // Do magic here.
  }
});

In either of these cases, substitute PageName.aspx for ServiceName.asmx and PageMethodName for WebMethodName if you want to call a page method instead of a web service.



European ASP.NET 4 Hosting :: How to Set Authentication Rules in Web.Config

clock February 2, 2012 06:20 by author Scott

I have seen so many people asking again and again how to give allow access to particular page to a person or roles. So I thought its good to put this in one place. I will discuss how to configure web.config depending on the scenario.

We will start with a web.config without any authorization and modify it on case by case bassis.

No Authorization

We will start with the root web.config without any authorization.

<configuration>

<system.web>
<authentication mode="Forms">
</authentication> </system.web>
</configuration>

Deny Anonymous user to access entire website

This is the case when you want everybody to login before the can start browsing around your website. i.e. The first thing they will see is a login page.

<system.web>
<authentication mode="Forms">
</authentication>
<authorization>
<deny users="?"/> //will deny anonymous users </authorization>
</system.web>

The above situation is good when user don't have to register themselves but instead their user account is created by some administrator.

Allow access to everyone to a particular page

Sometimes you want to allow public access to your registeration page and want to restrict access to rest of the site only to logged / authenticated users .i.e. do not allow anonymous access. Say your registration page is called register.aspx in your site's root folder. In the web.config of your website's root folder you need to have following setup.


<configuration>
<system.web>
<
authentication mode="Forms"/>

<authorization> <deny users="?"/>  //this will restrict anonymous user access
</authorization>
</system.web>
<location path="register.aspx"> //path here is path to your register.aspx page e.g. it could be ~/publicpages/register.aspx
<system.web>
<authorization>
<allow users="*"/> // this will allow access to everyone to register.aspx
</authorization>
</system.web>
</location>
</configuration>

Till now we saw either allow users or to authenticated users only. But there could be cases where we want to allow particular user to certain pages but deny everyone else (authenticated as well as anonymous). 

To allow access to particular user only and deny everyone else

Say you want to give access to user "John" to a particular page e.g. userpersonal.aspx and deny all others the location tag above should look like below:

<location path="userpersonal.aspx">

<system.web>
<authorization>
<allow users="Scott"/> // allow Scott ..note: you can have multiple users seperated by comma e.g. Scott,Gary,etc
<deny users="*"/>  // deny others
</authorization>
</system.web>
</location>

Allow only users in particular Role

Here I am will not show how to setup roles. I assume you have roles managment setup for users. We will see now what needs to be done in web.config to configure authorization for a particular role. e.g You have two roles. Customer and Admin and two folders CustomerFolder and AdminFolder. Users in Admin role can access both folders. Users in Customers role can access only CustomerFolder and not AdminFolder. You will have to add location tags for each folder path as shown below:

<location path="AdminFolder">
<system.web>
<authorization>
<allow roles="Admin"/> //Allows users in Admin role
<deny users="*"/> // deny everyone else
</authorization>
</system.web>
</location>
<location path="CustomerFolder">
<system.web>
<authorization>
<allow roles="Admin, Customers"/> //Allow users in Admin and Customers roles
<deny users="*"/> // Deny rest of all
</authorization>
</system.web>
</location>

Alternate way - using individual web.config for each Folder

Alternative to above mentioned method of using <location../> tag, you can add web.config to each folder and configure authorization accordingly almost similar to one show above but not using location tag. Taking same eg. as above. Add web.config to both the folders - AdminFolder and CustomerFolder.

Web.config in AdminFolder should look like:

<configuration>
<system.web>
<authorization>
<allow roles="Admin"/> //Allows users in Admin role
<deny users="*"/> // deny everyone else
</authorization>
</system.web>
</configuration>
Web.config in CustomerFolder should look like: 
<configuration>
<system.web>
<authorization>
<allow roles="Admin, Customers"/> //Allow users in Admin and Customers roles
<deny users="*"/> // Deny rest of all
</authorization>
</system.web>
</configuration>

Images and CSS files

Say you have all your images and CSS in a seperate folder called images and you are denying anonymous access to your website. In that case you might see that on your login page you cannot see images(if any) and css(if any) applied to your login page controls.

In that case you can add a web.config to the images and css folder and allow access to everyone to that folder. So your web.config in images folder should look as below:

<configuration>
<system.web>
<authorization>
<allow users="*"/> //Allow everyone
</authorization>
</system.web>
</configuration>

Common Mistakes

I have seen people complaining that they have setup their roles correctly and also made entry to their web.config but still their authorization doesn't work. Even they have allowed access to their role that user cannot access particular page/folder. The common reason for that is placing <deny../> before <allow ../>.

Say the web.config from AdminFolder as we have seen before is something like this:

//This web.config will not allow access to users even they are in Admin Role 

<configuration>
<system.web>
<authorization>
<deny users="*"/> // deny everyone else
<allow roles="Admin"/> //Allows users in Admin role
</authorization>
</system.web>
</configuration>

Since the authorization is done from top to bottom, rules are checked until a match is found. Here we have <deny users="*"/> first and so it will not check for allow any more and deny access even if in Admin role.

So PUT all allows BEFORE ANY deny.

NOTE: deny works the same way as allow. You can deny particular roles or users as per your requirement. 



European ASP.NET Hosting :: How to Solve Unable to make the session state request to the session state server

clock January 6, 2012 07:23 by author Scott

In this article I will explain how to solve Unable to make the session state request to the session state server. Please ensure that the ASP.NET State service is started and that the client and server ports are the same. To describe it, please see this image below:



To solve this error I started Asp.net state service from services to start the service just follow below steps

Go to Control Panel ---> Administrative Tools ---> Computer Management ---> Services and Applications ---> Services 

Now Select Asp.Net State Service

After that Right Click on Asp.net State Service and choose “Start” option.



After start the service your problem will solve automatically. Hope it helps



European ASP.NET Hosting :: Create Membership tables in another database than the standard aspnetdb.mdf

clock January 4, 2012 07:42 by author Scott

When you start creating a new ASP.NET 2.0 site with Visual Studio 2005 or Visual Web Developer Express (VWD) and want to start using it you'll notice that a new file in the App_Data folder gets created besides your own database, namely the aspnetdb.mdf file. This extra database holds all the tables and stored procedures to let Membership, Roles, Profile etc run smoothly.

However a problem arises when you don't want to use that dedicated new database when you want to deploy to your live webserver, certainly not when you use a host that only offers one database and charges you extra for another database. Luckely you can control things more when using the dedicated aspnet_regsql tool that ships with the .NET 2.0 framework.

What I'm about to describe in this article is how to use that tool to generate a SQL script that you can use to run on your other database with a tool like SQL Server Management Studio (SSMS). In this example I'll be using the installed Northwind database on my localhost developer machine.

Just start up a new DOS box by going to Start | Run and type in cmd followed by enter. In Windows Vista you push the blue windows logo button and in the field with the text Start Search you type in cmd followed by ctrl + shift + enter. The reason for that combination is that you must run it under Admin privileges or else the to be generated file doesn't get writed to disk.
A new DOS box will appear and you just navigate to the following directory/folder:

Windows\Microsoft.NET\Framework\v2.0.50727\

If you're not used to using DOS you can navigate to it by typing this in the DOS box: cd \windows\Microsoft.net\framework\v2.0.50727 followed by enter.


Then you type in this line: aspnet_regsql.exe -E -S localhost -d Northwind -A all -sqlexportonly c:\membership.sql again followed by enter. At the location c:\ a new file gets generated: membership.sql.



The Northwind name in the parameter list is later on used to set the db name in the generated sql file: SET @dbname = N'Northwind'

Once generated you can use/tweak this file to be used in SSMS to get executed and to install everything needed in the database.

Ok, up untill now we focussed on getting everything ready on the database side but we also have to let our ASP.NET 2.0 application know that we're pointing out to another database than the default one. The solution for this is to override the default settings for the LocalSqlServer connectionstring which can be found in the machine.config file.

<add name="LocalSqlServer"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;
AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true"
providerName="System.Data.SqlClient" />

To override that you open the web.config file in your application which can be normally found in the root of the application. Go to the <connectionStrings> element.


<connectionStrings>
    <remove name="LocalSqlServer"/>
    <add name="LocalSqlServer" connectionString="The connection string to your
                         (new) database" providerName="System.Data.SqlClient" />
</connectionStrings>

Notice the second line where you call the remove statement. This is needed in order to be able to override the LocalSqlServer connection string!

If you're in need of a little help to get your connection string right there's a dedicated site: http://www.connectionstrings.com/.

If you need ASP.NET hosting with SQL database, please visit our site at http://www.hostforlife.eu. If you have any questions, please feel free to email us at [email protected].



European ASP.NET 4 Hosting :: How to Making HTML5 Video work with IIS Express

clock January 3, 2012 15:10 by author Scott

Happy New Year 2012!!! Hope this year will bring happiness, success, and prosperiority.

In this tutorial, I will show how to making HTML 5 video work with IIS Express. Ok, first I created a simple MVC Application with “File – New - Project – ASP.NET MVC 3 Web Application” and left the defaults to create an Application.  I added a videos folder and added a H.264 encoded mp4 video (one of the supported HTML5 Video formats) inside the folder.

Then, I added the following line of code in the “Index.cshtml” file.

<video src="@Url.Content("~/Videos/video.mp4")" id="myVideo" controls ></video>



All I got was the above.  Basically a broken link.  I verified that the path is right and the video is indeed playable on Windows Media Player etc.,

The issue was that, since by default Visual Studio uses the ASP.NET Development Server and the ASP.NET Development Server doesn’t have the flexibility to configure MIME types,  It doesn’t understand the video format and hence could not play.  When I ran the application on IE9 and checked the Network Tab of the Developer Toolbar, all I got was what you see below



I switched the Project to use IIS Express using “ProjectName” – Right Click – Properties – Web Tab



Still had the same result.  Since IIS Express also doesn’t have the MIME Type to play video, configured by default, it couldn’t recognize the video and couldn’t play it.

The simple option is to configure it to use the “Actual IIS” (in the above screen, remove the check from “Use IISExpress”) which can play the video.

But, thankfully
this blog post has steps on how to configure MIME types for IIS Express.  Only thing is, I had to change it for configuring the MIME type for playing MP4 video.

So, the steps are

1. Click on Start button
2. Type CMD
3. Right click on the CMD that is listed and choose “Run as Administrator”
4. Do a cd to navigate to the IIS Express directory CD “Program Files (x86)”\”IIS Express”
5. And then run the following command

appcmd set config /section:staticContent /+[fileExtension='.mp4',mimeType='vieo/mp4']

That’s it.  When I re-ran the application, it could play the video.



Please note, I was unable to configure or figure out how to do it for the ASP.NET Development Server.  So, if we need to play HTML5 Video from Visual Studio we either need to use IIS Express or use the full fledged IIS.  And from the performance and configuration perspective IIS Express offers a lot more than ASP.NET Development Server and hence it makes more sense to use IIS Express for local development.



European ASP.NET 4 Hosting :: Global Exception Handling with ASP.NET

clock December 23, 2011 05:55 by author Scott

You can't debug a problem if you don't know that it exists. After you take your web application live, you are no longer the only one who is using it (hopefully), so you need an effective plan to track exceptions when they occur while others are surfing your site. A great way to do this is to implement an exception handler at the application level. This will allow you to consolidate the logging and notification parts of your exception handling in one convenient place. As you'll see from the code examples that follow, your global exception handler can handle both specific exceptions that you trap in your code and generic unhandled exceptions.

After your global exception handler has done its work, you'll want to redirect the users of your website to a friendly page that tells them that something has gone wrong, and then provide them with customer support information as well as a link back to your web application's home page.

Implementing the Application_Error Event Handler

The HttpApplication class in the System.Web namespace implements an Error event handler. This should not be confused with the HttpApplicationState class, which contains the definition for the Application object that you use in a typical ASP.NET page. You can implement this event handler in the global.asax file as shown in Listings 1 and 2.


Listing 1:
Application_Error Event Handler

<%@ Application Language="C#" %>
<%@ Import Namespace="System.Diagnostics" %>

<script language="C#" runat="server">
void Application_Error(object sender, EventArgs e)
{
   //get reference to the source of the exception chain
   Exception ex = Server.GetLastError().GetBaseException();

   //log the details of the exception and page state to the
   //Windows 2000 Event Log
   EventLog.WriteEntry("Test Web",
     "MESSAGE: " + ex.Message +
     "\nSOURCE: " + ex.Source +
     "\nFORM: " + Request.Form.ToString() +
     "\nQUERYSTRING: " + Request.QueryString.ToString() +
     "\nTARGETSITE: " + ex.TargetSite +
     "\nSTACKTRACE: " + ex.StackTrace,
     EventLogEntryType.Error);

   //Insert optional email notification here...
}
</script>

Listing 2:
Application_Error Event Handler (VB)

<%@ Application Language="VB" %>
<%@ Import Namespace="System.Diagnostics" %>

<script language="VB" runat="server">
Sub Application_Error(sender As Object, e As EventArgs)
   'get reference to the source of the exception chain
   Dim ex As Exception = Server.GetLastError().GetBaseException()

   'log the details of the exception and page state to the
   'Windows 2000 Event Log
   EventLog.WriteEntry("Test Web", _
     "MESSAGE: " & ex.Message & _
     "\nSOURCE: " & ex.Source & _
     "\nFORM: " & Request.Form.ToString() & _
     "\nQUERYSTRING: " & Request.QueryString.ToString() & _
     "\nTARGETSITE: " & ex.TargetSite & _
     "\nSTACKTRACE: " & ex.StackTrace, _
     EventLogEntryType.Error)

   'Insert optional email notification here...
End Sub
</script>

First, you have to be sure to set a reference to the System.Diagnostics namespace. You'll use the EventLog class in this namespace to write exception details to the Windows 2000 event log. Inside the Application_Error event handler, you declare an Exception object and initialize it through a call to Server.GetLastError().GetBaseException().


The GetLastError() method of the Server object simply returns a reference to a generic HttpException. This is a wrapper that was placed around the original exception when it was passed from your ASP.NET page to the Application_Error event. To get access to the original exception, you need to call its GetBaseException() method. This will yield the original exception information, regardless of how many layers have been added to the exception tree.

Next, you make a call to the WriteEntry() method of the EventLog class. There are several overloaded signatures for this method. The implementation that we chose to use here accepts three parameters. The first parameter is the source of the error. It appears in the Source field of the Windows 2000 event log viewer. The second parameter is the log data itself. You can see that we have added a lot of information to help track down what caused the exception, including the exception message, the exception source, the contents of the Form collection, the contents of the QueryString collection, the name of the method that generated the error (TargetSite), and a complete stack trace.

Note that the stack trace contains the name of the file that was the source of the exception. However, it strips off the contents of the query string—hence the need to specifically include it previously. The third and final parameter to the WriteEntry() method is an enumeration of type EventLogEntryType. We chose to use the Error element of the enumeration.

At the end of the event handler, we inserted a comment block where you can optionally put code to email the exception information to your IT support staff. Discussion of the different messaging paradigms in the .NET framework is beyond the scope of this article.

After the Application_Error event has completed its work, it automatically redirects the user of your web application to your custom error page. Optionally, however, you can use the Server.ClearError() method after you have logged the exception and redirect your user using the Server.Execute() method, specifying the page that you want to load in the user's browser.

The code that you have just implemented will capture all unhandled exceptions that occur in your web application. If you need to do some cleanup in the event of an exception and you implement structured exception handling inside your ASP.NET page, you can still leverage the global exception handler. Listings 3 and 4 present examples of how you would do it.

Listing 3: Throwing a Handled Exception

<%@ Page Language="C#" %>

<script language="C#" runat="server">
protected void button1_click(object sender, EventArgs e)
{
   try
   {
     //do some complex stuff

     //generate your fictional exception
     int x = 1;
     int y = 0;
     int z = x / y;
   }
   catch(DivideByZeroException ex)
   {
     //put cleanup code here
     throw(ex);
   }
}
</script>

<form runat="server">
   <asp:button id="button1" onclick="button1_click"
     text="click me" runat="server" />
</form>

Listing 4: Throwing a Handled Exception (VB)

<%@ Page Language="VB" %>

<script language="VB" runat="server">
Protected Sub button1_click(sender As Object, e As EventArgs)
   Try
     'do some complex stuff

     'generate your fictional exception
     Dim x As Integer = 1
     Dim y As Integer = 0
     Dim z As Integer = x / y
   Catch ex As DivideByZeroException
     'put cleanup code here
     Throw(ex)
   End Try
End Sub
</script>

<form runat="server">
   <asp:button id="button1" onclick="button1_click"
     text="click me" runat="server" />
</form>

The code in these listings defines a web form with a text box and a button. When you click the button, it fires the button1_click event handler. In the event handler, you would do processing as usual. For the purposes of this demonstration, however, you intentionally generate a DivideByZeroException. This takes you to the catch block. Here, you can perform any page-specific cleanup code before calling throw(ex) to pass your exception to the global exception handler to be logged to the Windows 2000 event log.

When the global exception handler is finished logging the error, the defaultredirect attribute that you set in your config.web file (discussed in the next section) takes over, and you are redirected to the error.aspx page to display your friendly message to the user of your web application.

Setting Up the Custom Error Page

The first step in setting up a custom error page is to modify your config.web file to route the users of your web application to a friendly error page if an exception occurs. It helps to boost users' confidence in your site when it can recover gracefully from the unexpected. Add the code in Listing 5 to the config.web file of your web application.

Listing 5: Adding the <customerrors> Tag to Your Config.web File

<configuration>
  <customerrors mode="On" defaultredirect="error.aspx" />
</configuration>

Note that your config.web file might already have a <customerrors> tag, so you might only need to modify the existing one. The mode attribute of the <customerrors> tag has three settings: On, Off, and RemoteOnly. If the mode is On, users will always be redirected to the custom error page specified by the defaultredirect attribute if an unhandled exception occurs. If the mode is Off, the details of any exception that occurs will be shown to the user in the browser. The RemoteOnly mode is a hybrid of the two other modes. If you are browsing your web application while sitting at the web server itself, it behaves like the Off mode. All other browsers of the site will get the behavior of the On mode. If no defaultredirect attribute is set, a default ASP.NET "friendly, yet not so friendly" message will be displayed to the user when exceptions occur.

Next, you need to build the custom error page (error.aspx) referenced in the config.web file. This is just an ordinary ASP.NET page that includes helpful information for the user of your web application if an error occurs. An extremely simple example is the one in Listing 6.

Listing 6: Simple Custom Error Page

<html>
<head>
<title>My web application: Error page</title>
</head>
<body>
An unexpected error occurred in the application. Please contact [ccc]
customer service at (800)555-5555. Or, you can click [ccc]
<a href="home.aspx">here</a> to go back to the homepage. [ccc]
Thank you for your patience.
</body>
</html>



European ASP.NET Hosting :: How to Set Up Your .NET Web Application to Use MySQL as Your ASP.NET Membership Provider

clock December 12, 2011 08:15 by author Scott

In this tutorial, I will show you how to setting up your .NET web application to use MySQL as your ASP.NET Membership Provider.

1. Download and install MySQL Connector/Net 5.2.1 or later version

2. Add a reference to MySQL.Web to your web application.
C:\Program Files\MySQL\MySQL Connector Net 5.2.1\Web Providers\MySql.Web.dll

3. Add the autogenerateschema=”true” attribute. Since the MySQL database schema wasn’t automatically created for me, I ended up using the autogenerateschema attribute. The attribute will signal the MySQL provider to build (or upgrade) the database schema.The MySQL 5.2.1 release notes state the following…

Using the new provider schema
=============================
For this release. the only way to upgrade a given server to the new schema is to
add a configuration option for one of your providers. The option is ‘autogenerateschema’.
By setting this to true, the provider will silently upgrade the server to the new schema.
Please note that there is no reversing of this procedure so please just do this on test
setups and not on your production systems.


Personally, I found it easiest to just add autogenerateschema=”true” to my machine.config on my development machine (as opposed to web.config) and it’s under providers…

<membership>
<providers>
<add name=”MySQLMembershipProvider” autogenerateschema=”true” ….
</providers>

Save the changes.


4. Edit your web application’s web.config.

<connectionStrings>
<remove name=”LocalMySqlServer”/>
<add name=”LocalMySqlServer” connectionString=”Datasource=localhost;Database=DB;uid=Username;pwd=Password;”
providerName=”MySql.Data.MySqlClient”/> </connectionStrings>

Then, save the changes.

5. Build your Web Application.

6. Config your web application.

Under the ASP.NET Web Site Administration Tool provider tab, click “Select a Different Provider (advanced)” and change the provider to MySQLMembershipProvider.


At this point, you should be able to use MySQL as your ASP.NET Membership and Role Provider (the tables will be automatically built for you).

After the tables are built, you’ll want to setup your web application’s web.config (using your machine.config as a template) so that you will have access to all of the membership provider settings.



About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in