Developing ASP.NET Applications

Considering IronPyth on Web Application Compatibility

IronPython (and Python for that matter) have huge potential for making Web sites significantly easier to build and manage. In fact, there are a lot of options for using Python (and IronPython) to perform Web development tasks that you can see at http://wiki.python.org/ moin/WebProgramming and http://www.fredshack.com/docs/pythonweb.html. The problem with IronPython is that it can’t use the C/C++ libraries used by Python, which means that some of these solutions won’t work. For example, it’s unlikely that you could use IronPython in a Common Gateway Interface (CGI) application because CGI relies on modules written in C/ C++. Consequently, the first rule for Web development with IronPython is to make sure that IronPython can actually interact with the desired modules.

Unfortunately, IronPython isn’t integrated into Visual Studio. Because Visual Studio relies on some level of integration to provide full Web development support, you’ll almost certainly find that some projects are out of reach. It’s not that you can’t create them using IronPython; it’s that the process would be so horribly time consuming and error prone that using another language would be a better idea. You do have full .NET capability when working with IronPython, as demonstrated by the example in this chapter. All you really need is to add Dynamic Language Runtime (DLR) support to the picture and things will work out just fine.

The picture isn’t all gloom. IronPython actually proves to be a good development language for some tasks. As you progress through this chapter, you’ll find that IronPython actually makes code behind tasks exceptionally easy. It’s conceivable that you can build and test simple Web projects using IronPython considerably faster than using another language such as C# or Visual Basic.NET.

It’s important to remember that you don’t have to work with IronPython alone. Your Web application can include other technologies, such as Silverlight. You can also rely on other languages, such as C# or Visual Basic.NET, to fill in the gaps in IronPython coverage. Having another language at your disposal is all about flexibility, and IronPython is a great add-on language for any Web application project.

Obtaining ASP.NET Dynamic Language Support

Microsoft built ASP.NET with extensibility in mind, but the native support tends to focus more on static languages such as Visual Basic.NET and C#, rather than dynamic languages such as IronPython. The Dynamic Language Runtime (DLR) is an add-on for ASP.NET that makes it possible to use languages, such as IronPython, that make typing decisions at run time, rather than compile time. You must download and install this support before you can use IronPython to create a Web application. The following sections describe DLR in more detail.

DLR Limitations

The DLR is currently a work in progress. The overall feel is of an alpha product that shows promise, but still has more than a few warts. In addition, the product currently lacks these features (in order of their importance to you as a developer):

  • IntelliSense: Most developers depend on IntelliSense to provide clues as to what works and what doesn’t — in essence, what to write next. Without IntelliSense support, most developers find themselves peaking at the documentation and spending hours being frustrated with the development environment. Because a default relies so heavily on IntelliSense during the entire development process, its lack is keenly felt. Let’s hope that Microsoft will choose to add this feature sooner rather than later.
  • Limited designer support: If you worked through the examples in Chapter 8, you probably have a good idea of why designer support is so important. Sure, you can create a perfectly usable interface without a designer, but doing so becomes time consuming and many developers give up before they get their user interface completely right. The better the designer support, the faster you can work.
  • Project templates: The lack of templates isn’t anything new. You’ve created examples throughout this book without them, so not having them now isn’t that big a deal. However, it will be nice to have the convenience of project templates when Microsoft creates them.
  • ASP.NET Model-View-Controller (MVC) pattern: MVC is a development pattern that Microsoft is pushing very hard because it provides better control over the development process. You can learn more about ASP.NET MVC at http://www.asp.net/mvc/. Microsoft eventually plans to add MVC to DLR by extending MVC for IronRuby (see http:// github.com/jschementi/ironrubymvc for additional details).
  • Language Services Support: A new language feature that Microsoft plans to provide sometime in the future. Details about this feature are unavailable as of this writing, but it’s likely that Language Services Support will somehow make DLR more flexible and able to support a myriad of languages.

If you read the information at http://www.asp.net/DynamicLanguages/ carefully, you notice that it contains a wealth of caveats. The DLR is essentially an alpha version of a product that may not even appear as part of ASP .NET. Consequently, you need to use DLR to see what’s possible, rather than as a production tool for needs you have today. Anything you create using DLR today is likely to require updates and changes tomorrow (assuming you can use DLR at all). The lack of solid DLR commitment by Microsoft is one reason this chapter provides an overview of ASP.NET application development, rather than in-depth information.

Getting DLR

Before you can use DLR, you must download and install it. The files you need for the installation appear at http://aspnet.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=17613. Download both the documentation and binaries files so that you have a complete setup. The documentation file is very small, so you might not think you even received the download at first.

The files are simple ZIP files, so you can extract them to your root directory. The examples in this chapter use a source folder of C:ironpython-2.6-beta1-aspnet-200905 for the DLR-specific examples. You need to change the path in the examples to match the location you used to extract the files on your machine.

The ironpython-2.6-beta1-aspnet-200905.ZIP file contains two folders: bin and examples. The bin folder contains a complete set of IronPython files, including the files required to make an IronPython script work as an ASP.NET application.

Using the Sample Applications

The ironpython-2.6-beta1-aspnet-200905examples folder contains two example applications. You should run at least one of these examples to ensure you have a good installation (simple as it is, sometimes there’s a configuration on your machine that prevents the examples from working as intended). To start as simply as possible, use the following steps to run the basic Hello Web forms example:

  1. Open a command prompt. It doesn’t have to be a VS2010 command prompt — any command prompt will do. If you’re using Vista or above, make sure you open the command prompt with administrator rights by right-clicking the Command Prompt icon in the Start menu and choosing Run As Administrator from the context menu.
  2. Type CD WINDOWSMicrosoft.NETFrameworkv2.0.50727 and press Enter to change directories to the .NET Framework 2.0 folder on your system. If you don’t have the .NET Framework 2.0 installed on your system, then type CD Program FilesCommon Files Microsoft SharedDevServer10.0 and press Enter to gain access to the ASP.NET Development Server folder on your system.
  3. Type WebDev.WebServer /port:85 /path:C:ironpython-2.6-beta1-aspnet-200905 exampleshello-webforms and press Enter (change your path information if you need to do so). You may need to type WebDev.WebServer20 if you’re using an alternate folder location. This action will start the ASP.NET Development Server on port 85. You’ll see an ASP.NET Development Server icon appear in the Notification Area.
  4. Right-click the ASP.NET Development Server icon and choose Open in Web Browser from the context menu. Your Web browser should open up and you should see a simple Web page like the one shown in Figure 11-1.

    This simple Web page relies on IronPython for support.
    Figure 11-1: This simple Web page relies on IronPython for support.
  5. Test the Web page to see if it works. Type your name in the Enter Your Name field and click Submit. You should see your name appear in place of the Your Name Here label shown in Figure 11-1. It’s a really simple example, but it will tell you whether you‘re getting the right results.
  6. Right-click the ASP.NET Development Server icon and choose Stop from the context menu. The server is no longer available.

The DLR package includes a second example. To use it, simply type WebDev.WebServer /port:85 / path:C:ironpython-2.6-beta1-aspnet-200905examplesalbum-handler and press Enter at the command prompt (again, make sure you use a path that matches your machine setup). This example is a little more complicated. When you initially display the browser, you see a list of filenames, which isn’t particularly helpful. Click the album-ipy.aspx entry and wait a few seconds. Eventually, you’ll see the Test icon shown in Figure 11-2.

The second example is a little more interesting
Figure 11-2: The second example is a little more interesting — at least it has graphics.

Click the Test icon and you’ll see more graphics. You can click the La Flore icon to see some flowers, or click one of the scenic images, as shown in Figure 11-3. Spend a bit of time with this application and you’ll find that it really is pretty interesting. Now, consider that this application is written in IronPython. Even though DLR isn’t a fully supported technology yet, it does have some amazing capabilities.

Creating a Web Site

You might think that creating an IronPython Web site is going to be complex at first — especially with a lack of IDE support. However, an IronPython Web site doesn’t really contain many parts that you have to worry about. A basic Web site starts with the root folder, which contains three items:

  • An Active Server Page Framework (.ASPX) file containing the user interface
  • The code behind file for the .ASPX file containing IronPython code
  • The Web.CONFIG file that contains all of the required configuration entries (such as the location of the special binaries used to interpret the IronPython script)

In addition to these files, you need a bin folder that contains the executables for working with IronPython. These files won’t vary between projects, so you may as well copy the bin folder whenever you create a new project. The following list is the files found in the bin folder.

  • IronPython.DLL
  • IronPython.Modules.DLL
  • Microsoft.Dynamic.DLL
  • Microsoft.Scripting.Core.DLL
  • Microsoft.Scripting.DLL
  • Microsoft.Scripting.ExtensionAttribute.DLL
  • Microsoft.Web.Scripting.DLL

It’s important to remember that IronPython is scripted. As a consequence, much of the compiled language baggage that you might have had to consider in the past isn’t an issue when working with IronPython. Don’t let the seeming simplicity of the Web site fool you, however; IronPython is just as capable as any other language.

Building a Basic ASP.NET Site Using IronPython

You’ve seen someone else’s examples for working with IronPython on a Web site. Now it’s time to create an IronPython Web site of your own. The example in this section isn’t meant to do anything too impressive. This section focuses on a process you can use to build ASP.NET applications of your own instead. The following sections describe every step you need to take to create any ASP.NET application using IronPython.

Creating the Project

Neither Visual Studio nor DLR provides a project template for you to use. In addition, you have more work to do when creating an ASP.NET application, so creating a project isn’t quite as easy as it should be. The DLR instructions suggest copying the hello-webforms folder to another location and using it as a starting point, which will work but will prove cumbersome. The following steps create a different kind of setup, one that will prove better in the long run, but require more work on your part now.

  1. Create a folder for your application. The example uses Calculator, but you can use any name you want.
  2. Copy the hello-webformsbin folder to your project folder.
  3. Create a .BAT file (the example uses Start.BAT) with the following content:
    [code]
    @Echo Off
    REM Change this directory to the location of WebDev.Webserver
    CD WINDOWSMicrosoft.NETFrameworkv2.0.50727
    REM Start the Web server.
    Start /B WebDev.WebServer /port:%1 /path:%2
    REM Open the Web browser to the right Web site.
    Start “C:Program FilesMozilla FirefoxFirefox” http://localhost:%1/
    @Echo On
    [/code]
    This batch file changes directories to the correct location for the WebDev.Webserver utility. It then starts the WebDev.Webserver utility with the port and path information you provide as part of the project arguments. Finally, it starts your browser so you can see the results.
  4. Start Visual Studio and choose File ➪ Open ➪ Project/Solution. Locate CMD.EXE found in the WindowsSystem32 folder and click Open. This step creates a project based on the command processor.
  5. Right-click cmd in Solution Explorer and choose Properties from the context menu. You see the General tab of the cmd Properties window, as shown in Figure 11-4.

    Set the properties for your project.
    Figure 11-4: Set the properties for your project.
  6. Type /C Start.BAT 85 “C:255 – Source CodeChapter11Calculator“ in the Arguments field. The arguments start with the /C command line switch, which tells the command processor to process all of the commands you’ve requested, and then terminate itself. The Start.BAT argument is the file you created in Step 3. This batch file requires two input arguments, the port number you want to use and the location of the example application.
  7. Type the location of your project, such as C:255 – Source CodeChapter11 Calculator, in the Working Directory folder.
  8. Right-click the Solution entry in Solution Explorer and choose Add ➪ New Item from the context menu. You’ll see the Add New Item dialog box shown in Figure 11-5.
  9. Highlight the HTML Page template and type Default.ASPX in the Name field. Click Add. Visual Studio adds a new ASPX file to your project.
  10. Right-click the Solution entry in Solution Explorer and choose Add ➪ New Item from the context menu to display the Add New Item dialog box again.
  11. Highlight the Text File template and type Default.ASPX.py in the Name field. Click Add. Visual Studio adds the code behind file for the Default.ASPX page.
  12. Copy the Web.CONFIG file from the hello-webforms folder to your project folder.
  13. Right-click the Solution entry in Solution Explorer and choose Add ➪ Existing Item from the context menu to display the Add Existing Item dialog box shown in Figure 11-6.
    Select items to add from the Add New Item dialog box.
    Figure 11-5: Select items to add from the Add New Item dialog box.

    Copy the Web.CONFIG file from an existing project.
    Figure 11-6: Copy the Web.CONFIG file from an existing project.
  14. Locate and highlight the Web.CONFIG file as shown in Figure 11-6. Click Add. Your project is now ready to go.

Defining the User Interface

The template used for this example is actually an .HTM file so it doesn’t contain a few essential entries; you need to use it as an .ASPX file. First, you must tell the Web service which language to use and where to find the code behind file. Add the following code as the first line in the .ASPX file.

[code]
<%@ Page Language=”IronPython” CodeFile=”Default.aspx.py” %>
[/code]

When you complete this step, close and then reopen the Default.ASPX file. Otherwise, the IDE is going to spend a lot of time complaining. The next step is to change where the code runs. You want it to run at the server so you change the <head> tag, as shown in the following code:

[code]
<head runat=”server”>
[/code]

Now you need to create content for the Web page. In this case, the user interface provides a simple four-function calculator. Listing 11-1 shows the code needed to perform this task.

Listin g 11-1: Defining a user interface for the example application

[code]
<form ID=”form1” runat=”server”>
<div>
<asp:Label ID=”lblInput” runat=”server”
text=”Type an input value:”/>
<asp:TextBox ID=”txtInput” runat=”server” />
<asp:Label ID=”lblError” runat=”server”
text=”Type a number in the input field!”
style=”color:red”
visible=”false” />
</div>
<div>
<asp:Button ID=”btnAdd” runat=”server” text=”+”
OnClick=”btnAdd_Click” />
<asp:Button ID=”btnSub” runat=”server” text=”-“
OnClick=”btnSub_Click” />
<asp:Button ID=”btnMul” runat=”server” text=”*“
OnClick=”btnMul_Click” />
<asp:Button ID=”btnDiv” runat=”server” text=”/“
OnClick=”btnDiv_Click” />
</div>
<div>
<asp:Label ID=”lblResult” runat=”server”
text=”Current Value:” />
<asp:TextBox ID=”txtResult” runat=”server” text=”0”
readonly=”true” />
</div>
<div>
<asp:Button ID=”btnClear” runat=”server” text=”Clear”
OnClick=”btnClear_Click” />
</div>
</form>
[/code]

As the listing shows, you work with IronPython code in the same way that you work with any .ASPX file. Unfortunately, the designer has not a clue as to what to do with your code, so you have to write it all by hand. Theoretically, you could start a Web project and then simply move the .ASPX file from that project to your IronPython project, but that seems like a lot of work unless your interface is relatively complex. If you find that you can’t quite remember all the ASP.NET controls at your disposal, you can find a complete list at http://www.w3schools.com/ASPNET/aspnet_refwebcontrols.asp in an easily accessible form.

In this case, the controls appear in four separate groups: input, control, result, and clearing. Figure 11-7 shows a typical view of the example form. Some common errors that developers make are not including the runat=”server” attribute and not providing the proper connectivity to events in the code behind, such as OnClick=”btnClear_Click”. Notice that you can use styles, just as you normally do, with the style attribute. One of the attributes that developers can forget about is visible=”false”, which makes the control invisible.

The example form is a simple four-function calculator.
Figure 11-7: The example form is a simple four-function calculator.

Creating the Code Behind

The code behind for this example is in pure IronPython. So, while you won’t see much difference in Default.ASPX, you’ll find that Default.ASPX.py looks completely different from any Web project you’ve worked with in the past. Listing 11-2 shows the code for this example.

Listin g 11-2: Creating the code behind for the example

[code]
# Import the required assemblies.
from System import *
# Respond to an Add button click.
def btnAdd_Click(sender, e):
# Get the current value.
Value = Int32.Parse(txtResult.Text)
# Reset the error message label.
lblError.Visible = False
# Obtain the new input value.
try:
Addition = Int32.Parse(txtInput.Text)
except:
# Display an error message when necessary.
lblError.Visible = True
return
# Perform the task and return the result.
Value = Value + Addition
txtResult.Text = str(Value)
# Respond to a Subtraction button click.
def btnSub_Click(sender, e):
# Get the current value.
Value = Int32.Parse(txtResult.Text)
# Reset the error message label.
lblError.Visible = False
# Obtain the new input value.
try:
Subtract = Int32.Parse(txtInput.Text)
except:
# Display an error message when necessary.
lblError.Visible = True
return
# Perform the task and return the result.
Value = Value – Subtract
txtResult.Text = str(Value)
# Respond to a Multiplication button click.
def btnMul_Click(sender, e):
# Get the current value.
Value = Int32.Parse(txtResult.Text)
# Reset the error message label.
lblError.Visible = False
# Obtain the new input value.
try:
Multiply = Int32.Parse(txtInput.Text)
except:
# Display an error message when necessary.
lblError.Visible = True
return
# Perform the task and return the result.
Value = Value * Multiply
txtResult.Text = str(Value)
# Respond to a Division button click.
def btnDiv_Click(sender, e):
# Get the current value.
Value = Int32.Parse(txtResult.Text)
# Reset the error message label.
lblError.Visible = False
# Obtain the new input value.
try:
Divide = Int32.Parse(txtInput.Text)
except:
# Display an error message when necessary.
lblError.Visible = True
return
# Perform the task and return the result.
Value = Value / Divide
txtResult.Text = str(Value)
# Respond to a Clear button click.
def btnClear_Click(sender, e):
txtResult.Text = ‘0’
[/code]

The code begins by importing the required assemblies. As with any IronPython application, you can use a combination of Python modules and .NET assemblies to create your application. You also have full access to both Python and .NET functionality in your application, so the considerable flexibility that IronPython provides is still available in this environment.

Each of the event handlers must provide both the sender and e arguments as shown. You don’t include a self argument in this case, as you would with other IronPython code. As you might expect, the sender argument contains a reference to the control that called the event handler, while e contains a list of event arguments (normally set to None).

The four math buttons begin by obtaining the current value of txtResult (the output TextBox) as an Int32 value. Because txtResult is read-only, you don’t need to worry about someone putting an incorrect value into it. Consequently, this task doesn’t provide any error trapping code.

The next step is to obtain the new value for the math operation from txtInput. In this case, you’re relying on the user to provide the correct input value, which means that the application code could receive anything. Someone might even try to enter a script in order to fool your application into doing something improper. Using the Int32.Parse() method means that any input other than a number triggers an exception, which your code can handle by simply not processing the input. The try…except structure does just that. If the user inputs an incorrect value, the Web page displays an error message, rather than doing anything with the input.

Now that the code has two inputs to process, it performs the required math operation. After the math operation is complete, the code outputs the result to txtResult.Text.

The btnClear_Click() event handler is relatively simple. All it does is place a 0 in txtResult .Text. The next math operation starts with a zero value, which means that txtResult is cleared.

Starting the Visual Studio Built-In Web Server

It’s time to begin testing your application. Many developers don’t realize it, but the .NET Framework includes a special utility that makes it possible to host Web sites without having a full-fledged Web server. The WebDev.WebServer utility originally appeared as part of the .NET Framework 2.0. When you build an application for testing purposes with Visual Studio, you’re using this built-in Web server to execute the code.

You find the WebDev.WebServer.EXE file in the WINDOWSMicrosoft.NETFrameworkv2.0.50727 folder on your system. Alternatively, you can also find versions of this utility in the Program Files Common FilesMicrosoft SharedDevServer10.0 folder as WebDev.WebServer20.EXE or WebDev.WebServer40.EXE.

The amazing part of the built-in Web server is that it works fine for any Web site using any kind of code. If you want to test your standard HTML pages, that’s fine — just point the built-in Web server to the correct directory on your hard drive. Of course, you can’t run some types of applications because the built-in Web server isn’t designed to handle them. For example, you can’t execute your PHP code. This little deficiency doesn’t matter for your IronPython application, however, because the built-in Web server will see it as a standard ASP.NET application.

Unlike your full-fledged Web server, the built-in Web server doesn’t provide outside access, which is the reason you want to use it to test your unsecured, experimental IronPython Webforms application. You don’t have to worry about prying eyes seeing your tests and possibly using them as a means to gain entrance to your machine. More important, because this server is virtual, it’s less likely that a failed experiment will cause your system to crash. The following sections describe the WebDev.WebServer utility in more detail.

Understanding the WebDev.WebServer Command Line Syntax

The WebDev.WebServer utility provides only a few command line switches because you perform most configuration tasks using a special Notification Area icon. Here’s the command line syntax for this utility.

[code]
WebDev.WebServer /port:<PortNumber> /path:<PhysicalPath> [/vpath:<VirtualPath>]
WebDev.WebServer20 /port:<PortNumber> /path:<PhysicalPath>
[/vpath:<VirtualPath>]
WebDev.WebServer40 /port:<PortNumber> /path:<PhysicalPath>
[/vpath:<VirtualPath>]
[/code]

The following list provides an explanation of each of the command line switches.

  • /port:PortNumber: Defines the port number used to host the application. Because your application isn’t accessible to the outside world and you use a local browser to access the Web server, the port you use isn’t as important as it usually is. You can’t select port 80 if you also have IIS installed on the system. Any port number between 1 and 65,535 will work as long as the port you select isn’t in use.
  • /path:PhysicalPath: Specifies the physical location of the application you want to host in the browser. You must provide the full path, but you don’t include a filename.
  • /vpath:VirtualPath: Provides a virtual path for the application where VirtualPath is normally the application name, such as /MyApp. The default setting provides a virtual path of /.
  • ?: Displays the help information for the WebDev.WebServer utility.

Using the Built-In Web Server with a Batch File

When you use a batch (.BAT) file to start the application, use the Start utility to execute WebDev .WebServer. Otherwise, the Web server won’t start properly. In addition, you should include the Start utility’s /B command line switch (it isn’t mandatory). The /B command line switch tells Windows not to open a new window to start the application. If Windows opens a new window, the Web server will start, but it may not display the Web page. Here’s a modified command line for batch files.

[code]
Start /B WebDev.WebServer /port:7171 /path:”F:My Web Site”
[/code]

Interacting with the Built-In Web Server

The WebDev.WebServer utility creates an icon in the Notification Area when you start it. In fact, a popup message alerts you to the presence of this icon. Right-click this icon and you see three options:

  • Open in Web Browser: Tells the utility to start the default Web browser and navigate to the Web page hosted by the Web server. In most cases, WebDev.WebServer uses the same defaults as any full Web server you have set up on your machine. Otherwise, you can count on these defaults working:
    • Default.HTM
    • Default.ASP
    • Default.ASPX
    • Index.HTM
  • Stop: Stops the server and makes any Web pages inaccessible.
  • Show Details: Displays the ASP.NET Development Server dialog box shown in Figure 11-8 where you can see details about the Web server. In addition, this dialog box provides a link to access the default Web page.
The ASP.NET Development Server dialog box provides details about the Web server.
Figure 11-8: The ASP.NET Development Server dialog box provides details about the Web server.

Considering the Built-In Web Server Limitations

It’s important to realize that we’re not using the WebDev.WebServer utility for production purposes. The following list helps you better understand why you can’t use this utility for every purpose.

  • Functionality: The WebDev.WebServer utility doesn’t create a full-fledged Web server. Some of the functionality you rely on, such as the ability to add users or work with virtual directories, simply isn’t available.
  • Security: Any security that you want to set up has to appear as part of your application in a Web.CONFIG file. The WebDev.WebServer utility does tend to follow whatever rules you set for Internet Information Server (IIS) if you have it installed. However, you can’t count on this behavior when working on your own and you certainly can’t count on it when you send the application to other machines.
  • Administrative tools support: Anything you normally configure through the Internet Information Services console located in the Administrative Tools folder of the Control Panel is unavailable when working with the WebDev.WebServer utility. Consequently, if your application relies on a special ISAPI Filter, you won’t be able to execute it using the WebDev.WebServer utility. The same holds true for anything else that you normally have to add using the Internet Information Services console.
  • Single user Web server: It’s important to remember that this is a single-user Web server. No one outside the local machine can access the Web server because theoretically, it doesn’t exist — it’s virtual. This means that you can’t perform some types of testing using the built-in Web server. The feature that makes it so secure also prevents you from performing some kinds of real-world testing. Multi-user applications simply won’t work with the built-in Web server.

Savvy developers can get around some of the WebDev.WebServer configuration limitations through judicious use of the Web.CONFIG file and by creating resources locally. Make sure you don’t assume that an application won’t work simply because you have to configure it in a new way.

Performing Basic Testing

Your IronPython Web application works just like any other Web application you create. Because IronPython is fully .NET capable, you can use any control set you want within the application. Of course, you also have access to standard Web controls. All of this flexibility increases complexity and makes it necessary to test your application fully.

The example application is relatively simple, so testing isn’t cumbersome. When you first start the application by pressing Ctrl+F5, you see the Web page shown in Figure 11-7. When you type a value into the Type an Input Value field and click one of the math buttons (+, -, *, or /), the application performs the desired task. Trying to input an invalid value triggers an error message like the one shown in Figure 11-9.

Incorrect values trigger an error message.
Figure 11-9: Incorrect values trigger an error message.

Interestingly enough, the scripting nature of IronPython makes it possible to use IronPython to test your Web application. This gives you an advantage over compiled languages such as C# and Visual Basic.NET.

Considering Debugging

You may be wondering whether this project can provide any debugging. The fact is that you don’t get direct debugging when working with DLR, even if you use a full Web server. However, there are four ways in which you can debug your application.

  • Use print statements and other old standbys to determine what your application is doing.
  • Attach the debugger to the running process after the fact by choosing Debug ➪ Attach to Process within Visual Studio.
  • Import the Microsoft.Scripting.Debugging.DLL found in the Program Files IronPython 2.6 folder and add debugging information manually.
  • Rely on the output error message from the Web server, such as the one shown in Figure 11-10.

    The Web server provides you with error messages as needed.
    Figure 11-10: The Web server provides you with error messages as needed.

Even though Webforms use isn’t quite ready for prime time, you should still take time to experiment. At the very least, try the example programs that come with DLR to see that IronPython is a viable Web development language. Use the example application in this chapter as a starting point for your own experimentation. In short, have a bit of fun using IronPython to create Web pages. Consider how the dynamic nature of IronPython could help you in future Web application development, because DLR won’t remain in alpha status forever.

Interesting Ads

The following are more technology-advanced forms of advertising. They are interesting to viewers because they have attributes that are unique or unusual in some way. These attributes might be more apt to grab viewers’ attention and entice them to click on the ad.

  • Expanding ads. An expanding banner ad (Figures 15.1) is one that looks like a normal ad but expands when you click on it, keeping you on the same site rather than transporting you to another site on the Internet. Usually these say “Click to Expand,” and the viewer then can learn more about what the banner is promoting.
  • Animated ads. Animated ads contain a group of images in one file that rotate in a specific order. These ads are more likely to receive a higher click-through than a normal ad because moving images increase the chance of viewers being attracted to and reading the ad. These ads also allow you to deliver more information than in a normal ad because you can show different files, which contain different data. Limit your ads to two to four frames to keep your load time fast and to make sure your viewers read your information.

This is an example of an expanding advertisement. It displays the ad and then prompts the viewer to scroll to see more. When the banner expands, it prompts the viewer to click through to the advertiser’s site.

  • Drop-down menu ads containing embedded HTML. We are seeing an increase in ads containing embedded HTML. These allow viewers to select from a drop-down menu which site they want to visit. These ads are great because instead of making viewers click through and then navigate through your site, as with a conventional ad, these direct your viewers to the page of interest on your site. This type of ad also is great for co-op advertising programs. Several companies targeting the same target market, in a noncompeting way, can use this type of advertising to get more exposure for their dollar.
  • Interstitial ads. These are advertisements that appear in a separate browser window while your visitors wait for a Web page to load.
    Interstitial ads are more likely to contain large graphics, streaming presentations, and more applets than a conventional ad. However, some users have complained that interstitial ads slow access to destination pages.
  • Flash ads. These ads allow you to use rich media in your advertisements. By using this technology, you can incorporate animation and sound into your advertisement.
  • Floating ads and DHTML. These ads appear when you first view a Web page, and they appear to “fly” or “float” over the page for anywhere from 5 to 30 seconds. They tend to obscure your view of the page, and they often disable mouse input until the ad is finished loading so that you must watch it before being able to access the page content. They have a high click-through rate and are great for branding, although their intrusiveness has been questioned.
  • Unicast ads. A unicast ad is basically like a television commercial that runs in a pop-up window. It has animation and sound and can last from 10 to 30 seconds. Although they are like television commercials, they go a step farther in that a viewer can then click on the ad to obtain further information. They have a higher-than-average click-through rate.
  • Rich media ads. These advertisements use dynamic tools such as Flash, HTML forms, Java, ASP, Javascript, or other programming languages or applications that increase the appearance or the functionality of the ad. A rich media ad may include sound or a registration form and usually commands higher CPM levels than other banner ads.

 

Installing the Mobile Client Application

This section describes how Tailspin arranges for users to install the mobile client application on their Windows Phone 7 devices. Users can only install applications on their devices from the Windows Marketplace, so Tailspin must first make sure that the application is available there.

Overview of the Solution

To make it easy for users to find, download, and install the mobile client application, Tailspin wanted to provide a link to the mobile client installer from the public Tailspin website with which users may already be familiar. Tailspin provides a Windows Phone 7-friendly page at the same address as the public Tailspin website. Accessing the site with Microsoft® Internet Explorer® from a desktop device shows a list of available surveys; alternatively, accessing the site with Internet
Explorer from a Windows Phone 7 device shows a link to the installer for the mobile client application.

The developers at Tailspin used a Model-View-Controller (MVC) view engine to display a different page based on the type of device making the request.

For more information about MVC, see “ASP.NET MVC 2” on MSDN® (http://msdn.microsoft.com/en-us/library/dd394709.aspx).

Inside the Implementation

Now is a good time to walk through the code that implements the Windows Phone 7 web page in more detail. As you go through this section, you may want to download the Microsoft® Visual Studio® development system solution for the Tailspin Surveys application from CodePlex (http://go.microsoft.com/fwlink/?LinkId=205602).

To render different pages at the same address based on the type of device, the Tailspin web application uses the WebForm ViewEngine class in the MVC namespace. The application creates a new view engine of type MobileCapableWebFormViewEngine in the Global.asax.cs file. The following code example shows the MobileCapableWebFormViewEngine class in the TailSpin.Web. Survey.Public project.

C#

namespace TailSpin.Web.Survey.Public.Extensions
{
using System;
using System.Web.Mvc;
public class MobileCapableWebFormViewEngine : WebFormViewEngine
{
public override ViewEngineResult FindView(
ControllerContext controllerContext, string viewName,
string masterName, bool useCache)
{
ViewEngineResult result = null
if (this.UserAgentIs(controllerContext, “IEMobile/7”))
{
result = new ViewEngineResult(new WebFormView(
“~/Views/MobileIE7/Index.aspx”, string.Empty), this);
}
if (result == null || result.View == null)
{
result = base.FindView(controllerContext, viewName,
masterName, useCache);
}
return result;
}
public bool UserAgentIs(ControllerContext controllerContext,
string userAgentToTest)
{
return controllerContext.HttpContext.Request
.UserAgent.IndexOf(userAgentToTest,
StringComparison.OrdinalIgnoreCase) > 0;
}
}
}

The FindView method checks the user agent to determine the browser type, and then it returns an appropriate ViewEngineResult instance.

For more information about creating websites for mobile devices, see the post, “Mix: Mobile Web Sites with ASP.NET MVC and the Mobile Browser Definition File,” on the blog, Scott Hanselman’s ComputerZen.com (http://www.hanselman.com/blog/MixMobileWebSitesWithASPNETMVCAndTheMobileBrowserDefinitionFile.aspx).

 

The Right Mail List Technology

There are several ways that you can manage your mail list:

  • Use your email program (not recommended).
  • Use mail list software.
  • Outsource your mail list management.

Using Your Email Program

Although managing your mail list through your email program might look like a great option in that it doesn’t cost you anything and is run from your desktop, giving you ultimate control, there are severe limitations.

Your email program doesn’t easily afford you the opportunity to segment your mail list—those who asked to receive your newsletter versus those who asked to receive notification when you update your What’s New section, for example.

Your email program doesn’t generally provide the technology to quickly and easily personalize your communication—that is, insert the recipient’s first name in designated areas within the email. Email programs do not provide much in the way of tracking information, either.

It would be nice to be able to track such things as how many people opened your email, how many sent a copy to a friend, and how many clicked through and visited your Web site. The tracking technology is generally available only
through mail list software or from the third party that manages your mail list marketing if you choose to outsource this activity.

Another drawback is the administrative headache of manually managing all the “Subscribes,” “Unsubscribes,” and “Changes of Email Address,” particularly when you have multiple sign-up opportunities on your Web site— for example, someone wants to unsubscribe from your e-specials but still wants to receive your newsletter and coupons. The time really has come when you need to invest in mail list software or outsource if you want to take this element of online marketing seriously.

Using Mail List Software

There are numerous mail list management software programs available to help you organize your list distribution. (See Internet Resources at http://www.SusanSweeney.com for links to mail list software programs.) This software enables you to easily add or remove subscribers. Mail list management software enables you to draft and send properly formatted html and text messages directly from within the software, and it generally allows you to personalize your emails quickly and easily.

Most of these programs can be integrated with your Web site so that people can add themselves to your list right from the site. You can also use this software to set up notification mechanisms to reply to subscribers, confirming that they have been added to the list. This makes running your mail list less time-consuming, as the software does most of the work for you.

Using your own mail list software requires an initial investment to purchase the program or an ongoing cost if you use an application service provider (ASP)—a company that develops the mail list software and provides it to you as a monthly or annual service rather than as a product. The major advantage to this model is that as new bells and whistles are introduced, they are immediately available to all users of the software.

The cost to purchase software can range from an entry-level program at $99 to a robust, full-featured program at $2,500. The ASP model could cost you from $30 a month to several thousand dollars if you use an application that charges you per email sent and you have a very large database.

Some of these programs run from your desktop; others have to be run from your server or through your Internet service provider. Many of the ASP model programs are run from the ASP’s server. Most of these programs are sophisticated enough to allow you to segment the email addresses in your database so you know who has asked to receive what from your Web site.

Most of these programs have the personalization capability to allow you to insert a recipient’s first name throughout the correspondence and in the subject line of the message as well. For this to work, you have to capture the first names for each email address in your database. Keep this in mind when asking people if they’d like to give you permission to send them email for whatever reason—in addition to their email address, have a mandatory field for their first name.

More and more of these programs are incorporating tracking features to let you know what’s working and what’s not. From an administrative perspective, many of these programs do a great job of adding new “Subscribes,” deleting
“Unsubscribes,” and managing undeliverable addresses. This feature alone is worth its weight in gold.

Features to look for in mail list software include:

  • Personalization capability—You want to be able to personalize each email by inserting the recipient’s first name in the subject line, in the salutation, and throughout the body of your message.
  • HTML capability—You want to be able to send HTML email (email that looks like a Web page rather than text), which gets much higher readership than text email.
  • Message editor—You want to be able to bring up a past email, edit it, and resend it to a group.
  • Previews—You want to be able to preview your message before you send it to make sure the formatting is correct, the personalization is working, and the message looks great.
  • Spam checker—The spam checker is a valuable tool to ensure that your message has the best chance of being received and not being rejected as spam. You want to be able to run your message through the spam checker to see how you score before you send any message. Today, if you score 5.0 or higher in the spam checker, you will want to edit your message to reduce your score before you send.
  • Dynamic personalization—Each message is personalized based on the individual’s priorities and preferences.
  • Filtering—This feature allows you to send specific messages to parts of your list. You could send a message only to those individuals in a specific state by filtering on the name of the state. You could send a message only to those interested in football if you have that information in a field in your database.
  • Scheduling—This allows you to prearrange to send your email at a specific future time and date. Great if you want to set up all of your “Tips of the Week” in advance, or if you are going to be traveling when you want your newsletter to be sent out.
  • Autoresponders—Some mail list software applications have autoresponders built in. See Chapter 10 for details on their uses.
  • Web site integration—You want your mail list software to work with your Web site so when someone subscribes from your site, his or her contact information is automatically included in your mail list software. If someone wants to unsubscribe or change contact information, this can be taken care of through your site or through the emails you have sent. This really cuts down on the administration you have to deal with.
  • Reporting and tracking—Some mail list software provides reports on messages sent (audience selected, date sent, clicks, total sent, number of bounces), subscriber activity (subscribes, unsubscribes, emails opened), link tracking, and bounce activity (number of undeliverables, hard bounces, soft bounces).

Outsourcing Your Mail List

A third option is to outsource your mail list management to a third party. There are companies that specialize in this service that have a great depth of experience. One such company that we have had the pleasure to work with is Inbox360.com (http://www.inbox360.com).

When you outsource this activity, of course you have a monthly service fee. The software is run from the outsource company’s server or its ISP’s server.

Virtually all of the mail list service providers have the latest software, allowing you to personalize your messages, segment your lists, and get great tracking reports. Generally, administrative issues like adding the “Subscribes,” deleting “Unsubscribes,” and managing the undeliverables are handled by software used by the outsource company.

On the down side, you might lose some control—over content, over your customer, and over timing of your message release. It is imperative to have a clearly laid-out contract with the outsource company, addressing:

  • Ownership of email addresses
  • Use of email addresses
  • Timing of correspondence
  • Final approval of content
  • Responsibility and timelines for replies to subscribers.

It is important that you retain ownership of all email addresses and that the contract clearly states that all subscribers’ names and email addresses are the property of your company. Also include in the contract that you are provided with the current list in digital format every month. This way, if you decide to change service providers, your list goes with you. It takes a lot of effort to build your list, and it is a very valuable asset. Make sure you protect it.

Make sure that your contract clearly states that your email addresses are not to be used by anyone else or provided to anyone else for any purpose whatsoever. People on your list have given you their email addresses in confidence. They
trust that you will not abuse the relationship. Make sure it is in your power to live up to that expectation.

Make sure that you have final control over the timing of your communications. It is important that your messages be delivered when you want them delivered. Timing is everything.

Make sure that your contract has a clause that permits you to approve the final content going out to your list. You want to see and approve everything. You want to make sure the formatting is the way you want it; you want to be sure the personalization is working as it should; and you want to make sure there is no problem with graphics or word wrap.

You want to have a clear understanding with the outsource company regarding replies from messages going out to your list. Often the “From” field, although it looks like it is coming from you, is actually an address that resides with the outsource company. Discuss and agree on what happens when a recipient replies to your communication. Where does it go? When does it go? To receive a batch of replies three weeks after your communication went out is not acceptable.

There are certain benefits to outsourcing this activity to a third party that specializes in mail list marketing. This is their core responsibility. Often the outsource company has been involved in many campaigns—gaining expertise in what works and what doesn’t. Often they can help you tweak your content or format to help achieve your objectives. Also, outsourcing this activity to a competent third party frees up your time and allows you to focus on other priorities.

Resources for Web and Service Developers

Windows Phone 7 includes comprehensive web browsing capabilities. In addition, ASP.NET allows you to detect the client device type making a request so that you can provide the content in a format and style appropriate to the device. For information about how Windows Phone 7 supports web browsing, and how to maximize your application experiences on Windows Phone 7, see Designing Web Sites for Phone Browsers (a PDF document) available from the Microsoft Download
Center (http://go.microsoft.com/?linkid=9713253).

For information about mobile device support in ASP.NET, see “ASP.NET for Mobiles” on the Microsoft ASP.NET website
(http://www.asp.net/mobile/) and “Walkthrough: Adding Support for Devices” on MSDN (http://msdn.microsoft.com/en-us/library/wa642f6e(VS.71).aspx).

Mobile phone applications aimed at the enterprise and for consumer use will usually require access to remote services to be able to obtain information, exchange data, or synchronize content. Typically, on the Microsoft platform, you will implement these services using the Windows Communication Foundation (WCF) technology that is part of the .NET Framework. For information about WCF, see “Windows Communication Foundation” on MSDN (http://msdn.microsoft.
com/en-us/netframework/aa663324.aspx).

A common approach for delivering data or exposing services to mobile devices such as Windows Phone 7 is by using the Representational State Transfer (REST) architectural style for the service. For information about REST-based services, see “REST in Windows Communication Foundation (WCF)” on MSDN (http://msdn.microsoft.com/en-us/netframework/cc950529.aspx) and “An Introduction To RESTful Services With WCF” in MSDN Magazine (http://msdn.microsoft.
com/en-us/magazine/dd315413.aspx). For a definition of the way that REST-based services work, see “Canonical REST Entity Service” on the Microsoft .NET website (http://code.msdn.microsoft.com/cannonicalRESTEntity).

In other cases, such as exchanging small volumes of data between the client and server or calling specific methods on the server, you may decide to use SOAP instead. For more information about WCF, see “Getting Started with WCF” on MSDN (http://msdn.microsoft.com/en-gb/library/ee354180.aspx).