Recipe16.3.Simulating Form Execution


Recipe 16.3. Simulating Form Execution

Problem

You need to send a collection of name-value pairs to simulate a form being executed on a browser to a location identified by a URL.

Solution

Use the System.Net.WebClient class to send a set of name-value pairs to the web server using the UploadValues method. This class enables you to masquerade as the browser executing a form by setting up the name-value pairs with the input data. The input field ID is the name, and the value to use in the field is the value:

 using System; using System.Net; using System.Text; using System.Collections.Specialized; Uri uri = new Uri("http://localhost/FormSim/WebForm1.aspx"); WebClient client = new WebClient( ); // Create a series of name-value pairs to send NameValueCollection collection = new NameValueCollection( ); // Add necessary parameter-value pairs to the name-value container collection.Add("Identity","foo@bar.com"); collection.Add("Item","Books"); collection.Add("Quantity","5"); Console.WriteLine("Uploading name/value pairs to URI {0} …", uri.AbsoluteUri); // Upload the NameValueCollection byte[] responseArray =     client.UploadValues(uri.AbsoluteUri,"POST",collection); // Decode and display the response Console.WriteLine("\nResponse received was {0}",     Encoding.ASCII.GetString(responseArray)); 

The webform1.aspx page, which receives and processes this data, looks like this:

 <%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="FormSim.WebForm1" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" > <HTML>     <HEAD>          <title>WebForm1</title>          <meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">          <meta name="CODE_LANGUAGE" Content="C#">          <meta name="vs_defaultClientScript" content="JavaScript">          <meta name="vs_targetSchema"               content="http://schemas.microsoft.com/intellisense/ie5">      </HEAD>      <body MS_POSITIONING="GridLayout">          <form  method="post" runat="server">               <asp:TextBox  style="Z-INDEX: 101; LEFT: 194px;                            POSITION: absolute; TOP: 52px" runat="server"></asp:TextBox>               <asp:TextBox  style="Z-INDEX: 102; LEFT: 193px;                           POSITION: absolute; TOP: 93px" runat="server"></asp:TextBox>               <asp:TextBox  style="Z-INDEX: 103; LEFT: 193px;                           POSITION: absolute; TOP: 132px"                    runat="server"></asp:TextBox>               <asp:Button  style="Z-INDEX: 104; LEFT: 203px;                          POSITION: absolute; TOP: 183px"                  runat="server" Text="Submit"></asp:Button>               <asp:Label  style="Z-INDEX: 105; LEFT: 58px;                          POSITION: absolute; TOP: 54px" runat="server"                   Width="122px" Height="24px">Identity:</asp:Label>               <asp:Label  style="Z-INDEX: 106; LEFT: 57px;                          POSITION: absolute; TOP: 94px" runat="server"                   Width="128px" Height="25px">Item:</asp:Label>              <asp:Label  style="Z-INDEX: 107; LEFT: 57px;                          POSITION: absolute; TOP: 135px" runat="server"                   Width="124px" Height="20px">Quantity:</asp:Label>           </form>      </body>  </HTML> 

The webform1.aspx code-behind looks like this. The added code is highlighted.

 using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; namespace FormSim {     /// <summary>     /// Summary description for WebForm1     /// </summary<     public class WebForm1 : System.Web.UI.Page     {         protected System.Web.UI.WebControls.Button Button1;         protected System.Web.UI.WebControls.TextBox Item;         protected System.Web.UI.WebControls.Label Label1;         protected System.Web.UI.WebControls.Label Label2;         protected System.Web.UI.WebControls.Label Label3;         protected System.Web.UI.WebControls.TextBox Identity;         protected System.Web.UI.WebControls.TextBox Quantity;         private void Page_Load(object sender, System.EventArgs e)          {              // Put user code to initialize the page here.          }         #region Web Form Designer generated code         override protected void OnInit(EventArgs e)         {             //             // CODEGEN: This call is required by the ASP.NET Web Form Designer             //             InitializeComponent( );             base.OnInit(e);         }         /// <summary>         /// Required method for Designer support - do not modify         /// the contents of this method with the code editor         /// </summary>         private void InitializeComponent( )         {             this.Button1.Click +=                   new System.EventHandler(this.Button1_Click);              this.Load += new System.EventHandler(this.Page_Load);         }         #endregion          private void Button1_Click(object sender, System.EventArgs e)          {              string response = "Thanks for the order!<br/>";              response += "Identity: " + Request.Form["Identity"] + "<br/>";              response += "Item: " + Request.Form["Item"] + "<br/>";             response += "Quantity: " + Request.Form["Quantity"] + "<br/>";             Response.Write(response);         }      } } 

The output from the form execution looks like this:

 Uploading name-value pairs to URI http://localhost/FormSim/WebForm1.aspx … Response received was <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" > <HTML>     <HEAD>         <title>WebForm1</title>         <meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">         <meta name="CODE_LANGUAGE" Content="C#">         <meta name="vs_defaultClientScript" content="JavaScript">         <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">     </HEAD>     <body MS_POSITIONING="GridLayout">          <form name="Form1" method="post" action="WebForm1.aspx" > <input type="hidden" name="__VIEWSTATE" value="dDwtMTI3ODA2MzE3NDs7PqEOy03ljfXs5tGC+P86H0bF9IMA" />             <input name="Identity" type="text"  style="Z-INDEX: 101; LEFT: 194px; POSITION: absolute; TOP: 52px" />              <input name="Item" type="text"  style="Z-INDEX: 102; LEFT:  193px; POSITION: absolute; TOP: 93px" />              <input name="Quantity" type="text"  style="Z-INDEX: 103; LEFT: 193px; POSITION: absolute; TOP: 132px" />              <input type="submit" name="Button1" value="Submit"  style="Z- INDEX: 104; LEFT: 203px; POSITION: absolute; TOP: 183px" />              <span  style="Z-INDEX: 105; LEFT: 58px; POSITION: absolute; TOP: 54px">Identity:</span>              <span  style="Z-INDEX: 106; LEFT: 57px; POSITION: absolute; TOP: 94px">Item:</span>              <span  style="Z-INDEX: 107; LEFT: 57px; POSITION: absolute; TOP: 135px">Quantity:</span>          </form>      </body>  </HTML> 

Discussion

The WebClient class makes it easy to upload form data to a web server in the common format of a set of name-value pairs. You can see this technique in the call to UploadValues that takes an absolute URI (http://localhost/FormSim/WebForm1.aspx), the HTTP method to use (POST), and the NameValueCollection you created (collection). The NameValueCollection is populated with the data for each of the fields on the form by calling its Add method, passing the id of the input field as the name and the value to put in the field as the value. In this example, you fill in the Identity field with foo@bar.com, the Item field with Book, and the Quantity field with 5. You then print out the resulting response from the POST to the console window.

See Also

See the "WebClient Class" topic in the MSDN documentation.



C# Cookbook
Secure Programming Cookbook for C and C++: Recipes for Cryptography, Authentication, Input Validation & More
ISBN: 0596003943
EAN: 2147483647
Year: 2004
Pages: 424

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net