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

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

ASP.NET 4 Hosting - ASPHostPortal :: Using HttpHandlers and HttpModules in your ASP.NET Websites

clock June 29, 2011 07:30 by author Jervis

Introduction

In this article I would explain about HttpModules and HttpHandlers and how to use it on your Website.
Sometimes, just creating dynamic Web pages with the latest languages and
databases just does not give you , the developer enough control over an application. At times, you need to be able to dig deeper and create applications that can interact with the Web Server itself. You want to be able to interact with the low level processes such as how the Web Server processes incoming and outgoing HTTP requests.

Before ASP.NET, in order to get this level of control using IIS, you were forced to create ISAPI extensions or filters. This proved to be quite daunting and painful task for many developers because creating ISAPI extensions and filters required knowledge of C/C++ and knowledge of how to create native Win32 DLLs. Thankfully, in .NET world, creating these types of low level applications is really no more difficult than most other tasks you would normally perform.


HttpModules

HttpModules are simple classes that can plug themselves into the request processing pipeline. They do this by hooking into a handful events thrown by the application as it processses the HTTP request. To create an HttpModule, you simply create a class that derives from the System.Web.IHttpModule interface. This interface requires you to implement two methods: Init and Dispose. The code snippet below will show you how to implement the methods.

Code in VB.NET

    Imports Microsoft.VisualBasic

   Imports System.Web



   Public Class SimpleHttpModule Implements IHttpModule


       Public Overridable Sub Init(ByVal context as HttpApplication) _

              Implements IHttpModule.Init

       End Sub


       Public Overridable Sub Dispose() Implements IHttpModule.Dispose

       End Sub

   End Class


Code in C#

    using System;

   using System.Web;



   public class SimpleHttpModule :IHttpModule {

       public void Dispose() {

       }     



       public void Init(HttpApplication context) {

       }

   }


The Init Method is the primary method that you use to implement the functionality. Notice that it has single method parameter named HttpApplication object named context. The parameter gives you access to the current HttpApplication context and it is what you use to wire up the different events that fired during the request processing.

Below is the list of the important EventName that you can use with the HttpApplication object.
1. AcquireRequestState.
Raised when ASP.NET runtime is ready to acquire the SessionState of the current Http request

2. AuthenticateRequest.
Raised when ASP.NET runtime is ready to authenticate the identity of the user.

3. AuthorizeRequest
Raised when ASP.NET runtime is ready to authorize the user for the resources user is trying to
access.

4. BeginRequest
Raised when ASP.NET runtime receivess a new HTTP request.

5. End Request
Raised just before sending the response content to the client


Simple Example using HTTPModule


The example below will showsyou how to modified the HTTP output stream before it get sent to the client. This can be a simple and useful tool if you want to add text to each page served from your Website but do not want to modify each page.

Code in VB.NET


    Public Class SimpleHTTPModule Implements IHttpModule

       Dim WithEvents oApps as HttpApplication = Nothing



       Public Overridable Sub Init(ByVal context as HttpApplication) _

           Implements IHttpModule.Init

           oApps = context

       End Sub  



       Public Overridable Sub Dispose() Implements IHttpModule.Dispos

       End Sub     



       Public Sub_context_PreSendRequestContent(ByVal sender As Object,_

                  ByVal e as EventArgs) Handles oApps.PreSendRequestContent

            Dim message as String = ""


            oApps.Context.Response.Output.Write(message);

       End Sub


   End Class


Code in C#

     public class SimpleHTTPModule : IHttpModule

    {

         private HttpApplication oApps = null;


         public void Dispose() {


         }


         public void Init(System.Web.HttpApplication context) {

             oApps = context;

             context.PreSendRequestContent += new EventHandler

             (context_PreSendRequestContent);

         }


         void context_PreSendRequestContent(object sender,EventArgs e) {

              string message = "<!-- This page is being processed at " +

              System.DateTime.Now.ToString() + " -->"


              oApps.Context.Response.Output.Write(message);

         }

    }


You can see from the code snippet above, we are using PreSendRequestContent event. This event fires right before the content is sent to the client and you have the last opportunity to modify it.

In the PreSendRequestContent handler method, you simply create a string containing an HTML comment that contains the current time. You take this string and write it to the current HTTP requests output stream. The Http request is then sent back to the client.

In order to use this module, you must let ASP.NET know that you want to include this module in the request pipeline. You can add the httpmodule section by modifying your web.config file.


     <system.web>

        <httpModules>

            <add name="SimpleHTTPModule" type="SimpleHTTPModule,App_code"/>

        </httpModules>

    </system.web>


The generic format of the httpModules in your web.config file is

     <system.web>

        <httpModules>

            <add name="modulename" type="namespace.classname,assemblyname"/>

        </httpModules>

    </system.web>


If you have created your HttpModule in the App_code directory of an ASP.NET project, you might wonder how you know the assemblyname value should be,considering ASP.NET 2.0 now dynamically compiles your code at runtime. The solution is to use the text App_code as the assembly name. This tells ASP.NET that your module is located in the dynamically located assembly.

You can also create HttpModules as a separate class library project in which case you simply use the assembly name of the library.

After you have added this section on your web.config file, try to run any file of your web project and view source the generated aspx file. You should be able to see the commented date time as we previously
coded in the http modules.

HttpHandlers

HttpHandlers differ from HttpModules not only because of their
positions in the request processing pipeline, but also because they must be mapped to a specific file extensions. HttpHandlers are the last stop for the incoming Http requests and are ultimately the point in the request processing pipeline that is responsible for serving up the requested content, be it in ASPX page,HTML,plain text or an image. Additionally HttpHandlers can offer significant performance gains.

In this arcticle, I will demonstrate two different ways to create a simple HttpHanlder that you can use to serve up dynamic images. First you look at creating an HttpHanlder using an ASHX file extension. Then you learn how you get even more control by mapping your HttpHandler to a custom file extension using IIS.

Generic Handlers
In Visual Studio 2005, Microsoft has introduced new template specifically for HttpHandler and it ends with .ashx extension. The .ashx extension is the default HttpHander file extension set up by ASP.NET.

Remember that HttpHandlers must be mapped to a unique file extensions. But luckily in asp.net 2.0, they have .ashx file extension that specifically created for HttpHandler purpose. This will save you heaps of time configuring and adding new file extension on your web.project

Outputting an image from HttpHandler


<@ WebHandler Language="VB" Class="Handler"/>

Imports System.Web


Public Class Handler:Implements IHttpHandler


   Public Sub ProcessRequest(ByVal context as HttpContext) _

            Implements IHttpHandler.ProcessRequest

         context.Response.ContentType = "image/jpeg"

         context.Response.WriteFile("Sunset.jpg")

   End Sub 


   Public ReadOnly Property IsReusable() As Boolean _

          Implements IHttpHandler.IsReusable

        Get

            Return False

        End Get

   End Property

End Class


<@ WebHandler Language="C#" Class="Handler"/>

using System.Web

    public class Handler:IHttpHandler {

         public void ProcessRequest(HttpContext context) {              

             context.Response.ContentType = "image/jpeg";

             context.Response.WriteFile("Sunset.jpg");

    }

    public bool IsReusable {

        get{

           return false;

        }

    }

}


As you can see, simply change the ContentType method to image/jpeg to indicate that you are returning JPEG image, then you use the WriteFile() method to write an image file to the output stream.

To use the handler, you can directly called the .ashx file from your html code

Conclusion


The article above is basically an introduction to the HttpHandler and HttpModules. Lots of ASP.NET developers until now never use and never heard about HttpHandlers and HttpModules. The reason is because they keep applying the old way and old technology from Classic ASP 3.0. You can do the similar thing without the need of using HttpHandler and HttpModules. However using HttpHandler and HttpModules allow your website to be more manageable, extensible and less code written in your presentation layer. You encapsulate all the logic inside the HttpHandler and HttpModules. Thats all for now. Happy programming !

Reasons why you must trust ASPHostPortal.com

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

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

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



ASP.NET 4 Hosting - ASPHostPortal :: How to Backup and Restore Database in ASP.NET

clock June 27, 2011 08:00 by author Jervis

Introduction

Sometimes we need to provide backup and restore facility in ASP.NET application in application's control panel. In this article, I am going to explain how to develop a database backup and restore application in ASP.NET. I have taken example of SQL Server in this article however, this application can be used to backup and restore any database that .NET supports. You just need to change their provider instead of System.Data.SqlClient and a single SQL Statement to list the table names of the database. I will explain them in details later in this article.

My Backup and Restore web application looks like below:



Let us develop this application in few easy steps.

1. Create a UI for database backup and restore

In this step, let us create a simple UI in ASP.NET to list all the database tables in the ListBox control that let the end user select the table to take backup and restore. Also put two buttons named Backup and Restore to do its respective functionality. My code for above UI looks like below:

<form id="form1" runat="server">
<div>
<table cellpadding="2" cellspacing="1" border="1" style="border-collapse: collapse;">
<tr>
<th style="background-color:#e0e0e0;">
Backup and Restore SQL Server
<br />
database using ASP.NET</th>
</tr

<tr>
<td align="Center">
List of Tables</td>
</tr

<tr>
<td align="Center">
<asp:ListBox ID="ListBox1" Rows="10" runat="Server" DataTextField="table_name" DataValueField="table_name">
</asp:ListBox>
</td>
</tr

<tr>
<td align="Center">
<span onclick="return confirm('Are you sure to backup selected table?')">
<asp:Button ID="btnBackup" runat="Server" Text="Backup" OnClick="BackUpNow" />
</span>
<span onclick="return confirm('Are you sure to restore selected table?')">
<asp:Button ID="btnRestore" runat="Server" Text="Restore" OnClick="RestoreNow" />
</span>
</td>
</tr>
</table> 

<asp:Label ID="lblMessage" runat="Server" EnableViewState="False" ForeColor="Blue"></asp:Label

</div>
</form>

2. Populate the database table in the ListBox control

In this step, we will write method that will populate all database tables in the ListBox control that will let the end user select the table to perform Backup or Restore. My code looks like below:

string connStr = ConfigurationManager.AppSettings["DatabaseToBackup"].ToString(); 

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
PopulateDatabaseTables();
}
}
/// <summary>
/// Populate database tables first
/// </summary>
private void PopulateDatabaseTables()
{
string tableName = string.Empty;
string sql = "SELECT *, name AS table_name " +
" FROM sys.tables WHERE Type = 'U' ORDER BY table_name";
using (SqlConnection conn = new SqlConnection(connStr))
{
using (DataTable table = new DataTable())
{
conn.Open();
using (SqlDataAdapter dAd = new SqlDataAdapter(sql, conn))
{
dAd.Fill(table);
}
ListBox1.DataSource = table;
ListBox1.DataBind();
}
}
}

You can notice in the above code snippet, I am calling a method named PopulateDatabaseTables() in the Not IsPostBack condition under Page_Load event that will populate all the tables of the database in the ListBox control. Notice the select statement that has been stored into sql variable. This select statement varies between databases to databases. To list all the tables in SQL Server database, you need to use above select statement. To list all the tables of the MySQL database, you need to write "show tables" in place of above select statement. Of course, you need to change the provider as well to connect to the MySQL database.

3. Code for taking backup of the selected table

In this step, we shall write code to take backup of the selected table when Backup button will be clicked. You can see that in OnClick event of the Backup button, I have specified BackupNow method. Let us see the code for this method.

/// <summary>
/// Backup the selected table
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void BackUpNow(object sender, EventArgs e)
{
string tableName = ListBox1.SelectedValue;
using (DataSet dSetBackup = new DataSet())
{
using (SqlConnection conn = new SqlConnection(connStr))
{
using (SqlDataAdapter dAd = new SqlDataAdapter("select * from " + tableName, conn))
{
dAd.Fill(dSetBackup, tableName);
}
}
dSetBackup.WriteXml(Server.MapPath("~/backup/" + tableName + ".xml"));
lblMessage.Text = "Backup for table <b>" + tableName + "</b> successful!";
}
}

In the above code snippet, I have got the selected table name form ListBox in the tableName variable. Selected all records from that table and filled into a DataSet named dSetBackup. Later on I used WriteXml method of DataSet to write the contents of the selected table in an xml file. The name of the xml file will be the table name in my case and will be placed in the backup folder. Then I have written a success message. This way your end user will be able to take backup of all the tables in the database.

4. Code for restoring selected table

In this step, we shall see how to restore a selected table into the database once the Restore button will be clicked. Notice the Restore button where I have specified RestoreNow method in the OnClick event. The code for this method looks like below:

/// <summary>
/// Restore the selected table
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void RestoreNow(object sender, EventArgs e)
{
string
restoreConnStr =
ConfigurationManager.AppSettings["RestoreConnStr"].ToString();

string tableName = ListBox1.SelectedValue;
using (SqlConnection conn = new SqlConnection(restoreConnStr))
{
using (DataSet dSetBackup = new DataSet())
{
// get the schema of the selected table from the database to restore
using
(SqlDataAdapter dAd = new SqlDataAdapter("select * from " + tableName,
conn))

{
     // Following line will get the schema of the selected table in the dSetBackup DataSet
     dAd.Fill(dSetBackup, tableName); 

// get the data for selected table from backed up XML file
using (DataSet dSet = new DataSet())
{
dSet.ReadXml(Server.MapPath("~/backup/" + tableName + ".xml"));
// Loop through all rows of the selected table and add into dSetBackup DataSet
foreach (DataRow row in dSet.Tables[0].Rows)
{
dSetBackup.Tables[0].NewRow();
dSetBackup.Tables[0].Rows.Add(row.ItemArray);


// Create a command builder to update dSetBackup DataSet
SqlCommandBuilder cmd = new SqlCommandBuilder(dAd); 

// Following update command will push all added rows of dSetBackup DataSet into the database
dAd.Update(dSetBackup, tableName); // We are done !!!
}
}
lblMessage.Text = "Restore of table <b>" + tableName + "</b> successful!";
}
}
}

Please note that in order to above code snippet work, you must have the schema in place into the Restore database. This schema must match the original database schema from which you had taken backup otherwise your restore will not work.

In the above code snippet, I am first getting the connection string of the database where we need to restore the data. Then I am getting the schema of the selected table into the dSetBackup DataSet using dAd (SqlDataAdapter), as there will not be any row into the restore database, so it will only give the schema of the table. This will help us to push the backed up data into this DataSet. In the next line, I have read the backed up xml of the table using ReadXml method of the DataSet that will get all the backed up data for that table into the dSet DataSet. In next line, I am looping through every rows of the dSet DataSet table and adding them into our dSetBackup DataSet. Next, I have created a SqlCommandBuilder object for the SqlDataAdapter. This will internally build insert, update, delete statement for the dSetBackup DataTable. In the following line, I have used dAd.Update (SqlDataAdapter update method) to push the data into the restore database. At last I am writing the success message. Simple! Isn't it?

Reasons why you must trust ASPHostPortal.com

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


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

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



ASP.NET Ajax Hosting - ASPHostPortal :: How to Fix Element 'ScriptManager' is not a known element in ASP.NET AJAX

clock June 24, 2011 07:42 by author Jervis

This is brief tutorial about how to fix Element ‘ScriptManager’ is not known element.

Change this in your web.config:

<controls>
        <add tagPrefix="asp" namespace="Microsoft.Web.UI" assembly="Microsoft.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
        <add tagPrefix="asp" namespace="Microsoft.Web.UI.Controls" assembly="Microsoft.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
        <add tagPrefix="asp" namespace="Microsoft.Web.Preview.UI" assembly="Microsoft.Web.Preview"/>
        <add tagPrefix="asp" namespace="Microsoft.Web.Preview.UI.Controls" assembly="Microsoft.Web.Preview"/>
</controls>


To this:

<controls>
        <add tagPrefix="ajax" namespace="Microsoft.Web.UI" assembly="Microsoft.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
        <add tagPrefix="ajax" namespace="Microsoft.Web.UI.Controls" assembly="Microsoft.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
        <add tagPrefix="ajax" namespace="Microsoft.Web.Preview.UI" assembly="Microsoft.Web.Preview"/>
        <add tagPrefix="ajax" namespace="Microsoft.Web.Preview.UI.Controls" assembly="Microsoft.Web.Preview"/>
 </controls>


Hope it helps. Please note I use the CTP web.config configuration.

Reasons why you must trust ASPHostPortal.com

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

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

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



ASP.NET 4 Hosting - ASPHostPortal :: How to Send Email with Gmail SMTP

clock June 16, 2011 07:11 by author Jervis

We frequently see questions about sending emails using .Net in the asp.net forums. The process of sending mail is the same for Windows apps and asp.net websites as the same .Net classes are used. The process can be slightly shortened by specifying default SMTP settings in the web.config or app.config file. Here, I’m showing the full version of the code and it does not rely on any configuration settings. The code also specifies unicode encoding for the subject and body.

using System.Net.Mail;
using System.Net;


//Create the mail message

MailMessage mail = new MailMessage();
mail.Subject = "Subject";
mail.Body = "Main body goes here";


//the displayed "from" email address
mail.From = new System.Net.Mail.MailAddress(
[email protected]); 

mail.IsBodyHtml = false;
mail.BodyEncoding = System.Text.Encoding.Unicode;
mail.SubjectEncoding = System.Text.Encoding.Unicode;
//Add one or more addresses that will receive the mail
mail.To.Add("[email protected]");


//create the credentials
NetworkCredential cred = new NetworkCredential(
"[email protected]", //from email address of the sending account
"password"); //password of the sending account


//create the smtp client...these settings are for gmail
SmtpClient smtp = new SmtpClient("smtp.gmail.com");
smtp.UseDefaultCredentials = false;
smtp.EnableSsl = true;


//credentials (username, pass of sending account) assigned here
smtp.Credentials = cred; 
smtp.Port = 587;


//let her rip
smtp.Send(mail);


Hope it helps!

This is another tutorial how to send email from ASP.NET 4.

Reasons why you must trust ASPHostPortal.com

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


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

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



ASP.NET 4 Hosting - ASPHostPortal :: Tutorial - How to Create Chart Control in ASP.NET 4.0

clock June 15, 2011 07:49 by author Jervis

This tutorial will teach you how to Create a Chart Control in ASP.NET 4.0

Creating a basic Chart Control in ASP .NET 4.

The purpose of this tutorial is to explain how to create a simple chart control and have it grab data
from a database. We will create a very simple Table inside our database that will show the productivity
of an imaginary worker. We will then display them on a chart for a better view of how he/she is doing.

For a More Basic Overview of Databases and ASP.NET go
Here

Overview

1. Create the database and table
2. Create the column chart control
3. Tweaking the chart

Create the Database and Table

1. Right click on your project in solution explorer and navigate to à Add à
New Item
2. Select SQL Server Database from the windows that pops up
3. Name the Database Productivity.mdf
4. Open it by double click
5. Add two new columns to your table WeekID(int) and ItemsDone(int)

6. Make the WeekID column is a Primary Key for the table right click on the WeekID column and navigate toà
Set Primary Key
7. Now we can set the identity of the key so that it auto increments itself, so switch (Is Identity) to Yes.

8. Add data to the table so save the table and name it Employee1
9. Right Click on the Employee1 and Navigate to à Show Table Data
10. Now fill out the table to reflect the Data I have filled in below. Once this is complete we are finished Creating the SQL Table and we can then move on to creating a Chart Control.


Create a Column Chart Control

In Order to create a Chart Control we have to have a Page to put it on so let's start with that


1. Right Click on your project and navigate to ->Add->New Item
2. Select Web Form and Name it PayRoll.aspx
3. Open up the page and go to Design View
4. Then we need to go to the Toolbar and Drag a Chart Item from the Data Section of the Toolbox onto our Web Form. This will create a Chart Control, but we need to link it to the database on order for it to get our information.
5. Next we need to click the Smart Tag of our object found here

6. Choose New Data Source from the Data Source Drop Down Box
7. This will bring up a wizard that will let you connect your database to your Chart
                a. On the first Window Choose SQL Database and Name it Employee1
                b. Choose your Connection String or have it create one for you I named mine ConnectionString    
                c. On the window where you select columns you should have the * selected
                 which means all data this is fine
                d. On the final window you can choose to click the Test Query button and you should see
                 these results after a few seconds, if so hit Finish and you are done with linking the Chart
8. After this Click on the Chart's Smart Tag one more time and edit the x Value Member and Y Value Member drop down boxes to appear as below

9. At this point you should be able to run the page and see your chart with all of the data

Tweaking the Chart

Notice that when you view the chart it has no text or labels on it, it could confuse some people so let's put some labels on there for the end user.


1. Right Click on the Chart and navigate to ->Properties
2. Select the Chart Areas Property under Chart and click the ellipses button(...) next to the word (Collection)
3. Then select the ellipses button next to the Axes property on the new popup window
4. This will bring us to where we can add labels for our AxesChange the Label Property Of the X Axis to say Weeks and Change the Label Property of the Y axis to say Items Done.
5. One more step to add a Table Title will Make it look even better so Go back to the Chart Properties and select the ellipses button next to the Titles Property
6. Click the Add button at the bottom Then change the (Text) property to say Productivity of Employee1 Over 7 Weeks
7. Now your table should look much better when you Load the Page

Reasons why you must trust ASPHostPortal.com

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


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

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



ASP.NET 4 Hosting - ASPHostPortal :: How to Fix "PageHandlerFactory-Integrated" bad module "ManagedPipelineHandler in IIS7

clock June 3, 2011 05:58 by author Jervis

After setting up a new Windows 7 computer with IIS 7.5 and Visual Studio 2010, I tried to start my ASP.NET 4.0 website using the Local IIS web server.  However, right off the bat I was hit with the following IIS error message:

HTTP Error 500.21 - Internal Server Error

Handler "PageHandlerFactory-Integrated" has a bad module "ManagedPipelineHandler" in its module list.

I knew the website worked correctly, because it ran fine in the Visual Studio Development Server, just not in IIS 7. Apparently, the reason I was recieving the Internal Server error message was that I had installed SQL Server 2008, after installing Visual Studio 2010, and because of this it corrupted the IIS Machine level configuration files ("If you install VS2010 and then install VS2008 and VS2008 SP1, the configuration files for ASP.NET in IIS only include about 1/2 of the correct .Net 4.0 configuration sections." read more
here). 

To repair this problem I ran a full silent repair of the .NET Framework 4.0.   Here's how on either a 32 bit or 64 bit computer:

1. Click Startà All Programsà Accessoriesà
Run
2. In the Open textbox paste in the following line (see list of all .NET Framework version install, repair and unistall command lines
here):

For silent repair on 32 bit computer with .Net Framework version 4.0.30319 use

%windir%\Microsoft.NET\Framework\v4.0.30319\SetupCache\Client\setup.exe /repair /x86 /x64 /ia64 /parameterfolder Client /q /norestart

For silent repair on 64 bit computer with .Net Framework version 4.0.30319 use:

%windir%\Microsoft.NET\Framework64\v4.0.30319\SetupCache\Client\setup.exe /repair /x86 /x64 /ia64 /parameterfolder Client /q /norestart

3. Click OK to start the repair
4. And then, restarted the IIS 7.5 and you’ll see the magic. J

Some people also seem to be having success correcting this error by running aspnet_regiis.exe. I initially tried this and it did not work for me, but feel free to give it a shot. (Keep in mind for the example below I have .Net Framework version 4.0.3.0319 installed on my computer, but you may need to change directory version to what is installed on your computer):  Here's how to run aspnet_regiis.exe:  

1. Run program command line:

run %windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe –i

If you want to open it using the Run program, just type in "Run" in the Windows 7 search box, then use the following line below in the Open box, then click OK:


%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe –i

Note if your computer is 64 bit, then I would change the line to:

%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe –i

Hopefully, these solutions help get you up and running and fix the IIS7 error...  Handler "PageHandlerFactory-Integrated" has a bad module "ManagedPipelineHandler" in its module list.

Reasons why you must trust ASPHostPortal.com

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

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

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



Cheap ASP.NET 4.5 Hosting

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

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


Author Link


 

Corporate Address (Location)

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

Tag cloud

Sign in