Currently showing entries with the tag: Python
|
page 1 of 1
|
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.
0 comments
10 Things This Skeptic Loves About Python's Syntax
August 15, 2007 • 9:38AM • permalink
First, a note...
Anyone that has worked with me in the past will know what a skeptic I am about new programming languages. I use a lot of different languages (new and old) and operating systems (mostly to fit the constraints of my client's environments) but I prefer to work in C++/C# and in Microsoft Visual Studio. I am always reading one tech book or another, so as a change of pace I started doing some random reading about Python.
While I still prefer C++/C#, the seamless integration of Python with C is very appealing. There is no question that Python is a RAD programming language, especially when looking over the syntax. I wanted to mention ten of my favorites, although there are many more than this - and I've just started learning it! I'm going to give very simple explanations to save space, but I suggest if you find the below interesting that you consider learning Python.
(Please note that the below are in no specific order.)
Divide-and-Floor Operator //
This is an additional divide operator that is used to truncate the entire decimal portion. This is a full truncation of the number with no rounding involved. Since this is a fairly common operation when dealing with floating-point numbers, it's nice to have a simple operator to handle it.
print 10.0 / 3
print 10.0 // 3
x = 10.0
x //= 3
print x
Multiple Assignments In One Statement
Why waste space and time when you need to get things done? Python allows you to perform multiple actions in one statement through use of a comma. Items on either end of the equals sign are indexed in order, as seen here:
x, y = 1, 2
print x + y
increment, decrement = x + y, x - y
print increment, decrement
Scope Delimiters
Python takes a very unique way of delimiting blocks of code: by using whitespace. Lines of code with the same indentations (after the start of a conditional block of code or other scoped construct) are considered part of the same block.
if x > 3:
print 'this is inside the if-statement'
print 'this is too!'
print 'this is executed regardless of whether x is greater than 3'
sprintf Operator %
StringBuilder.AppendFormat is probably one of the .NET functions that I use the most. At 26 letters, even with Intellisense, it's a handful.
Python has a much simpler way of doing the same thing:
print "I eat about %0.2f times every %d days" % (123.456789, 10)
Use of the else Keyword with Loops
Python allows you to append an else clause to both while and for loops that always execute when a break clause is not executed inside the conditional block.
In many situations this allows for the elimination of some branching logic, in addition to allowing developers to remove an additional variable, in many cases, that would only serve to act as a flag for whether or not the intended case executed.
A common example is to implement simple search functionality:
search_number = 699
for i in range(1, 1000):
if (i == search_number):
print 'your number was found'
break
else:
print 'your number was not found'
search_number = 10000
for i in range(1, 1000):
if (i == search_number):
print 'your number was found'
break
else:
print 'your number was not found'
Slice Operator [:]
Nevermind taking a portion of a string, this technique can also be used to take a subset of a list or a dictionary (Python's version of arrays/vectors and hashtables). The example below uses a list.
L = [1, 2, 3, 4, 5, 6]
print L[2:4]
print L[2:]
print L[:3]
print L[:]
Step Operator [::]
This is really an additional parameter to the Slice Operator, but this determines the direction and quantity of the index increment (or decrement), as if iterating through the list. It's best to show with an example or three:
L = [1, 2, 3, 4, 5, 6]
print L[::-1]
print L[::3]
print L[::-2]
Note that this can (obviously) be combined with the Slice Operator above to change the rate of index through sublists. As a continuation from the example above:
print L[:1:-1]
Optional Function Arguments (* and ** Operators)
The whole reason you can use a different programming language in a given situation is the fundamental rule that you should always use the right tool for the right job. In Python, these are known as Arbitrary Function Arguments.
Python gives developers several options (and several combinations of the options) that can be used when using function overloading with optional arguments.
The first is the * operator which returns the remaining arguments of a function in a Python data type known as a tuple.
def SomeFunction(first_arg, *other_args):
print len(other_args)
SomeFunction('test', 'test2', 'test3', 4)
The other operator is the **operator which performs the same action, only returning a dictionary instead of a tuple. This only works with named arguments and will automatically map the argument name to the requested value.
def SomeFunction(**the_args):
print the_args
SomeFunction(a=1, b=2, c=3, d=4, e=5, f=6)
Multiple Comparison Operators
Unlike C and most other languages, Python allows you to chain the various comparison operations together to form complex expressions, just like in algebra. Note that like other boolean expressions, these are short-circuited to increase performance.
a = 1
b = 3
c = 5
print a < b < c
print c < b < a
Stop Reinventing the Wheel
Finally, Python takes many higher level constructs and implementations that have been propagated into multiple languages over the years.
Three (out of more than I can easily count) are shown below: simple string duplication, (theoretically) infinitely sized numbers and the Complex number type. These are shown very briefly below:
print "*" * 20
print 2 ** 100
x = 1 + 3j
y = 1 - 3j
print x * y
If you've ever programmed in any other language, you can see that Python has an extremely unique syntax. It is very unique, but surprisingly intuitive once you've begun to use it. The above is only a small example of how Python syntax varies from other languages. Now, I finally understand what people mean when they refer to Python code as being very "un-Python-like". Since Python supports most of the basic constructs of other languages, it's very easy to do most actions one of two ways: the normal way and the Python way.
Anyone that has worked with me in the past will know what a skeptic I am about new programming languages. I use a lot of different languages (new and old) and operating systems (mostly to fit the constraints of my client's environments) but I prefer to work in C++/C# and in Microsoft Visual Studio. I am always reading one tech book or another, so as a change of pace I started doing some random reading about Python.
While I still prefer C++/C#, the seamless integration of Python with C is very appealing. There is no question that Python is a RAD programming language, especially when looking over the syntax. I wanted to mention ten of my favorites, although there are many more than this - and I've just started learning it! I'm going to give very simple explanations to save space, but I suggest if you find the below interesting that you consider learning Python.
(Please note that the below are in no specific order.)
Divide-and-Floor Operator //
This is an additional divide operator that is used to truncate the entire decimal portion. This is a full truncation of the number with no rounding involved. Since this is a fairly common operation when dealing with floating-point numbers, it's nice to have a simple operator to handle it.
print 10.0 / 3
#prints 3.3333333333333335
print 10.0 // 3
#prints 3.0
x = 10.0
x //= 3
print x
#prints 3.0
Multiple Assignments In One Statement
Why waste space and time when you need to get things done? Python allows you to perform multiple actions in one statement through use of a comma. Items on either end of the equals sign are indexed in order, as seen here:
x, y = 1, 2
print x + y
#prints 3
increment, decrement = x + y, x - y
print increment, decrement
#prints 3, -1
Scope Delimiters
Python takes a very unique way of delimiting blocks of code: by using whitespace. Lines of code with the same indentations (after the start of a conditional block of code or other scoped construct) are considered part of the same block.
if x > 3:
print 'this is inside the if-statement'
print 'this is too!'
print 'this is executed regardless of whether x is greater than 3'
sprintf Operator %
StringBuilder.AppendFormat is probably one of the .NET functions that I use the most. At 26 letters, even with Intellisense, it's a handful.
Python has a much simpler way of doing the same thing:
print "I eat about %0.2f times every %d days" % (123.456789, 10)
#prints I eat about 123.46 times every 10 days
Use of the else Keyword with Loops
Python allows you to append an else clause to both while and for loops that always execute when a break clause is not executed inside the conditional block.
In many situations this allows for the elimination of some branching logic, in addition to allowing developers to remove an additional variable, in many cases, that would only serve to act as a flag for whether or not the intended case executed.
A common example is to implement simple search functionality:
search_number = 699
for i in range(1, 1000):
if (i == search_number):
print 'your number was found'
break
else:
print 'your number was not found'
#prints your number was found
search_number = 10000
for i in range(1, 1000):
if (i == search_number):
print 'your number was found'
break
else:
print 'your number was not found'
#prints your number was not found
Slice Operator [:]
Nevermind taking a portion of a string, this technique can also be used to take a subset of a list or a dictionary (Python's version of arrays/vectors and hashtables). The example below uses a list.
L = [1, 2, 3, 4, 5, 6]
#a (0-based) list
print L[2:4]
#prints [3, 4]
print L[2:]
#prints [3, 4, 5, 6]
print L[:3]
#prints [1, 2, 3]
print L[:]
#prints [1, 2, 3, 4, 5, 6]
Step Operator [::]
This is really an additional parameter to the Slice Operator, but this determines the direction and quantity of the index increment (or decrement), as if iterating through the list. It's best to show with an example or three:
L = [1, 2, 3, 4, 5, 6]
#a (0-based) list
print L[::-1]
#prints [6, 5, 4, 3, 2, 1]
print L[::3]
#prints [1, 4]
print L[::-2]
#prints [6, 4, 2]
Note that this can (obviously) be combined with the Slice Operator above to change the rate of index through sublists. As a continuation from the example above:
print L[:1:-1]
#prints [6, 5, 4, 3]
Optional Function Arguments (* and ** Operators)
The whole reason you can use a different programming language in a given situation is the fundamental rule that you should always use the right tool for the right job. In Python, these are known as Arbitrary Function Arguments.
Python gives developers several options (and several combinations of the options) that can be used when using function overloading with optional arguments.
The first is the * operator which returns the remaining arguments of a function in a Python data type known as a tuple.
def SomeFunction(first_arg, *other_args):
print len(other_args)
SomeFunction('test', 'test2', 'test3', 4)
#prints 3
The other operator is the **operator which performs the same action, only returning a dictionary instead of a tuple. This only works with named arguments and will automatically map the argument name to the requested value.
def SomeFunction(**the_args):
print the_args
SomeFunction(a=1, b=2, c=3, d=4, e=5, f=6)
#prints {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6}
Multiple Comparison Operators
Unlike C and most other languages, Python allows you to chain the various comparison operations together to form complex expressions, just like in algebra. Note that like other boolean expressions, these are short-circuited to increase performance.
a = 1
b = 3
c = 5
print a < b < c
#prints True
print c < b < a
#prints False
Stop Reinventing the Wheel
Finally, Python takes many higher level constructs and implementations that have been propagated into multiple languages over the years.
Three (out of more than I can easily count) are shown below: simple string duplication, (theoretically) infinitely sized numbers and the Complex number type. These are shown very briefly below:
#1) Simple String Extension
print "*" * 20
#prints ********************
#2) Infinitely Sized Numbers (based on Memory Limits)
#Note that ** is the exponent operator in Python.
#Normally 2 ** 64 is the long type limit in most systems.
print 2 ** 100
#prints 1267650600228229401496703205376L
#3) Complex Number Type
x = 1 + 3j
y = 1 - 3j
print x * y
#prints (10+0j)
If you've ever programmed in any other language, you can see that Python has an extremely unique syntax. It is very unique, but surprisingly intuitive once you've begun to use it. The above is only a small example of how Python syntax varies from other languages. Now, I finally understand what people mean when they refer to Python code as being very "un-Python-like". Since Python supports most of the basic constructs of other languages, it's very easy to do most actions one of two ways: the normal way and the Python way.
|
page 1 of 1
|