CPS 353: Internet Programming

HTML Forms, Basic HTTP, and more c#

Marcos Elugardo

Gordon College

Last Modified: 09/23/2015

Selected content adapted from material by Marty Stepp, Jessica Miller, and Victoria Kirst © 2012. Used by permission.

Agenda

Notes should go here...

Check-in

Form Basics

Web data

Query strings and parameters

URL?name=value&name=value...
http://www.google.com/search?q=Obama
http://example.com/student_login?username=aardvark&id=1234567

HTML forms

HTML form

HTML form: <form>

<form action="destination URL">
	form controls
</form>

Form example

<form action="http://www.google.com/search">
	<div>
		Let's search Google:
		<input name="q" />
		<input type="submit" />
	</div>
</form>
Let's search Google:

Form Controls

Form controls: <input>

<!-- 'q' happens to be the name of Google's required parameter -->
<input type="text" name="q" value="Colbert Report" />
<input type="submit" value="Booyah!" />

Text fields: <input>

<input type="text" size="10" maxlength="8" /> NetID <br />
<input type="password" size="16" /> Password
<input type="submit" value="Log In" />
NetID
Password

Text boxes: <textarea>

a multi-line text input area (inline)

<textarea rows="4" cols="20">
Type your comments here.
</textarea>

Checkboxes: <input>

yes/no choices that can be checked and unchecked (inline)

<input type="checkbox" name="lettuce" /> Lettuce
<input type="checkbox" name="tomato" checked="checked" /> Tomato
<input type="checkbox" name="pickles" checked="checked" /> Pickles
Lettuce Tomato Pickles

Radio buttons: <input>

sets of mutually exclusive choices (inline)

<input type="radio" name="cc" value="visa" checked="checked" /> Visa
<input type="radio" name="cc" value="mastercard" /> MasterCard
<input type="radio" name="cc" value="amex" /> American Express
Visa MasterCard American Express

Text labels: <label>

<label><input type="radio" name="cc" value="visa" checked="checked" /> Visa</label>
<label><input type="radio" name="cc" value="mastercard" /> MasterCard</label>
<label><input type="radio" name="cc" value="amex" /> American Express</label>

Drop-down list: <select>, <option>

menus of choices that collapse and expand (inline)

<select name="favoritecharacter">
	<option>Jerry</option>
	<option>George</option>
	<option selected="selected">Kramer</option>
	<option>Elaine</option>
</select>

Using <select> for lists

<select name="favoritecharacter[]" size="3" multiple="multiple">
	<option>Jerry</option>
	<option>George</option>
	<option>Kramer</option>
	<option>Elaine</option>
	<option selected="selected">Newman</option>
</select>

Option groups: <optgroup>

<select name="favoritecharacter">
	<optgroup label="Major Characters">
		<option>Jerry</option>
		<option>George</option>
		<option>Kramer</option>
		<option>Elaine</option>
	</optgroup>
	<optgroup label="Minor Characters">
		<option>Newman</option>
		<option>Susan</option>
	</optgroup>
</select>

Reset buttons

Name: <input type="text" name="name" /> <br />
Food: <input type="text" name="meal" value="pizza" /> <br />
<label>Meat? <input type="checkbox" name="meat" /></label> <br />
<input type="reset" />
Name:
Food:

Common UI control errors

Hidden input parameters

<input type="text" name="username" /> Name <br />
<input type="text" name="sid" /> SID <br />
<input type="hidden" name="school" value="Gordon" />
<input type="hidden" name="year" value="2048" />
Name
SID

Submit and other Buttons

<input type="text" name="name" /> Name <br />
<input type="text" name="sid" /> SID <br />
<input type="submit" name="action" value="Go For It!" />
<input type="button" name="another-action" value="Do Something Else..." />
Name

Grouping input: <fieldset>, <legend>

groups of input fields with optional caption (block)

<fieldset>
	<legend>Credit cards:</legend>
	<input type="radio" name="cc" value="visa" checked="checked" /> Visa
	<input type="radio" name="cc" value="mastercard" /> MasterCard
	<input type="radio" name="cc" value="amex" /> American Express
</fieldset>
Credit cards: Visa MasterCard American Express

Styling form controls

element[attribute="value"] {
	property : value;
	property : value;
	...
	property : value;
}
input[type="text"] {
	background-color: yellow;
	font-weight: bold;
}

Submitting Data

Problems with submitting data

<label><input type="radio" name="cc" /> Visa</label>
<label><input type="radio" name="cc" /> MasterCard</label> <br />
Favorite Star Trek captain:
<select name="startrek">
	<option>James T. Kirk</option>
	<option>Jean-Luc Picard</option>
</select> <br />

Favorite Star Trek captain:

The value attribute

<label><input type="radio" name="cc" value="visa" /> Visa</label>
<label><input type="radio" name="cc" value="mastercard" /> MasterCard</label> <br />
Favorite Star Trek captain:
<select name="startrek">
	<option value="kirk">James T. Kirk</option>
	<option value="picard">Jean-Luc Picard</option>
</select> <br />

Favorite Star Trek captain:

URL-encoding

Submitting data to a web server

Query parameters: Request.QueryString

user_name = Request.QueryString["username"];
id_number = (int) Request.QueryString["id"];
eats_meat = FALSE;
if (Request.QueryString.AllKeys.Any(k => k == "meat")) {
    $eats_meat = TRUE;
}

HTTP GET vs. POST requests

GET Example: Exponents

@{
	var firstName = Request.QueryString["fname"];
	var lastName = Request.QueryString["lname"];
	var result = "Hello " + firstName + " " + lastName;
	@result;
}
http://example.com/hello?fname=Donald&lname=Trump
Hello Donald Trump

GET Example: Print all parameters

@{
foreach (var key in Request.QueryString.AllKeys) {
	

	<p>Parameter @key has value @Request.QueryString[key]</p>

	
}
}
http://example.com/printparams?name=Orycteropus+afer&sid=1234567

Parameter name has value Orycteropus afer

Parameter sid has value 1234567

Form POST example

<form action="http://foo.com/app" method="post">
	<div>
		Name: <input type="text" name="name" /> <br />
		Food: <input type="text" name="meal" /> <br />
		<label>Meat? <input type="checkbox" name="meat" /></label> <br />
		<input type="submit" />
	<div>
</form>
Name:
Food:

GET or POST?

if (Request.HttpMethod == "GET") {
	# process a GET request
	...
} elseif (Request.HttpMethod == "POST") {
	# process a POST request
	...
}
  • some MVC actions process both GET and POST requests
  • to find out which kind of request we are currently processing,
    look at the global Request object's "HttpMethod" property

The Server.UrlEncode function

returns an HTML-escaped version of a string
  • text from files / user input / query params might contain <, >, &, etc.
  • we could manually write code to strip out these characters
  • better idea: allow them, but escape them
var text = "<p>hi 2 u & me</p>";
text = Server.UrlEncode(text);   # "&lt;p&gt;hi 2 u &amp; me&lt;/p&gt;"

Processing Form Data in C#

  • 5.1: Form Basics
  • 5.2: Form Controls
  • 5.3: Submitting Data
  • 5.4: Processing Form Data in C#

"Superglobal" arrays

Uploading files

<form action="http://webster.cs.washington.edu/params.php"
      method="post" enctype="multipart/form-data">
	Upload an image as your avatar:
	<input type="file" name="avatar" />
	<input type="submit" />
</form>
Upload an image as your avatar:
  • add a file upload to your form as an input tag with type of file
  • must also set the enctype attribute of the form to multipart/form-data
  • it makes sense that the form's request method must be post (an entire file can't be put into a URL!)
  • form's enctype (data encoding type) must be set to multipart/form-data or else the file will not arrive at the server

Processing an uploaded file in c#

  • uploaded files are placed into array Request.Files, not Request.Form
  • each element of Request.Files is itself an array, containing HttpFileCollectionBase objects. A few properties of this object are:
    • FileName      : the local filename that the user uploaded
    • ContentType      : the MIME type of data that was uploaded, such as image/jpeg
    • ContentLength      : file's size in bytes

Uploading details

<input type="file" name="avatar" />
  • example: if you upload borat.jpg as a parameter named avatar,
    • Request.Files["avatar"].FileName will be "borat.jpg"
    • Request.Files["avatar"].ContentType will be "image/jpeg"
    • Request.Files["avatar"].ContentLength will be something like "32421343"

Processing uploaded file, example

	var username = Request.Form["username"];

	<p>Received  file from @username called  @Request.Files["avatar"].FileName</p>

A form that submits to itself

<form action="" method="post">
	...
</form>
  • a form can submit its data back to itself by setting the action to the page's own URL (or blank)
  • benefits
    • fewer pages/files (don't need a separate file for the code to process the form data)
    • better encapsulation and modularity
    • can more easily re-display the form if there are any errors

Processing a self-submitted form

if (Request.HttpMethod == "GET") {
	// normal GET request; display self-submitting form
	
	<form action="" method="post">...</form>
	
} elseif (Request.HttpMethod == "POST") {
	// POST request; user is submitting form back to here; process it
	var var1 = Request.Form["param1"];
	...
}
  • a page with a self-submitting form can process both GET and POST requests
  • look at the Request.HttpMethod to see which request you're handling
  • handle a GET by showing the form; handle a POST by processing the submitted form data
  • another approach: process the form if the submit button's value is set
    • allows form processing on both GET and POST requests
    • processing on POST only is "truer" to the spirit of HTTP methods

Web Server Basics

Web server is the program on the remote computer generating and serving up content

  • takes a request
  • returns a response
    • both of these have headers -- i.e. content (MIME) type, user agent, cookies, etc.
  • server settings reside in a configuration file
    • for instance, Apache configuration values live in the httpd.conf file

Popular Web Servers

The Netcraft Web Server Survey tracks web server usage statistics.

Common Server Configuration Values

  • Document Root -- server-side directory that serves as the root for URLs to the server
    • static content (i.e. HTML files) typically must reside beneath the document root
  • Server Name
  • -- domain name for which the server answers requests
    • Used in conjunction with DNS to route requests to the server
  • Location -- path configured to execute special application code (i.e. PHP programs)
    • does not need to correspond to a real directory within the document root

What is a web service?

web service: software functionality that can be invoked through the internet using common protocols

  • like a remote function you can call by contacting a program on a web server
  • many web services accept parameters and produce results
  • can be written in PHP (or another language) and contacted by the browser in XHTML and/or Ajax code
  • service's output is often not HTML but rather text, JSON, XML, or other content types

Content ("MIME") types

MIME type related file extension
text/plain.txt
text/html.html, .htm, ...
text/css.css
text/javascript.js
text/xml.xml
image/gif.gif
image/jpeg.jpg, .jpeg
video/quicktime.mov
application/octet-stream.exe

Setting content type with Response.ContentType

Response.ContentType = "text/javascript"
  • by default, a C# page's output is assumed to be HTML
  • use the Response.ContentType function to specify non-HTML output
    • must appear before any other output generated by the script

Request.ServerVariables

index description example
Request.ServerVariables["SERVER_NAME"] name of this web server "math-cs.gordon.edu"
Request.ServerVariables["SERVER_ADDR"] IP address of web server "128.208.179.154"
Request.ServerVariables["REMOTE_HOST"] user's domain name "hsd1.wa.comcast.net"
Request.ServerVariables["REMOTE_ADDR"] user's IP address "57.170.55.93"
Request.ServerVariables["HTTP_USER_AGENT"] user's web browser "Mozilla/5.0 (Windows; ..."
Request.ServerVariables["HTTP_REFERER"] where user was before this page "http://www.google.com/"
Request.ServerVariables["REQUEST_METHOD"] HTTP method used to contact server "GET" or "POST"

Reporting errors

  • how does a web service indicate an error to the client?
    • error messages (print) are not ideal, because they could be confused for normal output
  • web service should return an HTTP "error code" to the browser, possibly followed by output
    • these are the codes you see in Firebug's console and in your Ajax request's .status property
    HTTP codeMeaning
    200 OK
    301-303 page has moved (permanently or temporarily)
    400 illegal request
    403 you are forbidden to access this page
    404 page not found
    500 internal server error
    complete list

Using headers for HTTP error codes

Response.StatusCode

	 I am not happy with the value of foo; this is an error
	Response.StatusCode = (int)HttpStatusCode.BadRequest
	Response.StatusCode = (int)HttpStatusCode.NotFound
	

Class Research Mini-topics on Web Servers

  • HTTP Methods
  • User agents
  • Server logs
  • Custom error pages
  • Web server parent and child processes

Milestone 3