Monday, October 27, 2008

Displaying images in ASP.NET using HttpHandlers

Introduction

Most of the time when developing web applications/projects we find the need to display images dynamically on the ASP.NET pages. This can include customer pictures or your product pictures. And normally there are two way of storing the pictures on your database. First, stored the images file in the database, and second one would be storing the images binary data inside the database. Most of the database including MSSQL support storing images as binary format.

Retrieving images dynamically from database based on filename can be quite simple. What we normally do is store all the images on certain folder , get the file name from the database, and then set the image server control path based on the filename and path that we get from database.


Retrieving images dynamically from database based the image binary format on the other hand also is simple. You just need to do Response.BinaryWrite,after you have got the data from the database.
In this tutorial, I will show you how to simplify the code of displaying images by using the HttpHandler. By using HTTPHandler, you only need one single line of html code to dynamically find and display your images from database regardless of you are storing the image only or you are storing the image data.

What is HTTPHandler

HttpHandlers are the earliest possible point where we have access to the requests made to the web server (IIS). When a request is made to the web server for an ASP.NET resource (.aspx, .asmx, etc.), the worker process of the ASP.NET creates the right HttpHandler for the request which responds to the request. The default handlers for each request type that ASP.NET handles are set in the machine.config file. For example, all the requests made to ASP.NET (.aspx) pages are handled by System.Web.UI.PageHandlerFactory. So whenever an ASP.NET is requested at the web server, the PageHandlerFactory will fulfill the request.

Why Http Handlers

Almost everything we do in an HttpHandler, we can simply do it in a normal .aspx page. Then why do we need HttpHandlers? First, the HttpHandlers are more reusable and portable than the normal .aspx pages. Since there are no visual elements in an HttpHandler, they can be easily placed into their own assembly and reused from project to project. Second, HttpHandlers are relatively less expensive than the PageHandler. For a page to be processed at the server, it goes through a set of events (onInit, onLoad, etc.), viewstate and postbacks or simply the complete Page Life Cycle. When you really have nothing to do with the complete page life cycle (like displaying images), HttpHandlers are very useful.


Creating an HttpHandler

To create HTTPHandler, your class need to implement IHttpHandler interface and you need to override two methods. The method name is IsReusable and ProcessRequest. HttpHandler has been known with .ashx extension in ASP.NET World.
Now, lets start coding HttpHandler.

Create new ashx file from VisualStudio
<%@ WebHandler Language="C#" Class="getImage" %>

using System;
using System.Web;
using dsImagesTableAdapters;

public class DisplayImage: IHttpHandler {

public void ProcessRequest (HttpContext context) {
int iImageId;
if (context.Request.QueryString["id"] != null)
{
iImageId = Convert.ToInt32(context.Request.QueryString["id"]);
}
else {
throw new ArgumentException("No parameter specified");
}

DataSet dsImages = GetDataSetImagesfromDatabase();
DataTable dtImgTable = dsImages.Tables[0];
if (dtImgTable .Rows.Count > 0)
{
if (dtImgTable [0]["Image"] != DBNull.Value)
{
context.Response.ContentType =
dtImgTable [0]["ImageType"].ToString();
context.Response.BinaryWrite((byte[])dtImgTable[0]["Image"]);
}
}
}

public bool IsReusable {
get {
return false;
}
}
The code above is quite self explanatory. We search the images data based on the query string passed into the HttpHandler. Please note that the code above assume that we are storing the image binary format into database and thats why we are using Response.BinaryWrite to output the result to client.
You can change the code above by using your own logic.


Now, to use the HttpHandler on your ASP.NET Pages,

<img alt="httpHandler" src="DisplayImage.ashx?id=1">

Conclusion

As you can see from the code sample above, your code is very easy to read if you are using HttpHandler to handle some of the operation on your ASP.NET pages such as displaying images. There are lots more things you can do in HttpHandler to make your code easier to read and maintain. Please leave me a comment if you have any difficulties in understanding the concept of HttpHandler.

Encrypt Passing Parameter in Url QueryString

Introduction

Once upon a time in the tech world, security is very important. This being most true in the early years of the industry, when there were gaping holes in privacy policies and confidential client information. With the new Cryptography classes in .NET, there's absolutely no excuse for not hiding even the most innocuous user data.

Main

In computer programming, a parameter is a variable which takes on the meaning of a corresponding argument passed in a call to a subroutine. A parameter represents a value that the procedure expects you to supply when you call it. The procedure's declaration defines its parameters. You can define a procedure with no parameters, one parameter, or more than one. The part of the procedure definition that specifies the parameters is called the parameter list.

If you're not going to use a session variable for storing end user information, you're most likely going to keep some sort of State by passing the information to a cookie or push it around with GET/POST parameters. If you're passing around any sort of ID or user information like their name, it's better to encrypt the information.

What I was looking for was a quick way to encrypt and decrypt parts of a QueryString - it had to be on the fly and quick.

Example: url with QueryString http://www.weburl.com/product.aspx?id=1234. In here id is a parameter and 1234 is the value of it. Now we want to encrypt 1234 so it cant be recognize by common user.


Class To Encpypt Passing Parameter Value

using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Security.Cryptography;
using System.Xml;
using System.Text;
using System.IO;

public class Encryption
{
private static byte[] key = { };
private static byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
private static string EncryptionKey = "!5623a#de";
public Encryption()
{

}
public static string Decrypt(string Input)
{
Byte[] inputByteArray = new Byte[Input.Length];
try
{
key = System.Text.Encoding.UTF8.GetBytes
(EncryptionKey.Substring(0, 8));
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
inputByteArray = Convert.FromBase64String(Input);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream
(ms, des.CreateDecryptor(key, IV), <BR>
>CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();

Encoding encoding = Encoding.UTF8;
return encoding.GetString(ms.ToArray());

}
catch (Exception ex)
{
return "";
}

}
public static string Encrypt(string Input)
{
try
{
key = System.Text.Encoding.UTF8.GetBytes
(EncryptionKey.Substring(0, 8));
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
Byte[] inputByteArray = Encoding.UTF8.GetBytes(Input);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream
(ms, des.CreateEncryptor(key, IV),CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
return Convert.ToBase64String(ms.ToArray());
}
catch (Exception ex)
{
return "";
}


}
}

Conclusion

When you need to pass the encryption parameter just simple write:
c# backend sytax:
Int value = 1234;
Asp.net url syntax:
http://www.weburl.com/product.aspx?id=<%=Encryption.Encrypt(value)%>

And to Decrypt it, c# backend sytax:
int id = Convert.ToInt32(Encryption.Decrypt(Request.QueryString["id"].Trim()));

References

Include all the useful links or references that can help users learn about this tutorial

  1. How to use ASP.NET to Encrypt Data
  2. ASP.NET Encryption Symplified

Sending Mail Using Web Form Controls

Introduction

To send e-mails, you should require access to a server with .NET Framework and SMTP enabled on it. The .NET Framework supplies a SMTP class that enables you to send a simple e-mail message. If you have to send an e-mail with added functionalities, you have to make use of the MailMessage class. With the help of this class, you can insert attachments, set priorities, and much more, very easily. You can also send HTML e-mail using this class.

Main

To send an e-mail with a simple text message, you have to use the Send() method of SMTP class. The syntax of the Send() method is shown below:

SmtpMail.Send("FROM","TO","SUBJECT","MESSAGE BODY");
}

Example:

SmtpMail.Send("mymail@mymail.com","yourmail@yourmail.com",
"Test Mail Subject","This is the test mail");

You can build a User Interface using the required WebForm controls, as shown in below.

Before we going to the next step one important thing is to check/ validate your form. Always perform validation control in every form submitted is a clever way to reduce database data stroring error because of mismatch datatype, etc. In this case it is for validating an email. For Email validation method can refer to another tutorial Here.

Instead of supplying all parameters in the Send() method, you can define properties and their corresponding values separately by creating an instance of the MailMessage class. With the help of this class, you can easily add attachments, set priorities, BCC, CC values, and much more. Table given at the end of this article, shows a list of properties of the MailMessage class. Add the code given below by double-clicking the button captioned Submit:

MailMessage objEmail          = new MailMessage();
objEmail.To = txtTo.Text;
objEmail.From = txtFrom.Text;
objEmail.Cc = txtCc.Text;
objEmail.Subject = "Test Email";
objEmail.Body = txtName.Text + ", " +
txtComments.Text;
objEmail.Priority = MailPriority.High;
//SmtpMail.SmtpServer = "localhost";
try{
SmtpMail.Send(objEmail);
Response.Write("Your Email has been sent sucessfully -
Thank You"
);
}
catch (Exception exc){
Response.Write("Send failure: " + exc.ToString());
}

Property Description
Attachments Used for sending e-mails with attachments
From Sender's e-mail address
To Recipient's e-mail address
Cc Recipient's e-mail address (Carbon Copy)
Bcc Recipient's e-mail address (Blind Carbon Copy)
Body Text of the e-mail message
BodyFormat Specifies the format of an e-mail message (Possible Values: Text, Html)
Priority Specifies the priority of an e-mail message (Possible Values: High, Low, and Normal)
Subject Denotes the subject of an e-mail message
Headers Denotes a collection of acceptable headers (Example: Reply-To)
BodyEncoding Specifies the method of encoding an e-mail message (Possible Values: Base64 and UUEncode)


Below sytax is used for sending your mail in HTML format:

objEmail.BodyFormat = MailFormat.Html;

Conclusion

To send an email from your ASP.NET page, you need to: import the System.Web.Mail namespace in your ASP.NET page, create an instance of the MailMessage class, set all the properties of the MailMessage instance, and send the message with SmtpMail.Send method.

References

All the useful links or references that can help you learn about this tutorial

  1. SMTP Client Class
  2. Configure SMTP Server and Email

Passing Values from One Page to Another in ASP.NET

Introduction

Passing parameters from one page to another is a very common task in Web development. Granted, its importance and frequency has faded a bit with ASP.NET's inherent preference for postback forms, but regardless, there are still many situations in which you need to pass data from one Web page to another. There are three widely used methods of passing values from one page to another in ASP.NET

Main

1. Using Query String
We usually pass value through query string of the page and then this value is pulled from Request object in another page.

FirstForm.aspx.cs

Response.Redirect("SecondForm.aspx?Parameter=" + TextBox1.Text);


SecondForm.aspx.cs

TextBox1.Text = Request. QueryString["Parameter"].ToString();


This is the most reliable way when you are passing integer kind of value or other short parameters.

More advance in this method if you are using any special characters in the value while passing it through query string, you must encode the value before passing it to next page. So our code snippet of will be something like this:

FirstForm.aspx.cs

Response.Redirect("SecondForm.aspx?Parameter=" + Server.UrlEncode(TextBox1.Text));


SecondForm.aspx.cs

TextBox1.Text = Server.UrlDecode(Request.QueryString["Parameter"].ToString());

2. Passing value through context object
Passing value through context object is another widely used method.

FirstForm.aspx.cs

TextBox1.Text = this.Context.Items["Parameter"].ToString();

SecondForm.aspx.cs

this.Context.Items["Parameter"] = TextBox1.Text;
Server.Transfer("SecondForm.aspx", true);


Note that we are navigating to another page using Server.Transfer instead of Response.Redirect.

Some of us also use Session object to pass values. In that method, value is store in Session object and then later pulled out from Session object in Second page.

3. Posting form to another page instead of PostBack
Third method of passing value by posting page to another form. Here is the example of that:

FirstForm.aspx.cs

private void Page_Load(object sender, System.EventArgs e)
{
buttonSubmit.Attributes.Add("onclick", "return PostPage();");
}

And we create a javascript function to post the form.

SecondForm.aspx.cs

function PostPage()
{
document.Form1.action = "SecondForm.aspx";
document.Form1.method = "POST";
document.Form1.submit();
}
TextBox1.Text = Request.Form["TextBox1"].ToString();


Here we are posting the form to another page instead of itself. You might get viewstate invalid or error in second page using this method. To handle this error is to put EnableViewStateMac=false

4. Another method is by adding PostBackURL property of control for cross page post back

In ASP.NET 2.0, Microsoft has solved this problem by adding PostBackURL property of control for cross page post back. Implementation is a matter of setting one property of control and you are done.

FirstForm.aspx.cs



SecondForm.aspx.cs

TextBox1.Text = Request.Form["TextBox1"].ToString();

In above example, we are assigning PostBackUrl property of the button we can determine the page to which it will post instead of itself. In next page, we can access all controls of the previous page using Request object.

You can also use PreviousPage class to access controls of previous page instead of using classic Request object.

SecondForm.aspx

TextBox textBoxTemp = (TextBox) PreviousPage.FindControl("TextBox1");
TextBox1.Text = textBoxTemp.Text;

As you have noticed, this is also a simple and clean implementation of passing value between pages.

Conclusion

Passing values between pages is another common task accomplishes in web based development. As we have discussed many of mechanisms above, I prefer and recommend to use Query String then other methods for its clean and simple implementation as long as your parameter doesnt have security concern.

References

All the useful links or references that can help you learn about this tutorial

1. ASP.NET State Management Overview
2. How to Pass Values Between ASP.NET Webpages

Creating and modifying XML Document using XML DOM in ASP.Net

Introduction

In .Net, modifying an XML document is a task that is central to developing XML based application (Either it is a web application or windows application). Microsoft .Net Framework has classes that can be used to perform this task. Mainly the class we used is in the namespace System.XML.

In this article we’ll learn how to manipulating XML Document using XML DOM (XML Document Object Model). The XML DOM provides a programming interface for applications to manipulate XML. This implementation is fully support the W3C standard and provides additional features that make it easier to program applications to work with XML files.

Why using XML DOM? Not using XML Reader?

Main reason for using XML DOM (Document Object Model) rather than using XML Reader is because XML Reader can only read XML Document by forward only and read only. By using XML DOM we can read XML document by non sequential or by random. This can be done because DOM cache XML data in memory, and by doing this, an application can use DOM to:

  1. Search specific content in an XML Document
  2. Add, remove, or replace content (nodes, properties, or it’s value)
  3. Save result to an XML File

Creating XML Document

XMLDocument object acts as a container for an XML document. You typically create an XMLDocument and load it with XML from a file, string, or a stream.



Now we look how to create XML using XmlDocument.

Dim XmlDoc As New XmlDocument

Dim XmlDecl As XmlDeclaration
XmlDecl = XmlDoc.CreateXmlDeclaration("1.0", "UTF-8", "")
XmlDoc.AppendChild(XmlDecl)
Dim RootElem As XmlElement
RootElem = XmlDoc.CreateElement("Employee")
XmlDoc.AppendChild(RootElem)
RootElem.SetAttribute("Name", "Hendra")
RootElem.SetAttribute("Age", 26)
Dim DeptElem As XmlElement
DeptElem = XmlDoc.CreateElement("Department")
RootElem.AppendChild(DeptElem)
DeptElem.InnerText = "Information Technology Department"
XmlDoc.Save("c:\employee.xml")

With the code above, you will get a XML file with content as below :

"1.0" encoding="UTF-8"?>

"Hendra" Age="26">
Information Technology Department

See, it’s easy to generate a XML file with predefine content by using XML DOM.

Reading XML Document

XMLDocument can be loaded with a XML file, string, or a stream.

Example :

Dim XmlDoc As New XmlDocument

XmlDoc.Load("c:\employee.xml")
Dim employees As XmlNodeList
employees = XmlDoc.SelectNodes("//Employee ")
Dim item As XmlElement
For Each item In employees
Response.write(item.GetAttribute("
Name") )
Next

By using XmlDocument, it’s easy to retrieve nodes of an XML File. Then you can retrieve it’s attribute, values, or inner text / XML.

Modifying XML Document
XML DOM enable you to modify XML Document

Example :

    Dim XmlDoc As New XmlDocument

XmlDoc.Load("C:\employee.xml")
Dim elements As XmlNodeList
elements = XmlDoc.SelectNodes("//Employee")
Dim elemen As XmlElement
For Each elemen In elements
Dim EmployeeName As String
EmployeeName = elemen.GetAttribute("
Name")
'We use xpath to querying Employee element
Dim xpath As String
xpath = "
//Employee[@Name='" & EmployeeName & "']"
Dim EmployeeElement As XmlElement
EmployeeElement = XmlDoc.SelectSingleNode(xpath)
'We now update the age attribute in Employee node / element
Dim x As Integer
x = Int32.Parse(EmployeeElement.GetAttribute("Age"))
x = x + 5
EmployeeElement.SetAttribute("Age", x.ToString)
Next
XmlDoc.Save("C:\employee.xml")

The code above is used to modify a XML file content. In the example as you can see, we use XML DOM to read XML File, then using xpath to querying XML content. And then we use XmlElement in XML DOM to set the attribute of the XmlElement.

Sending Email in ASP.NET 1.0

Introduction

One of the most common things we do as a webmaster is sending email to our clients. In old classic ASP, we need to rely on third party components just for sending email. Things has change a lot since Microsoft release .NET 1 framework. We can use the library inside the .NET Framework to send email.

In .NET Framework 1, there is a class library that you can use to send email. The class is inside the System.Web.Mail namespace and the class name is SmtpMail.
Main

Sending Email in ASP.NET 1 is quite easy and straight forward, and you can send ASP.NET email in just 5 lines of code. I will write down the sample code below in both VB.NET and C# language.
First and foremost you need to add reference to System.Web.Mail namespace.

The code below will work only with .NET Framework 1.0 and not on .NET Framework 2.0. The reason is because Microsoft has move the SmtpMail class from System.Web.Mail namespace to System.Net.Mail namespace

Basic Sample Code to Send Text Email in ASP.NET 1.0
[C#]

MailMessage mail = new MailMessage();
mail.To = "me@mycompany.com";
mail.From = "you@yourcompany.com";
mail.Subject = "Testing Email.";
mail.Body = "this is my test email body";
SmtpMail.SmtpServer = "IPAddress"; //your real server goes here
SmtpMail.Send( mail );

[VB.NET]

Dim mail As New MailMessage()
mail.To = "me@mycompany.com"
mail.From = "you@yourcompany.com"
mail.Subject = "Testing Email."
mail.Body = "this is my test email body"
SmtpMail.SmtpServer = "IPAddress" 'your real server goes here

SmtpMail.Send(mail)


Replace the IPAddress with your SMTP Server IPAddress. If you are hosting your site somewhere, you need to ask the support for the SMTP Server address.

If you see the code above, it is quite simple actually to send email in .NET Framework 1 and ASP.NET. However the code above will not work if your SMTP server is configured with SMTP Authentication.
If you are hosting your site somewhere, big chances that the code above will not work.

The reason is simple, to fight the abuse and spam. Most of the email administrators will enabled SMTP authentication on their server. And this will means only those who can authenticate successfully will be allowed to send email.

In the following code, we will look on how to send email using SMTP authentication in .NET Framework and ASP.NET 1

Basic Sample Code on Sending Email using SMTP Authentication with ASP.NET 1

[C#]

MailMessage mail = new MailMessage();
mail.To = "me@mycompany.com";
mail.From = "you@yourcompany.com";
mail.Subject = "this is a test email.";
mail.Body = "Some text goes here";
mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");
mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", "email username");
mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", "email password");
SmtpMail.SmtpServer = "mail.mycompany.com";
SmtpMail.Send( mail );


[VB.NET]

Dim mail As New MailMessage()
mail.To = "me@mycompany.com"
mail.From = "you@yourcompany.com"
mail.Subject = "this is a test email."
mail.Body = "Some text goes here"
mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1")
mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", "email username")
mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", "email password")
SmtpMail.SmtpServer = "mail.mycompany.com" 'your mail server goes here

SmtpMail.Send(mail)

From the code above, you can see that we provide the authentication details before we called the SMTPMail.Send method. This will allow you to send the username and password details to your mailserver so that your mailserver will know that you are a legitimate user and therefore will allow you to send email

Now, lets go through another example on Sending HTML email. Sending HTML Email is quite easy also in the .NET 1. With just switching one properties from Mail class, you can set whether you like to send HTML email or Text Email. The code sample is below

Sample Code on Sending Email using HTML and ASP.NET 1

[C#]

MailMessage mail = new MailMessage();
mail.To = "me@mycompany.com";
mail.From = "you@yourcompany.com";
mail.Subject = "Testing Email.";
mail.BodyFormat = MailFormat.Html;
mail.Body = "this is my test email body.
Bold"
SmtpMail.SmtpServer = "localhost"; //your real server goes here
SmtpMail.Send( mail );


[VB.NET]

Dim mail As New MailMessage()
mail.To = "me@mycompany.com"
mail.From = "you@yourcompany.com"
mail.Subject = "Testing Email."
mail.BodyFormat = MailFormat.Html
mail.Body = "this is my test email body.
Bold"
SmtpMail.SmtpServer = "localhost" 'your real server goes here

SmtpMail.Send(mail)

Troubleshooting System.Net.Mail
Few tips and tricks for you to troubleshoot if you email never arrived to the destination

* Check if the SMTP Server is listening on port 25 (telnet ipaddress 25)
* Check if your Mailserver ip is being blacklisted (http://mxtoolbox.com/blacklists.aspx)
* Check if your SMTP Server is being configured using SMTP Authentication. If using SMTP Authentication, then check if your username and password is correct. You can try login using the username and password using outlook and try to send email from outlook. Remember to check using SMTP Authentication is your outlook settings.

Working with HttpWebRequest and HttpWebResponse in ASP.NET

Introduction

I will explain about the usage of HttpWebRequest and HttpWebResponse in this article. As you all probably know or heard about this class before. HttpWebRequest and HttpWebResponse class is inside the System.NET namespace, and this two classes is designed to communicate by using the Http Protocol

You can use this two classes to make requests to other Web Pages via HTTP and parse the resulting text to extract data. This is what we know as screen scraping.

In ASP world, you normally need to rely on third party components called ASPTear to grab the contents from other site. But now with the help of HttpWebRequest and HttpWebResponse, you can do that easily without have to invoke third party components.
Using HttpWebRequest and HttpWebResponse

In the code below, I provide very basic sample code on how to use HttpWebRequest and HttpWebResponse. In the first example I will list out the code on how to do screen scraping and the second example would be doing HttpPost data to another website

1. Sample Code on Grabbing Contents (Screen Scraping)

C#

protected void Page_Load(object sender,EventArgs e) {
Uri uri = new Uri("http://www.microsoft.com/default.aspx");
if(uri.Scheme = Uri.UriSchemeHttp) {
HttpWebRequest request = HttpWebRequest.Create(uri);
request.Method = WebRequestMethods.Http.Get;
HttpWebResponse response = request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string tmp = reader.ReadToEnd();
response.Close();
Response.Write(tmp);
}
}


VB.NET

Protected Sub Page_Load(ByVal sender as Object,ByVal e as System.EventArgs)
Dim uri as New Uri("http://www.microsoft.com/default.aspx");

If(uri.Scheme == uri.UriSchemeHttp) Then
Dim request as HttpWebRequest = HttpWebRequest.Create(uri)
request.Method = WebRequestMethods.Http.Get
Dim response As HttpWebResponse = request.GetResponse()
Dim reader As New StreamReader(response.GetResponseStream())
Dim tmp As String = reader.ReadToEnd()
response.Close()
Response.Write(tmp)
End If
End Sub

If you try to run the code, you can see that all the HTML code from Microsoft site has been grabbed and display on your local web server.

2. Sample Code on how to Post Data to remote Web Page using HttpWebRequest
C#

protected void Page_Load(object sender,EventArgs e) {
Uri uri = new Uri("http://www.amazon.com/exec/obidos/search-handle-form/102-5194535-6807312");
string data = "field-keywords=ASP.NET 2.0";
if (uri.Scheme == Uri.UriSchemeHttp)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.Method = WebRequestMethods.Http.Post;
request.ContentLength = data.Length;
request.ContentType = "application/x-www-form-urlencoded";

StreamWriter writer = new StreamWriter(request.GetRequestStream());
writer.Write(data);
writer.Close();

HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string tmp = reader.ReadToEnd();
response.Close();
Response.Write(tmp);
}
}


VB.NET

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim uri As New Uri("http://www.amazon.com/exec/obidos/search-handle-form/102-5194535-6807312")
Dim data As String = "field-keywords=ASP.NET 2.0"
If uri.Scheme = uri.UriSchemeHttp Then
Dim request As HttpWebRequest = HttpWebRequest.Create(uri)
request.Method = WebRequestMethods.Http.Post
request.ContentLength = data.Length
request.ContentType = "application/x-www-form-urlencoded"

Dim writer As New StreamWriter(request.GetRequestStream)
writer.Write(data)
writer.Close()

Dim oResponse As HttpWebResponse = request.GetResponse()
Dim reader As New StreamReader(oResponse.GetResponseStream())
Dim tmp As String = reader.ReadToEnd()
oResponse.Close()

Response.Write(tmp)
End If

End Sub

Conclusion

Based on the sample code above, you can see that it is quite simple to do Http Post and Http Get to remote Website by using two built in class HttpWebRequest and HttpWebResponse. There is another set of classes called FtpWebRequest and FtpWebResponse that allow you to do ftp post and get to remote ftp Server.

Publish and create RSS Feeds easily on your ASP.NET websites

Publish and create RSS Feeds easily on your ASP.NET websites

This article explains the concept of creating RSS feeds for your ASP.NET website with auto updating contents

Introduction

This article explains the concept of creating and publishing RSS feeds on your websites by dynamically and auto updating RSS contents driven from your database.

Many of the web application this days update their website contents frequently to attract the users at the maximum extent. Even web publishers needs to share their content without re-creating it on any form. But there is no way to inform the users about the new contents in their website. Either they have send newsletters to the users or the users have to bookmark the website URL in their browser’s favorites, which had its own drawbacks. To overcome this difficulty, Netscape introduced the concept of RSS in late 90s. It serves the information consumers and publishers to stay up to date with their desired website's content.

What is RSS?

RSS, can be expanded as Really Simple Syndication. RSS is a lightweight XML format for distributing regularly changed web contents among different web sites and users. A Web site can allow the users or other sites to publish some of its content by creating an RSS feeds.

Once you create the RSS Feeds, all your website users can subscribe the feeds and publish the feeds into their news reader or into their website. So instead of having to browse each individual site for the news, they can just import into their RSS reader all the RSS feeds. A good example of site that using RSS heavily is Google News. With google news, you can see news from around the world in one simple page. The main concept behind the Google News is subscribe RSS feeds from all major news provider around the world. Lots of article driven websites these days will provide RSS feeds on their website.


RSS Feeds Structure

If you check most of the website RSS Feeds, you can see that the output of the Feeds is just an XML File with certain tags. RSS itself is basically a creation of well formed XML file in a pre defined format.

The basic main RSS tags are shown below

<rss version="2.0">

<channel>
......
channel>
podcast directory
Bloglisting.net - The internets fastest growing blog directory

RSS Feed

Blog Directory & Search engine

Followers

About Me