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. 



About HostForLIFE

HostForLIFE 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 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Month List

Tag cloud

Sign in