Currently showing entries with the tag: hack
|
page 1 of 1
|
.NET Interview Questions - Part 3
December 02, 2007 • 7:56PM • permalink
I received such an overwhelming response to my last two blog posts on .NET interview questions, that I decided to post a third.
Part 1 can be found here.
Part 2 can be found here.
Continuing from where we left off...
6. If placed in the Page_Load method of a ASP.NET page, what will the following code output?
Response.Write("<br />Before");
try
{
Response.Write("<br />In the 'try'");
int i = 0;
int j = 1 / i;
}
catch
{
Response.Write("<br />In the 'catch'");
Response.End();
return;
}
finally
{
Response.Write("<br />In the 'finally'");
}
Response.Write("<br />After");
Pretty simple question, right? Wrong!
I got it wrong the first time round too and even for the posting of this blog I made sure to execute the program and check the results!
You would see the following:
Before
In the 'try'
In the 'catch'
In the 'finally'
Remember that the finally clause will execute without exception (no pun intended). I tried to really drive that home by first executing Response.End, which even throws a second exception, and then executing a return function, in an attempt to leave the currently executing method.
Regardless of the return, the finally clause still executes before returning control to the return statement, preventing the display of the word "After".
7. Write a script to generate a dynamic image on a webpage, such as for use as a CAPTCHA, placing a watermark on an image or checking the referring url of a requested image?
For my example, I'll display 10 characters of randomly sized/styled/selected text in on a Red background. Note that I'm not going to introduce any warping, backgrounds or any other security features. This code is not intended for use as a real CAPTCHA and it would be trivial to write a OCR script to attack it.
I'm going to put the whole block of code without too much discussion. Most of the work is done by the GDI functions, which you can easily look up on MSDN. This would be placed in the OnLoad portion of a page and then called through a img object in the HTML like:
<img src="CaptchaImage.aspx" />
Note that we have previously defined the following helper structure to avoid repeated boxing/unboxing:
struct CaptchaCharacter
{
public char character;
public Font font;
}
The rest of the code follows:
int width = 600;
int height = 400;
int number_of_characters = 10;
string character_choices = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
string[] font_families = { "Tahoma", "Arial", "Verdana" };
int[] font_sizes = { 36, 60, 84, 108 };
Rectangle bmp_rect = new Rectangle(0, 0, width, height);
Bitmap bmp = new Bitmap(width, height);
Graphics graphics = Graphics.FromImage(bmp);
graphics.SmoothingMode = SmoothingMode.AntiAlias;
graphics.FillRectangle(Brushes.Red, bmp_rect);
CaptchaCharacter[] character_array = new CaptchaCharacter[number_of_characters];
Random rnd = new Random();
for (int x = 0; x < number_of_characters; x++)
{
CaptchaCharacter new_char = new CaptchaCharacter();
new_char.character = character_choices[rnd.Next(0, character_choices.Length)];
new_char.font = new Font(font_families[rnd.Next(0, font_families.Length)],
font_sizes[rnd.Next(0, font_sizes.Length)]);
character_array[x] = new_char;
}
StringFormat format = new StringFormat();
format.Alignment = StringAlignment.Center;
format.LineAlignment = StringAlignment.Center;
GraphicsPath path = new GraphicsPath();
for (int a = 0; a < number_of_characters; a++)
{
RectangleF rect = new RectangleF((width / number_of_characters) * a,
0,
width / number_of_characters,
height);
path.AddString(character_array[a].character.ToString(),
character_array[a].font.FontFamily,
0,
character_array[a].font.SizeInPoints,
rect,
format);
}
graphics.FillPath(Brushes.Black, path);
Response.ContentType = "image/gif";
bmp.Save(Response.OutputStream, ImageFormat.Gif);
for (int z = 0; z < character_array.Length; z++)
character_array[z].font.Dispose();
path.Dispose();
graphics.Dispose();
bmp.Dispose();
First a Bitmap object is created, which is what we will eventually output. After obtaining a reference to it's GDI Graphics object, we begin drawing on it. First a background rectangle with a Red brush is drawn and then a GraphicsPath object is created. We can use the built-in AddString method of the GraphicsPath to easily style and add our characters. We could have easily output the whole string at once, but we loop through each character to apply individual styling of FontFamily and font size to each character. Finally, we change the ResponseType of the our encapsulating page and save the bitmap to the built-in OutputStream (which will block all other output to the page).
Lately, I've seen a lot of really bad SQL come through the office on interviews. In our extensive interview process, many of the other developers focus on simple SQL problems, which is really all that is necessary for the day-to-day job at Demand.
Unlike some of the other developers, my boss constantly chastises me for worrying about security too much. I can't deny that I do obsess about security too much, given my background, but because of that I'll occasionally ask the following question, which I think any SQL developer should be able to answer:
8. Given a simple login box (with username and password fields), what input will compromise the database in a susceptible system?
I'll even go so far as to show you the poorly written code that will allow this... (Note that the code is looking for the password of the given user and will check it in C# code below, that's all it takes to allow an exploit).
string sql = string.Format(@"
SELECT
password
FROM [dbo].[Accounts]
WHERE username='{0}' ", Request.Form["username"]);
DataTable dt = new DataTable();
SqlConnection connection = new SqlConnection(connection_string);
SqlCommand command = new SqlCommand(sql, connection);
command.CommandType = CommandType.Text;
connection.Open();
SqlDataReader sdr = command.ExecuteReader(CommandBehavior.CloseConnection);
dt.Load(sdr);
sdr.Close(); //this will close the connection too
if (dt.Rows.Count > 0)
if (dt.Rows[0]["password"].ToString() == Request.Form["password"])
LoginUser();
First, the exploit. There are an infinite number of things you can do with a SQL Injection, but we'll use the simple input:
' AND 0=1 UNION SELECT '123456' -- in the username field and 123456 in the password field.
This turns the executed query into:
SELECT
password
FROM [dbo].[Accounts]
WHERE username='' AND 0=1 UNION SELECT '123456' --'
First, you'll note that the -- placed at the end will comment out the original query ending, including the single-quote. The end result has the WHERE-clause being interpreted as username='' AND 0=1. Obviously, the AND 0=1 portion will cause the entire clause to return FALSE. At this point, we UNION a literal '123456', which will allow us access to the site. (Note that this is a very simple example, in most cases you would most likely be selecting back the matching user account and hence could theoretically login to any account.)
Some may argue that I made the impossible possible by revealing the original source code, but that's not necessarily true. For anyone that's attempting a SQL-injection, it's most likely not a large leap to write a script to brute force the parameters of the victim query. At that point, you can literally do whatever you want by using a little ingenuity and the INFORMATION_SCHEMA object, supported by most RDMS.
.NET Quickies
* Using a method of the String object, what is the optimized .NET way of performing the (often executed) compound conditional:
if (some_string != null && some_string != "")
DoSomething();
String.IsNullOrEmpty()
(in my tests for this blog entry, it consistently performed 40-45% faster)
* When encoding data, what is the key overall difference between hashing and encrypting?
Hashing is a one-way mapping, while encryption has a corresponding decryption which will reverse the process.
* What is the effect of making a method of a class static and what might it's use be?
Static methods are not associated with any one instance of the class, nor are they able to access any instance fields of a class. Thus, instead of invoking the methods through an instance call, you use the name of the class instead (since you are referencing the single Type object of that class maintained by .NET), like so:
string s = "some test string";
bool starts_with_some = s.StartsWith("some");
bool not_null_or_empty = string.IsNullOrEmpty(s);
Static methods allow you to provide stand-alone methods that relate to a classes functionality. Another example might be a Country class. I might use it to represent a single country object, with fields/properties like CountryID, Name or ZipCodeList. I might also include a method to use the current class' data like GetIPRange() or FindContinent(). Finally, I could also add stand-alone (static) methods, like Country.GetAllCountries() to return a List containing the name of every country on Earth.
I want to add the additional note that since I've been seeing an increase in the number of "demand media" interview questions Google searches hit my blog, we have been working on restructuring our interview process to change the questions around and are now working towards a much more hands-on interview. Note that part of the review process includes reviewing my blog for any questions and removing them (or limiting the use of them) from our interview process. So make sure you know how to use .NET in ways outside the scope of these questions.

I also want to encourage people to continue contacting me with your questions and comments. As long as there is an interest in the topic, I will continue to present real-life .NET interview questions.
Part 1 can be found here.
Part 2 can be found here.
Continuing from where we left off...
6. If placed in the Page_Load method of a ASP.NET page, what will the following code output?
Response.Write("<br />Before");
try
{
Response.Write("<br />In the 'try'");
int i = 0;
int j = 1 / i;
}
catch
{
Response.Write("<br />In the 'catch'");
Response.End();
return;
}
finally
{
Response.Write("<br />In the 'finally'");
}
Response.Write("<br />After");
Pretty simple question, right? Wrong!
I got it wrong the first time round too and even for the posting of this blog I made sure to execute the program and check the results!
You would see the following:
Before
In the 'try'
In the 'catch'
In the 'finally'
Remember that the finally clause will execute without exception (no pun intended). I tried to really drive that home by first executing Response.End, which even throws a second exception, and then executing a return function, in an attempt to leave the currently executing method.
Regardless of the return, the finally clause still executes before returning control to the return statement, preventing the display of the word "After".
7. Write a script to generate a dynamic image on a webpage, such as for use as a CAPTCHA, placing a watermark on an image or checking the referring url of a requested image?
For my example, I'll display 10 characters of randomly sized/styled/selected text in on a Red background. Note that I'm not going to introduce any warping, backgrounds or any other security features. This code is not intended for use as a real CAPTCHA and it would be trivial to write a OCR script to attack it.
I'm going to put the whole block of code without too much discussion. Most of the work is done by the GDI functions, which you can easily look up on MSDN. This would be placed in the OnLoad portion of a page and then called through a img object in the HTML like:
<img src="CaptchaImage.aspx" />
Note that we have previously defined the following helper structure to avoid repeated boxing/unboxing:
struct CaptchaCharacter
{
public char character;
public Font font;
}
The rest of the code follows:
int width = 600;
int height = 400;
int number_of_characters = 10;
string character_choices = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
//NUMBERS 0+1, LETTERS I+O removed for legibility reasons
string[] font_families = { "Tahoma", "Arial", "Verdana" };
int[] font_sizes = { 36, 60, 84, 108 };
Rectangle bmp_rect = new Rectangle(0, 0, width, height);
Bitmap bmp = new Bitmap(width, height);
Graphics graphics = Graphics.FromImage(bmp);
graphics.SmoothingMode = SmoothingMode.AntiAlias;
graphics.FillRectangle(Brushes.Red, bmp_rect);
CaptchaCharacter[] character_array = new CaptchaCharacter[number_of_characters];
Random rnd = new Random();
for (int x = 0; x < number_of_characters; x++)
{
CaptchaCharacter new_char = new CaptchaCharacter();
new_char.character = character_choices[rnd.Next(0, character_choices.Length)];
new_char.font = new Font(font_families[rnd.Next(0, font_families.Length)],
font_sizes[rnd.Next(0, font_sizes.Length)]);
character_array[x] = new_char;
}
StringFormat format = new StringFormat();
format.Alignment = StringAlignment.Center;
format.LineAlignment = StringAlignment.Center;
GraphicsPath path = new GraphicsPath();
for (int a = 0; a < number_of_characters; a++)
{
RectangleF rect = new RectangleF((width / number_of_characters) * a,
0,
width / number_of_characters,
height);
path.AddString(character_array[a].character.ToString(),
character_array[a].font.FontFamily,
0,
character_array[a].font.SizeInPoints,
rect,
format);
}
graphics.FillPath(Brushes.Black, path);
Response.ContentType = "image/gif";
bmp.Save(Response.OutputStream, ImageFormat.Gif);
//we dispose all the Graphics objects
for (int z = 0; z < character_array.Length; z++)
character_array[z].font.Dispose();
path.Dispose();
graphics.Dispose();
bmp.Dispose();
First a Bitmap object is created, which is what we will eventually output. After obtaining a reference to it's GDI Graphics object, we begin drawing on it. First a background rectangle with a Red brush is drawn and then a GraphicsPath object is created. We can use the built-in AddString method of the GraphicsPath to easily style and add our characters. We could have easily output the whole string at once, but we loop through each character to apply individual styling of FontFamily and font size to each character. Finally, we change the ResponseType of the our encapsulating page and save the bitmap to the built-in OutputStream (which will block all other output to the page).
Lately, I've seen a lot of really bad SQL come through the office on interviews. In our extensive interview process, many of the other developers focus on simple SQL problems, which is really all that is necessary for the day-to-day job at Demand.
Unlike some of the other developers, my boss constantly chastises me for worrying about security too much. I can't deny that I do obsess about security too much, given my background, but because of that I'll occasionally ask the following question, which I think any SQL developer should be able to answer:
8. Given a simple login box (with username and password fields), what input will compromise the database in a susceptible system?
I'll even go so far as to show you the poorly written code that will allow this... (Note that the code is looking for the password of the given user and will check it in C# code below, that's all it takes to allow an exploit).
string sql = string.Format(@"
SELECT
password
FROM [dbo].[Accounts]
WHERE username='{0}' ", Request.Form["username"]);
DataTable dt = new DataTable();
SqlConnection connection = new SqlConnection(connection_string);
SqlCommand command = new SqlCommand(sql, connection);
command.CommandType = CommandType.Text;
connection.Open();
SqlDataReader sdr = command.ExecuteReader(CommandBehavior.CloseConnection);
dt.Load(sdr);
sdr.Close(); //this will close the connection too
if (dt.Rows.Count > 0)
if (dt.Rows[0]["password"].ToString() == Request.Form["password"])
LoginUser();
First, the exploit. There are an infinite number of things you can do with a SQL Injection, but we'll use the simple input:
' AND 0=1 UNION SELECT '123456' -- in the username field and 123456 in the password field.
This turns the executed query into:
SELECT
password
FROM [dbo].[Accounts]
WHERE username='' AND 0=1 UNION SELECT '123456' --'
First, you'll note that the -- placed at the end will comment out the original query ending, including the single-quote. The end result has the WHERE-clause being interpreted as username='' AND 0=1. Obviously, the AND 0=1 portion will cause the entire clause to return FALSE. At this point, we UNION a literal '123456', which will allow us access to the site. (Note that this is a very simple example, in most cases you would most likely be selecting back the matching user account and hence could theoretically login to any account.)
Some may argue that I made the impossible possible by revealing the original source code, but that's not necessarily true. For anyone that's attempting a SQL-injection, it's most likely not a large leap to write a script to brute force the parameters of the victim query. At that point, you can literally do whatever you want by using a little ingenuity and the INFORMATION_SCHEMA object, supported by most RDMS.
.NET Quickies
* Using a method of the String object, what is the optimized .NET way of performing the (often executed) compound conditional:
if (some_string != null && some_string != "")
DoSomething();
String.IsNullOrEmpty()
(in my tests for this blog entry, it consistently performed 40-45% faster)
* When encoding data, what is the key overall difference between hashing and encrypting?
Hashing is a one-way mapping, while encryption has a corresponding decryption which will reverse the process.
* What is the effect of making a method of a class static and what might it's use be?
Static methods are not associated with any one instance of the class, nor are they able to access any instance fields of a class. Thus, instead of invoking the methods through an instance call, you use the name of the class instead (since you are referencing the single Type object of that class maintained by .NET), like so:
string s = "some test string";
bool starts_with_some = s.StartsWith("some");
//StartsWith uses the instance s
bool not_null_or_empty = string.IsNullOrEmpty(s);
//IsNullOrEmpty is a static method
Static methods allow you to provide stand-alone methods that relate to a classes functionality. Another example might be a Country class. I might use it to represent a single country object, with fields/properties like CountryID, Name or ZipCodeList. I might also include a method to use the current class' data like GetIPRange() or FindContinent(). Finally, I could also add stand-alone (static) methods, like Country.GetAllCountries() to return a List
I want to add the additional note that since I've been seeing an increase in the number of "demand media" interview questions Google searches hit my blog, we have been working on restructuring our interview process to change the questions around and are now working towards a much more hands-on interview. Note that part of the review process includes reviewing my blog for any questions and removing them (or limiting the use of them) from our interview process. So make sure you know how to use .NET in ways outside the scope of these questions.
I also want to encourage people to continue contacting me with your questions and comments. As long as there is an interest in the topic, I will continue to present real-life .NET interview questions.
0 comments
Javascript and ASP.NET Hacks
September 12, 2007 • 7:25AM • permalink
Both ASP.NET and Javascript can be extremely useful, in entirely different ways. ASP.NET is a great server-side environment and Javascript can be used to enhance the client-side experience. In my experience, junior developers often have a difficult time getting the two to play nicely together, so I thought I would share a few common tricks. (Please note tricks apply whether you code using Visual Basic or C#. Also, many of these tricks or similar implementations of them are trivial to implement in many other server-side languages, such as PHP, Python or JSP.)
1) Data Injection (ASP.NET => Javascript)
First, in the code-behind area of the page, we setup a simple string variable from an external source:
private string username;
public string Username
{
get { return username; }
set { username = value; }
}
public void Page_Load(object sender, EventArgs e)
{
username = Request["username"];
}
Then, in the front-end part of the page, we can use this variable for a Javascript injection:
<head>
<script type="text/javascript">
alert('<% =Username %>');
</script>
</head>
The result, is that when the page loads, the value that is in username is injected into the Javascript. So if the value Adam is passed into the page, the Javascript is transformed at runtime to:
<head>
<script type="text/javascript">
alert('Adam');
</script>
</head>
So that when the page loads, the alert box appears with the requested username:

2) Input Injection (Javascript => ASP.NET)
There are many ways to get data from a HTML form to the ASP.NET code, including the basic query string and basic form post. Sometimes though, a server control doesn't contain the dynamic nature needed to properly collect user input. In the following example, we're going to collect data from multiple checkboxes and pass them back as a comma-delimited string.
Before I begin, you may ask why I wouldn't just use a CheckboxList or a series of single Checkboxes. You could (especially after reading the third trick that I will present below), but that would make it a little more difficult to do a few dynamic tricks with the checkboxes, like a Select All or Select None functionality.
First, the back-end code:
private string received_values;
public string ReceivedValues
{
get { return received_values; }
set { received_values = value; }
}
public void Page_Load(object sender, EventArgs e)
{
received_values = Request.Form["sent_value"];
}
All we're doing is making the results of a HTTP form post, with the input name "sent_value", publically accessible.
Then, on the front-end, we're going to create our checkboxes based on the contents of a static array. This is only to make a simple example, and our "IDValues" could represent anything from friends on a buddylist, stocks in a portfolio, books in a library, software titles in a shopping cart - anything you could retrieve from a database, XML feed, etc.
Here's the entire code listing. The explanation is below it.
<form id="the_form" method="post">
<% int[] IDValues = new int[] { 5, 10, 25, 50 }; %>
<% for (int x = 0, cnt = IDValues.Length; x < cnt; ++x) { %>
<input type="checkbox" id="someid_<% =IDValues[x] %>" /> <% =IDValues[x] %>
<% } %>
<input type="hidden" id="sent_value" name="sent_value" value="" />
<input type="button" onclick="doSubmit(); return false;" value="Submit" />
</form>
<% if (!string.IsNullOrEmpty(ReceivedValues)) { %>
<strong>Received Values:</strong> <% =ReceivedValues %>
<% } %>
<script type="text/javascript">
function doSubmit()
{
var frm = document.getElementById('the_form');
var post_string = "";
for (var x = 0, cnt = frm.elements.length; x < cnt; ++x)
{
if (frm.elements[x].checked)
post_string += frm.elements[x].id.substring(7) + ",";
}
if (post_string.length > 0)
post_string = post_string.substring(0, post_string.length - 1);
document.getElementById('sent_value').value = post_string;
frm.submit();
}
</script>
It's actually very simple! We create four checkboxes, easily identified by the prefix 'someid_' in their id property. When the button is clicked, we obtain a reference to the form object and loop through all of its elements. If the item is checked (obviously indicating a checkbox in our example), then we remove the 'someid_' prefix and append the id to a running string, with a comma-delimeter.
After traversing the whole form, we cleanup the string by removing the extraneous comma and store the value in a hidden input tag we've created already. This is the key to posting the resulting values to the back-end.
Upon submission, the ReceivedValues string will be populated and will be output, like so:

3) Javascript on ASP.NET Controls (Javascript <=> ASP.NET)
Finally, there are a few additional tricks you can mix in to ease the integration of Javascript and ASP.NET. A very simple example would be a form that requires both client-side validation and server-side validation.
I'll assume the reader can already output an error message using either Javascript or ASP.NET. In this example, we'll assume that we have an existing system to validate a page and upon error, set the InnerHtml property of a div object with the ID 'ErrorMessage'. (Note that divs are implemented as HttpGenericControl objects on the back-end)
If we decided to add in Javascript validation as well (possibly to implement a 'strong password' indicator like Live.com), we don't want to have to create a new location for Javascript error messages.
Using a simple trick, we don't have to:
<form runat="server">
<div id="ErrorMessage" runat="server"></div>
<script type="text/javascript">
document.getElementById("<% =ErrorMessage.ClientID %>").innerHTML = "Cool, eh?";
</script>
</form>
That's all there is to it! While this example is oversimplified, it is easy to see how it can be implemented and extended. This applies to all the examples given above. With the plethora of ASP server controls and Javascript methods available, not to mention AJAX implementations, it's very easy to see how you can make your sites much more dynamic by using the above tricks.
1) Data Injection (ASP.NET => Javascript)
First, in the code-behind area of the page, we setup a simple string variable from an external source:
private string username;
public string Username
{
get { return username; }
set { username = value; }
}
public void Page_Load(object sender, EventArgs e)
{
username = Request["username"];
}
Then, in the front-end part of the page, we can use this variable for a Javascript injection:
<head>
<script type="text/javascript">
alert('<% =Username %>');
</script>
</head>
The result, is that when the page loads, the value that is in username is injected into the Javascript. So if the value Adam is passed into the page, the Javascript is transformed at runtime to:
<head>
<script type="text/javascript">
alert('Adam');
</script>
</head>
So that when the page loads, the alert box appears with the requested username:

2) Input Injection (Javascript => ASP.NET)
There are many ways to get data from a HTML form to the ASP.NET code, including the basic query string and basic form post. Sometimes though, a server control doesn't contain the dynamic nature needed to properly collect user input. In the following example, we're going to collect data from multiple checkboxes and pass them back as a comma-delimited string.
Before I begin, you may ask why I wouldn't just use a CheckboxList or a series of single Checkboxes. You could (especially after reading the third trick that I will present below), but that would make it a little more difficult to do a few dynamic tricks with the checkboxes, like a Select All or Select None functionality.
First, the back-end code:
private string received_values;
public string ReceivedValues
{
get { return received_values; }
set { received_values = value; }
}
public void Page_Load(object sender, EventArgs e)
{
received_values = Request.Form["sent_value"];
}
All we're doing is making the results of a HTTP form post, with the input name "sent_value", publically accessible.
Then, on the front-end, we're going to create our checkboxes based on the contents of a static array. This is only to make a simple example, and our "IDValues" could represent anything from friends on a buddylist, stocks in a portfolio, books in a library, software titles in a shopping cart - anything you could retrieve from a database, XML feed, etc.
Here's the entire code listing. The explanation is below it.
<form id="the_form" method="post">
<% int[] IDValues = new int[] { 5, 10, 25, 50 }; %>
<% for (int x = 0, cnt = IDValues.Length; x < cnt; ++x) { %>
<input type="checkbox" id="someid_<% =IDValues[x] %>" /> <% =IDValues[x] %>
<% } %>
<input type="hidden" id="sent_value" name="sent_value" value="" />
<input type="button" onclick="doSubmit(); return false;" value="Submit" />
</form>
<% if (!string.IsNullOrEmpty(ReceivedValues)) { %>
<strong>Received Values:</strong> <% =ReceivedValues %>
<% } %>
<script type="text/javascript">
function doSubmit()
{
var frm = document.getElementById('the_form');
var post_string = "";
for (var x = 0, cnt = frm.elements.length; x < cnt; ++x)
{
if (frm.elements[x].checked)
post_string += frm.elements[x].id.substring(7) + ",";
}
if (post_string.length > 0)
post_string = post_string.substring(0, post_string.length - 1);
document.getElementById('sent_value').value = post_string;
frm.submit();
}
</script>
It's actually very simple! We create four checkboxes, easily identified by the prefix 'someid_' in their id property. When the button is clicked, we obtain a reference to the form object and loop through all of its elements. If the item is checked (obviously indicating a checkbox in our example), then we remove the 'someid_' prefix and append the id to a running string, with a comma-delimeter.
After traversing the whole form, we cleanup the string by removing the extraneous comma and store the value in a hidden input tag we've created already. This is the key to posting the resulting values to the back-end.
Upon submission, the ReceivedValues string will be populated and will be output, like so:

3) Javascript on ASP.NET Controls (Javascript <=> ASP.NET)
Finally, there are a few additional tricks you can mix in to ease the integration of Javascript and ASP.NET. A very simple example would be a form that requires both client-side validation and server-side validation.
I'll assume the reader can already output an error message using either Javascript or ASP.NET. In this example, we'll assume that we have an existing system to validate a page and upon error, set the InnerHtml property of a div object with the ID 'ErrorMessage'. (Note that divs are implemented as HttpGenericControl objects on the back-end)
If we decided to add in Javascript validation as well (possibly to implement a 'strong password' indicator like Live.com), we don't want to have to create a new location for Javascript error messages.
Using a simple trick, we don't have to:
<form runat="server">
<div id="ErrorMessage" runat="server"></div>
<script type="text/javascript">
document.getElementById("<% =ErrorMessage.ClientID %>").innerHTML = "Cool, eh?";
</script>
</form>
That's all there is to it! While this example is oversimplified, it is easy to see how it can be implemented and extended. This applies to all the examples given above. With the plethora of ASP server controls and Javascript methods available, not to mention AJAX implementations, it's very easy to see how you can make your sites much more dynamic by using the above tricks.
HTTP Status Code 307 - Temporary Redirect
August 19, 2007 • 9:41AM • permalink
I'm sure that many of you haven't gotten past the title before saying, "No, a HTTP Status Code of 302 is the Temporary Redirect." I'd like to briefly explain the difference between the two and show you how you can benefit from a 307 redirect. Please also note, that this is a temporary redirect and should probably be avoided in most production situations. You will see one case in particular below where this can be useful.
In .NET, the standard way to redirect between pages is to use the Response.Redirect() method. This implicitly flushes the Response buffer and instead of sending back HTML (with a status code 200 OK), it sends the user a 302 Found code, meaning the requested page was found, but under a different URI. The server also sends back the new URI in the Location header that should be subsequently retrieved by the client.
This works in most cases, except for one minor problem: the case when you're trying to POST data to the server. There are many ways around this problem (including changing it to a GET/QueryString combo), but if a POST is necessary a 307 Temporary Redirect status code will indicate to the browser that the POST method should be retained.
This can be very valuable when developing on a machine with Windows XP Pro (and hence IIS 5.1 which doesn't allow you to identify web sites with host headers.) Under IIS, I setup multiple projects with the directory schema C:\Inetpub\wwwroot\ProjectName\. In my code, I prefix all links with an Web.config driven value that indicates the subdirectory off the root that the project resides in. This way, I can use the value /ProjectName/ in dev and / in production and the links will work in both environments. I don't like to pass these values around though, so when I recently wrote a small Flash application specifically for one website, I wanted to hardcode the SWF to POST to 'http://www.domainname.com/'. It seemed like a lot of work at first, but with a 307 redirect, it was simple!
If the Flash file was hardcoded to POST to 'http://www.domainname.com/PageName.aspx', you just create a file in the localhost root directory (C:\Inetpub\wwwroot\ in my example) called PageName.aspx and run the following on Page_Load():
Response.StatusCode = 307;
Response.RedirectLocation = "/ProjectName/PageName.aspx";
This will allow proper testing in IIS 5.1 and will redirect to the correct page with a POST method and all associated form data.
One final note as to why this should only be used for testing. Part of the definition of a 307 status code directs that browsers should prompt the user of the redirect and allow them to replicate the action (for older browsers). Firefox, in particular, is one browser that fully supports the standard and prompts the user, asking if they want to allow the form data to be sent via a POST. Since this could lead to a very poor user experience, I would recommend limiting use of the 307 status code to development and testing environments only.
In .NET, the standard way to redirect between pages is to use the Response.Redirect() method. This implicitly flushes the Response buffer and instead of sending back HTML (with a status code 200 OK), it sends the user a 302 Found code, meaning the requested page was found, but under a different URI. The server also sends back the new URI in the Location header that should be subsequently retrieved by the client.
This works in most cases, except for one minor problem: the case when you're trying to POST data to the server. There are many ways around this problem (including changing it to a GET/QueryString combo), but if a POST is necessary a 307 Temporary Redirect status code will indicate to the browser that the POST method should be retained.
This can be very valuable when developing on a machine with Windows XP Pro (and hence IIS 5.1 which doesn't allow you to identify web sites with host headers.) Under IIS, I setup multiple projects with the directory schema C:\Inetpub\wwwroot\ProjectName\. In my code, I prefix all links with an Web.config driven value that indicates the subdirectory off the root that the project resides in. This way, I can use the value /ProjectName/ in dev and / in production and the links will work in both environments. I don't like to pass these values around though, so when I recently wrote a small Flash application specifically for one website, I wanted to hardcode the SWF to POST to 'http://www.domainname.com/'. It seemed like a lot of work at first, but with a 307 redirect, it was simple!
If the Flash file was hardcoded to POST to 'http://www.domainname.com/PageName.aspx', you just create a file in the localhost root directory (C:\Inetpub\wwwroot\ in my example) called PageName.aspx and run the following on Page_Load():
Response.StatusCode = 307;
Response.RedirectLocation = "/ProjectName/PageName.aspx";
This will allow proper testing in IIS 5.1 and will redirect to the correct page with a POST method and all associated form data.
One final note as to why this should only be used for testing. Part of the definition of a 307 status code directs that browsers should prompt the user of the redirect and allow them to replicate the action (for older browsers). Firefox, in particular, is one browser that fully supports the standard and prompts the user, asking if they want to allow the form data to be sent via a POST. Since this could lead to a very poor user experience, I would recommend limiting use of the 307 status code to development and testing environments only.
|
page 1 of 1
|