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

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

ASP.NET Hosting :: Working with ASP.NET Cookies

clock January 31, 2012 09:53 by author Administrator

 

 

Introduction

Cookies are also known by many names, HTTP Cookie, Web Cookie, Browser Cookie, Session Cookie, etc. Cookies are one of several ways to store data about web site visitors during the time when web server and browser are not connected. Common use of cookies is to remember users between visits. Practically, cookie is a small text file sent by web server and saved by web browser on client machine.

Use of Cookies?

Cookies may be used for authentication, identification of a user session, user's preferences, shopping cart contents, or anything else that can be accomplished through storing text data. Cookies can also be used for travelling of data from one page to another.

Is Cookies Secured?

Well, this question has no specific answers in YES or NO. Cookies could be stolen by hackers to gain access to a victim's web account. Even cookies are not software and they cannot be programmed like normal executable applications. Cookies cannot carry viruses and cannot install malware on the host computer. However, they can be used by spyware to track user's browsing activities.

Using Cookies

Creating/Writing Cookies

There are many ways to create cookies, I am going to outline some of them below:

Way 1 (by using HttpCookies class)
//First Way
HttpCookie StudentCookies = new HttpCookie("StudentCookies");
StudentCookies.Value = TextBox1.Text;
StudentCookies.Expires = DateTime.Now.AddHours(1);
Response.Cookies.Add(StudentCookies);

Way 2 (by using Response directly)
//Second Way
Response.Cookies["StudentCookies"].Value = TextBox1.Text;
Response.Cookies["StudentCookies"].Expires = DateTime.Now.AddDays(1);


Way 3 (multiple values in same cookie)
//Writing Multiple values in single cookie
Response.Cookies["StudentCookies"]["RollNumber"] = TextBox1.Text;
Response.Cookies["StudentCookies"]["FirstName"] = "Abhimanyu";
Response.Cookies["StudentCookies"]["MiddleName"] = "Kumar";
Response.Cookies["StudentCookies"]["LastName"] = "Vatsa";
Response.Cookies["StudentCookies"]["TotalMarks"] = "499";
Response.Cookies["StudentCookies"].Expires = DateTime.Now.AddDays(1);


Reading/Getting Cookies

In the above code, I have used many ways to write or create cookies so I need to write here using all the above ways separately.

For Way 1
string roll = Request.Cookies["StudentCookies"].Value; //For First Way

For Way 2
string roll = Request.Cookies["StudentCookies"].Value;  //For Second Way

For Way 3
//For Multiple values in single cookie
string roll;
roll = Request.Cookies["StudentCookies"]["RollNumber"];
roll = roll + " " + Request.Cookies["StudentCookies"]["FirstName"];
roll = roll + " " + Request.Cookies["StudentCookies"]["MiddleName"];
roll = roll + " " + Request.Cookies["StudentCookies"]["LastName"];
roll = roll + " " + Request.Cookies["StudentCookies"]["TotalMarks"];
Label1.Text = roll;


Deleting Cookies

In the above code, I have used many ways to create or read cookies. Now look at the code given below which will delete cookies.

if (Request.Cookies["StudentCookies"] != null)
{
    Response.Cookies["StudentCookies"].Expires = DateTime.Now.AddDays(-1);    Response.Redirect("Result.aspx");  //to refresh the page
}


Understanding HttpCookie Class It contains a collection of all cookie values.

We do not need to use any extra namespaces for HttpCookies class (we already have used this in Way 1 above), because this class is derived from System.Web namespaces. HttpCookies class lets us work with cookies without using Response and Request objects (we have already used this in Way 2 and Way 3 above).

HttpCookie class has a list of some properties, let us outline them.

    * Domain: It contains the domain of the cookie.
    * Expires: It contains the expiration time of the cookie.
    * HasKeys: It contains True if the cookie has subkeys.
    * Name: It contains the name of the cookie.
    * Path: It contains the virtual path to submit with the cookie.
    * Secure: It contains True if the cookie is to be passed in a secure connection only.
    * Value: It contains the value of the cookie.
    * Values:

Limitations of Cookies

There are following limitations for cookies:
   1. Size of cookies is limited to 4096 bytes.
   2. Total 20 cookies can be used on a single website; if you exceed this browser will delete older cookies.
   3. End user can stop accepting cookies by browsers, so it is recommended to check the users’ state and prompt the user to enable cookies.

Sometimes, the end user disables the cookies on browser and sometimes browser has no such feature to accept cookies. In such cases, you need to check the users’ browser at the home page of website and display the appropriate message or redirect on appropriate page having such message to enable it first. The following code will check whether the users’ browser supports cookies or not. It will also detect if it is disabled too.

protected void Page_Load(object sender, EventArgs e)
{
    if (Request.Browser.Cookies)
    {
        //supports the cookies
    }
    else
    {
        //not supports the cookies
        //redirect user on specific page
        //for this or show messages
    }
}


It is always recommended not to store sensitive information in cookies

 

 

 



ASP.NET Hosting :: How to Connect to ASP.NET Using MySQL 5.0 - Part II

clock November 8, 2011 05:56 by author darwin

Please stay focus in the first part of this article. In this article, we will focus on taking advantage of the new support for stored procedures in MySQL 5.0. We will be building upon the example application created in Part 1, so please refer to the scripts in the previous article if you wish to create the sample database and ASP.NET application.

MySQL Stored Procedures

A stored procedure is made up of one or more SQL statements or commands and is stored within the database. Stored procedures can be used to perform any type of database operation such as retrieving one or more rows, inserting, updating, deleting data, or perhaps multiple database operations at once.


Before moving on, let’s take a look at creating a stored procedure. Launch MySQL Query Browser, connect to your versedb database, open a new Script Tab, and execute the following script.

DELIMITER $$

DROP PROCEDURE IF EXISTS `versedb`.`usp_Verse_GetList`$$
CREATE PROCEDURE `usp_Verse_GetList`()
BEGIN
  SELECT  verse_id,
          verse_text,
          verse_ref
  FROM    verse
  ORDER BY
          verse_ref DESC;
END$$

DELIMITER ;


This simple stored procedure retrieves all the rows in the verse table ordered by verse reference in descending order. To see this stored procedure in action, open a new Query Tab and execute the following command. 

CALL usp_Verse_GetList(); 

What you should see (assuming you have data in your verse table from Part 1), is a list of all the rows in your table ordered by the verse reference in descending order, just as you might expect.

One of the primary benefits of using stored procedures is that SQL statements and logic can be maintained apart from the applications that use them. So, instead of embedding SQL commands in your application, your application only needs to know how to execute the stored procedures it needs.

Stored procedures also support parameters. In this way, a single stored procedure can be used in many scenarios without having to be modified. For example, you can create a stored procedure that can retrieve a single row in your table based upon a primary key value passed as a parameter.

DELIMITER $$

DROP PROCEDURE IF EXISTS `versedb`.`usp_Verse_Get_By_Id`$$
CREATE PROCEDURE `usp_Verse_Get_By_Id`(v_id INT)
BEGIN
  SELECT  verse_id,
          verse_text,
          verse_ref
  FROM    verse
  WHERE   verse_id = v_id;
END$$


To see the stored procedure in action, execute the following command.

CALL usp_Verse_Get_By_Id(2);

What you should see is a single row returned from the database where the verse_id field is equal to 2. To retrieve a different row, you would simply replace the value 2 with a different valid primary key value. If you specify a value that does not exist in the table, then no rows would be returned.

A couple more things to mention: it is possible to define output parameters as well as for input, and stored procedures do not have to return any rows. We will look at an example of both in a later article, but imagine the scenario of creating a stored procedure to insert a new row into a table. You might pass the values for the row as input parameters, return the new primary key ID assigned to the inserted row as an output parameter, and would not need to return any rows of data.

Calling MySQL Stored Procedures from ASP.NET


Executing a stored procedure using ASP.NET is nearly identical to executing straight SQL. Unless a procedure requires parameters, you only need to provide the name of the stored procedure in the command text, and specify the CommandType property is of type StoredProcedure

// Get the MySQL connection string stored in the Web.config
string cnnString = ConfigurationSettings.AppSettings["ConnectionString"];

// Create a connection object and data adapter
MySqlConnection cnx = new MySqlConnection(cnnString);
MySqlDataAdapter adapter = new MySqlDataAdapter();

// Create a SQL command object
string cmdText = "usp_Verse_GetList";
MySqlCommand cmd = new MySqlCommand(cmdText, cnx);

// Set the command type to StoredProcedure
cmd.CommandType = CommandType.StoredProcedure;

// Create and fill a DataSet
DataSet ds = new DataSet();
adapter.SelectCommand = cmd;
adapter.Fill(ds);

One difference you might notice from the previous article is retrieving the connection string from the web.config using ConfigurationSettings.AppSettings
, which is typically best practice. If you are not familiar with this technique, you would simply create an block in your web.config that looks like the following

<appsettings>
  <add key="ConnectionString" value="Server=localhost;Port=3306;Database=versedb;Uid=root;Pwd=mySecret" />
  </add>
</appsettings>


You would need to add the section directly after and before. If you already have an section defined, you only need to insert the node for the connection string.

Executing Stored Procedures with Parameters

To execute a stored procedure with parameters, you must create and add a
MySqlParameter object to the MySqlCommand.Parameters collection for each required parameter.  Also, parameter names in MySQL use a prefix of "?" which is similar to Microsoft SQL Server's use of "@."


// Hard-coding the Verse ID for example only
int verseID = 2;

// ...Code to create connection goes here...

// Create a SQL command object
string cmdText = "usp_Verse_Get_By_Id";
MySqlCommand cmd = new MySqlCommand(cmdText, cnx);

// Set the command type to StoredProcedure
cmd.CommandType = CommandType.StoredProcedure;

// Create the verse ID parameter
MySqlParameter param;
param = new MySqlParameter("?v_id", MySqlDbType.Int32);
param.Value = verseID;
param.Direction = ParameterDirection.Input;
cmd.Parameters.Add(param);

// ...Code to build DataSet goes here...


Of course, you would probably wrap all of this code in a method that takes a verseID as a parameter and returns a DataSet or DataRow

Summary

In summary, you might think of stored procedures as a public method exposed by your database that encapsulates your SQL code. You can make any change to the stored procedure’s code, and as long as the name of the procedure and its parameters, if any, do not change (in other words, the “method signature” to continue our illustration), there would be no need to modify your ASP.NET application.

Hopefully this gives you a starting point for using MySQL stored procedures.  However, we have only begun to scratch the surface of this very powerful feature.  In the future, we will look at creating more complex stored procedures, and using stored procedures to insert, update, and delete data in your database.



ASP.NET Hosting :: How to Connect to ASP.NET Using MySQL 5.0 - Part I

clock November 8, 2011 05:31 by author darwin

In this series of articles, I want to introduce you to using MySQL 5.0 with ASP.NET.  I hope to cover the most common uses for MySQL, as well as take advantage of some of the new features in version 5.0.  To do this, we will look at creating a database of Bible verses and ASP.NET pages to view and manage the verses.

To begin development, you will need to have the following tools. 

Required Components:

-
.NET Framework 1.0 or higher

-
MySQL 5.0 database server
-
MySQL Connector/Net 1.0.6 or higher

Optional Components:

-
MySQL Query Browser 1.1.15 or higher
-
MySQL Administrator 1.1 or higher
-
Visual Studio 2002 or higher

MySQL database server comes with command-line utilities to administer and develop MySQL.  However, MySQL Query Browser and MySQL Administrator are great utilities that will make your life much easier.  Visual Studio is not required, but certainly makes developing ASP.NET applications much easier.  Alternatively, you can use the free ASP.NET Web Matrix or simply create your ASP.NET web pages using any text editor. 

Installing each of these components is outside the scope of this article.  Please refer to the documentation provided with each for installation and configuration instructions.

Setting up the Database

Here are the scripts you’ll need to create the verse schema (database).  To execute the scripts, you’ll need to use the mysql command line utility or MySQL Query Browser application.

CREATE DATABASE versedb;
CREATE TABLE `verse` (
  `verse_id` int(10) unsigned NOT NULL auto_increment,
  `verse_text` varchar(1024) NOT NULL default '',
  `verse_ref` varchar(50) NOT NULL default '',
  PRIMARY KEY  (`verse_id`)
)


As you can see, we are going to work with just a single table named verse to start with.  Before we can get data out of MySQL, obviously we have to put some data in.  Use the following scripts to add two verses to the table.

INSERT INTO `verse` (`verse_text`,`verse_ref`) VALUES
  ('And God is able to make all grace abound to you, so that in all things
  at all times, having all that you need, you will abound in every good work.',
  '2 Corinthians 9:8'),
  ('Whatever you do, work at it with all your heart, as working for the
  Lord, not for men, since you know that you will receive an inheritance from
  the Lord as a reward. It is the Lord Christ you are serving.',
  'Colossians 3:23-24');


Setting Up the Web Site

This article assumes you will set up a virtual directory on your local computer or you will upload the examples to a Web host that supports ASP.NET.  Setting up the test web site locally is outside the scope of this document.  If you plan to develop and debug ASP.NET on your local computer and are not already familiar with setting up Internet Information Server (IIS) or creating virtual directories, you can use the links provided on the Online Resources page to find tutorials that cover this subject.

Connecting to MySQL from ASP.NET

As mentioned before, you will need to download and install the MySQL Connector/Net ADO.NET library.  Once you’ve added the MySql.Data.dll assembly as a reference to your project or placed it in your /bin folder, you are ready to start writing code to access MySQL.  Here is an example of connecting to MySQL and retrieving all of the rows from the verse table into a DataSet.

// Connection string for a typical local MySQL installation
string cnnString =
"Server=localhost;Port=3306;Database=versedb;Uid=root;Pwd=MySecretPassword";

// Create a connection object and data adapter
MySqlConnection cnx = new MySqlConnection(cnnString);
MySqlDataAdapter adapter = new MySqlDataAdapter();

// Create a SQL command object
string cmdText = "SELECT * FROM verse";
MySqlCommand cmd = new MySqlCommand(cmdText, cnx);

// Create a fill a Dataset
DataSet ds = new DataSet();
adapter.SelectCommand = cmd;
adapter.Fill(ds);

// Bind the DataSet
// ... Place your databinding code here ...

If you’re already accustomed to data binding in .NET, you should immediately recognize the similarities.  The only difference is you use the MySqlXxx classes instead of the OleDbXxx or SqlXxx classes. 


Hello World…

The following code provides a simple yet complete example of connecting to MySQL and displaying the data retrieved from the database.  To use this code, add a new Web Form (.aspx) to your ASP.NET project, copy and paste, change the connection string to match your MySQL database user name and password, and save.

<%@ Page language="c#" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="MySql.Data.MySqlClient" %>
<html>
<head>
<script runat="server" type="text/javascript">
void Page_Load(object sender, EventArgs e)
{
  if (!IsPostBack)
  {
    BindVerses();
  }
}

private void BindVerses()
{
  try
  {
    // Connection string for a typical local MySQL installation
    string cnnString =
"Server=localhost;Port=3306;Database=versedb;Uid=root;Pwd=myPassword";

    // Create a connection object and data adapter
    MySqlConnection cnx = new MySqlConnection(cnnString);
    MySqlDataAdapter adapter = new MySqlDataAdapter();

    // Create a SQL command object
    string cmdText = "SELECT * FROM verse";
    MySqlCommand cmd = new MySqlCommand(cmdText, cnx);

    // Create a fill a Dataset
    DataSet ds = new DataSet();
    adapter.SelectCommand = cmd;
    adapter.Fill(ds);

    // Bind the DataSet
    VerseRepeater.DataSource = ds;
    VerseRepeater.DataBind();
  }
  catch (Exception ex)
  {
    lblError.Text = ex.Message;
  }
}
</script>

<title></title>    
<style type="text/css">
  body { font-family:Verdana, Arial, Sans-Serif; font-size:small; }
  h1, h2, h3, h4, h5 { font-family:Trebuchet MS, Verdana, Arial, Sans-Serif;
}
  input, textarea { font-family: Verdana, Arial, Sans-Serif; font-size:small;
}
  .Error { font-weight:bold; color:#c00; }
  .VerseList { width:400px; }
  .VerseHeader {
    padding:5px;
    border:1px solid #999;
    background-color:#ddd;
    font-weight:bold;
  }
  .VerseText {
    font-family: Trebuchet MS, Verdana, Arial;
    font-size: small;
    padding:5px 5px 0px 5px;
    border-left:1px solid #999;
    border-right: 1px solid #999;
  }
  .VerseRef {
    font-family: Arial, sans-serif;
    font-style:italic;
    font-size: x-small;
    text-align:right;
    padding:5px 15px 0px 5px;
    border-left:1px solid #999;
    border-right: 1px solid #999;
    border-bottom:1px solid #ccc;
  }
  .VerseFooter {
    border-left:1px solid #999;
    border-right: 1px solid #999;
    border-bottom:1px solid #999;
}
</style>
</head>
<body>

  <form runat="server" method="post" id="Form1">
    <p><asp:label cssclass="Error" enableviewstate="False" runat="server"
id="lblError"></asp:label></p>
    <div class="VerseList">
      <asp:repeater runat="server" id="VerseRepeater">
        <headertemplate>
          <div class="VerseHeader">Verse List</div>
        </headertemplate>
      
        <itemtemplate>
          <div class="VerseText"><%# DataBinder.Eval(Container.DataItem, "verse_text") %></div>
          <div class="VerseRef">--
            <%# DataBinder.Eval(Container.DataItem, "verse_ref") %>
          </div>
        </itemtemplate>
        <footertemplate>
          <div class="VerseFooter"><img width="1" height="2" alt="" src="images/pixel.gif" /></div>
        </footertemplate>
      </asp:repeater>
    
    </div>
  </form>
</body>
</html>



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

clock October 31, 2011 07:43 by author Administrator

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

Application pool settings

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

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

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

- memoryLimit
- requestLimit
- timeout

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

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

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

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

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

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

File Change Notification

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

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

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

Workaround for the sub-directory issue

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

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

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

Is recycling the application pool good or bad?


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



ASPHostCentral.com - The Importance of having a UNIQUE IP Address on your Website!

clock October 14, 2011 08:07 by author Administrator

What is an IP address?

An IP address is a set of 4 numbers assigned to each device on a computer network. When we apply this definition for the internet, the IP address can be considered a numerical representation of a website address. For example, the domain google.com would go to the IP address 73.14.213.99.

How do IP addresses work?

When you type in a domain name on your browser, your browser will first match that domain name to an IP address. Then, it will access the server at that IP address.

Why would you want a unique IP address for your website?

Websites that have unique IP addresses are more stable and more reliable.

Disadvantages of sharing an IP address:
Sharing an IP address = Higher chance of website outage

Most web hosting providers nowadays cram thousands of websites onto one server. And because IP addresses are in short supply, they will often have all of the websites that are on a server share one IP address. This practice is quite dangerous as it will jeopardize the stability and functionality of each website on the server.

If your website is sharing an IP address with 1,000 other websites on a server and one of those websites becomes blocked or blacklisted, all 1,000 of those websites, including yours, would be blocked or blacklisted as well.

Advantages of having a unique IP address:
Having a unique IP address = Increased stability and reliability for your website.

By having your own unique IP address, your website would be unaffected by the other websites that are on the same server. If a website on your server gets its IP address blocked or blacklisted, it would not affect your website since it's not sharing the same IP address.

In other words, when you have a unique IP address, your website is unaffected by the other websites that are on the server.

The internet is running out of space

The current IPv4 address pool is almost completely used up.

It was announced in early 2011 that the last batch of IP addresses have been allocated. This last batch of IP addresses will probably be used up towards the end of 2011. The current IPv4 address system has about 4.3 billion addresses. With a growing pool of internet users and internet-connected devices, 4.3 billion IP addresses are not enough to meet today's demand.

Fortunately, researchers have designed a new IP address system - IPv6. This new system has 360 undecillion IP addresses and has been available since 1999. But, it seems like the transition is slow, and we'll be stuck with IPv4 for a while. Here's why:

- Transitioning 4.3 billion IP addresses over to the new IPv6 system will take quite some time.
- Existing equipment will need to be upgraded in order to support the new IPv6 address system.
- Not many Internet Service providers (ISP) support IPv6. This means that if your ISP doesn't support IPv6, then you won't be able to access websites hosted with IPv6 addresses.
- Currently, IPv4 addresses are accessible through all ISP's, whereas IPv6 addresses are not.
With that said, the value of the existing IPv4 addresses are likely going to shoot up before IPv6 comes into play. So, make sure you get your IPv4 address before they run out!



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

clock October 10, 2011 11:16 by author Administrator

 

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

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

 




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

clock September 13, 2011 06:59 by author Administrator

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

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

A couple examples of what NOT to do

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

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

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

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

Manual serialization, using JavaScriptSerializer

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

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

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

What actually happens

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

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

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

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

But, what it actually returns is this:

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

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

Using DataContractJsonSerializer or Json.NET is no better

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

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

The impact this mistake has on the client-side

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

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

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

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

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

Flipping the script (and the JSON)

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

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

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

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

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

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

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

Doing it right

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

Returning an object

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

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

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

Accepting an object from the client-side

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

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

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

 



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

clock August 23, 2011 07:57 by author Administrator

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

Before we start lets define both the terms:

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

Limitation of UserControl :

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

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

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

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

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

Limitation :

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

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

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

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

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

Happy Coding.



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

clock July 4, 2011 08:35 by author Administrator

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

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

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

It’s a simple 3 process step!

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



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



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

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

 

 

 

 



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

clock March 25, 2011 09:22 by author Administrator

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

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

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

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

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

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

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

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

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

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



ASP.NET 4.0 & ASP.NET 4.5 Hosting

 

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

 

Calendar

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

View posts in large calendar

Sign in