Tuesday, June 30, 2009
#
My Toolbox column in the July 2009 issue of MSDN Magazine is available online and includes the following reviews:
- ApexSQL Enforce - I've reviewed source code static analysis tools in previous issues, such as Microsoft's FxCop and StyleCop programs. ApexSQL Enforce is a static analysis tool for your database. In a nutshell, it runs a series of rules against a specified database, ranging from security concerns to data modeling.
- Podcasts of Note: Hanselminutes - in addition to a great blog, Scott Hanselman also hosts a weekly podcast show, Hanselminutes. These roughly 30-minute long shows usually include a guest and focus on a specific development-related topic, like ADO.NET Services, getting started with Domain Driven Design, and an overview of jQuery. These high-quality and educational productions are great material for your daily commute or time at the gym.
- Terminals - Terminals is a free, open source project that provides a multi tab UI for connecting to remote computers. Terminals supports Terminal Services, Microsoft RDP, VNC, RAS. Telnet, and other protocols and helps consolidate various remote connections into one window. Also included are a number of networking tools, tools for taking and managing screen shots from remote desktops, and one-click access to common administration and network configuration utilities. If you routinely connect to remote computers be sure to check out Terminals.
This issue reviewed Programming Entity Framework, by Julia Lerman. An exerpt from my review follows:
At nearly 800 pages, Programming Entity Framework is fairly hefty, but it offers a solid grounding in using the Entity Framework. The book assumes its readers are intermediate to advanced .NET developers who are already familiar with database concepts, ADO.NET, LINQ, and other core .NET features and spends no time introducing these topics. Instead, the book is packed with walkthroughs that illustrate the use of Entity Framework in various scenarios. It also does a great job pointing out what this first version of the Entity Framework can and cannot do and what use cases are difficult or tricky to implement, along with workarounds where appropriate.
Enjoy! - http://msdn.microsoft.com/en-us/magazine/dd943051.aspx
As always, if you have any suggestions for products, blogs, or books to review for the Toolbox column, please send them to toolsmm@microsoft.com.
Friday, June 19, 2009
#
The final six tutorials in my Hosting Tutorials on www.asp.net have been published. These tutorials walk readers through hosting an ASP.NET website with a web host provider and are aimed at beginning to intermediate ASP.NET developers interested in getting a small- to medium-sized ASP.NET application online. The first six hosting tutorials served as an introduction to the series and provided an overview of core concepts. These current four tutorials examine deploying a data-driven web application. The following four tutorials explored common challenges in deploying data-driven web applications. These final six tutorials look at handling and logging runtime errors in the production environment as well as site administration and advanced deployment options.
- Displaying a Custom Error Page [VB | C#] - What does the user see when a runtime error occurs in an ASP.NET web application? The answer depends on how the website's <customErrors> configuration. By default, users are shown an unsightly yellow screen proclaiming that a runtime error has occurred. This tutorial shows how to customize these settings to display an aesthetically-pleasing custom error page that matches your site's look and feel.
- Processing Unhandled Exceptions [VB | C#] - When a runtime error occurs on a web application in production it is important to notify a developer and to log the error so that it may be diagnosed at a later point in time. This tutorial provides an overview of how ASP.NET processes runtime errors and looks at one way to have custom code execute whenever an unhandled exception bubbles up to the ASP.NET runtime.
- Logging Error Details with ASP.NET Health Monitoring [VB | C#] - Microsoft's health monitoring system provides an easy and customizable way to log various web events, including unhandled exceptions. This tutorial walks through setting up the health monitoring system to log unhandled exceptions to a database and to notify developers via an e-mail message.
- Logging Error Details with ELMAH [VB | C#] - Error Logging Modules And Handlers (ELMAH) offers another approach to logging runtime errors in a production environment. ELMAH is a free, open source error logging library that includes features like error filtering and the ability to view the error log from a web page, as an RSS feed, or to download it as a comma-delimited file. This tutorial walks through downloading and configuring ELMAH.
- Precompiling Your Website [VB | C#] - Visual Studio offers ASP.NET developers two types of projects: Web Application Projects (WAPs) and Web Site Projects (WSPs). One of the key differences between the two project types is that WAPs must have the code explicitly compiled prior to deployment whereas the code in a WSP can be automatically compiled on the web server. However, it is possible to precompile a WSP prior to deployment. This tutorial explores the benefits of precompilation and shows how to precompile a website from within Visual Studio and from the command line.
- Managing Users and Roles On The Production Website [VB | C#] - The ASP.NET Website Administration Tool (WSAT) provides a web-based user interface for configuring Membership and Roles settings and for creating, editing, and deleting users and roles. Unfortunately, the WSAT only works when visited from localhost, meaning that you cannot reach the production website's Administration Tool through your browser. The good news is that there are workarounds that make it possible to manage users and roles on production. This tutorial looks at these workarounds and others.
As with the previous 10 tutorials in this series, each tutorial can be downloaded as a PDF for offline viewing or printing and each tutorial includes a working website that illustrates the concepts discussed in the tutorial (and can be downloaded as a ZIP file).
Enjoy!
-- Hosting Tutorials Homepage: http://www.asp.net/learn/hosting/
-- ASP.NET Vidoes, Tutorials, and Other Learning Material - http://www.asp.net/learn/
Wednesday, June 17, 2009
#
The Scenario
You need to setup the Windows FTP service that is part of IIS 6.0 on a port number other than the standard port 21 and are using Windows Firewall on the server.
The Challenge
Getting an FTP server and the firewall to play nicely can be a bit of an adventure because FTP uses two ports for communicating - one for establishing the connection (typically port 21) and another one for transferring the data. I believe that the FTP service for IIS 6.0 uses port 20 as the data port when using port 21 as the connection port, but I am not 100% certain. What I am certain of is that the data port may be randomly selected from a wide range of ports, and that is certainly the case when you select an alternate port number for the FTP service. The challenge lies in configuring the firewall to accept incoming requests to both the alternate port and the randomly selected data port.
If neither port is opened in the firewall then when you attempt to connect to the FTP server the client will hang and eventually report that it cannot connect. If only the connection port is open then the FTP client will connect successfully but will repor the error: Failed to retrieve directory listing. The reason is because the connection can be established over the connection port, but the request made to the data port to get the directory listing was blocked by the firewall. Long story short, you need to make sure that the firewall will allow traffic for the randomly selected data port.
The Solution
- Create an FTP site on the port number of choice, such as 12345. Typically you'll want to use a high port number to minimize the likelihood of a conflict. See Creating Multiple FTP Site (IIS 6.0) for more information on how to create multiple FTP sites using multiple ports.
- If you are using Windows Vista or Windows 2008 as the server, run the following command from the command line: sc sidtype MSFTPSVC unrestricted
- Stop and restart the FTP service.
- Note: I got an error when restarting the service that complained that an unrestricted service could not be started in the same host as restricted services. I'm sure there is a more elegant workaround, but what worked for me was to reboot the server.
- Configure Windows Firewall to allow all TCP traffic in for the MSFTPSVC service. This will allow traffic on the randomly selected data port to penetrate the firewall. You can do this from the Windows Firewall configuration GUI or from the command line via: netsh advfirewall firewall add rule name="FTP" service=MSFTPSVC action=allow protocol=TCP dir=in
- Ensure that the FTP filter for Windows Firewall is disabled. You can do this via the command line, as well: netsh advfirewall set global Statefulftp disable
For more on Steps 2-5 see Windows Firewall Setup for Microsoft FTP Publishing Service for IIS 7.0. Some of the command line arguments are different in the article than what I have posted above because my commands are for the FTP Service that's part of IIS 6.0 whereas the article linked to looks at using the FTP Publishing Service for IIS 7.0.
I spent the better part of an afternoon figuring out these five steps. I hope this blog entry saves someone else a few precious hours.
Thursday, May 28, 2009
#
My Toolbox column in the June 2009 issue of MSDN Magazine is available online and includes the following reviews:
- ProjectLocker - ProjectLocker lets you outsource source control, defect tracking, and other common project management tasks to the cloud. Unlike open source hosting sites like CodePlex and Google Code, ProjectLocker is designed for closed source applications. Create a project, define which users have access, and, voila, you have a collaborative, online source control repository and defect tracking system. Monly prices range from free to hundreds of dollars per month, depending on the needed disk space, number of users, and installed features.
- Blogs of Note: The Morning Brew and Morning Dew - it's amazing how much technical content is available online, from blogs to community sites to newsgroups, we are swimming in a wealth of information. Finding the most interesting content can be a time consuming task. Fortunately, there are a number of blogs available whose sole purpose is to find and share the best technical content online. Two such blogs are The Morning Brew and Morning Dew, which are maintained by Chris Alcock and Alvin Ashcraft, respectively. Subscribe to these two blogs to find new blogs or just to get a taste of the latest technical content each day.
- Quince - Quince is a User Experience pattern browser, created by the folks at Infragistics. Each pattern includes a description of the problem being solved, provides a solution, the context of the problem, the rationale behind the solution, and steps for implementing the pattern. There are also several examples from real computer applications and websites. Next time you're working on designing the user experience, head over to Quince for guidance and advice.
This issue reviewed The C# Programming Language, by Anders Hejlsberg et al. An exerpt from my review follows:
At 754 pages, The C# Programming Language is a dense, technical, and very thorough examination of C# 3.0's syntax and semantics. The first three chapters provide an overview of the language's key features, including types and variables, classes and objects, arrays, interfaces, and events. There's also an overview of C# grammar. ... The writing style in The C# Programming Language is formal and dry. There are no figures or screen shots; the code samples given are terse. The book reads like a technical specification. However, there are several annotations throughout the book from the authors and other prominent C# software engineers both from within Microsoft and from the wider developer community. Some annotations offer a real-world example to complement the material discussed. Others include pearls of wisdom or point out common pitfalls that may surface when working with a particular feature. These annotations are written in a more conversational voice and help add context to the material. ... This book is best suited for intermediate to advanced developers who want to explore the nitty-gritty details of C# and gain a deeper understanding of the language's syntax and semantics.
Enjoy! - http://msdn.microsoft.com/en-us/magazine/dd882511.aspx
As always, if you have any suggestions for products, blogs, or books to review for the Toolbox column, please send them to toolsmm@microsoft.com.
Thursday, May 21, 2009
#
ELMAH is a free, open source error logging system for ASP.NET created by Atif Aziz. This blog post assumes the reader is already familiar with using and configuring ELMAH. If this is not the case, refer to Simone Busoli's article, ELMAH - Error Logging Modules and Handlers for more information.
One of ELMAH's most useful features is that it can automatically e-mail the details of a runtime error to a specified set of recipients. This feature allows developers to be notified immediately once a runtime error occurs. (ELMAH can also syndicate recent errors as an RSS feed and, with the release of ELMAH version 1.0, ELMAH can even tweet error details.) While I've used this feature many times in the past, I ran into some difficulties setting it up to send the error e-mails through GMail's SMTP servers. You can specify the SMTP settings directly in ELMAH's <errorMail> setting or you can define it in the <system.net> section, as described in Sending Email in ASP.NET. I typically use the <system.net> setting because I also use this information in my website and don't want to repeat it twice in Web.config. Consequently, my Web.config file looks similar to the following:
<elmah>
<errorMail
from="..."
to="..."
subject="..."
async="true"
/>
</elmah>
<system.net>
<mailSettings>
<smtp deliveryMethod="network">
<network host="..." port="..." userName="..." password="..." />
</stmp>
</mailSettings>
</system.net>
The first challenge is that GMail's SMTP servers require SSL. However, you cannot specify SSL behavior through the <system.net> settings; rather, you have to do it when you instantiate the SmtpClient object, via its EnableSsl property. To instruct ELMAH to send e-mail via SSL you need to set the <errorMail> section's useSsl attribute to true, like so:
<errorMail
...
useSsl="true" />
As of the time I am writing this blog post, this attribute is not shown in the sample Web.config file, so you wouldn't know it exists unless you examined ELMAH's source code.
The second issue is that GMail's SMTP server uses port 587 instead of the standard port 25. I had correctly set the port number in the <system.net> section and believed I could then omit it from the <errorMail> section. However, I was wrong. If you omit the port from <errorMail> then ELMAH uses port 25. It does not turn to the <system.net> section and use the port number specified there.
To remedy this you can do one of two things:
- In <errorMail>, set the smtpPort attribute to the port you want to use.
- In <errorMail>, set the smtpPort attribute to "0". Doing so will cause ELMAH to use the port defined per the <system.net> settings.
With these changes my Web.config ends up looking like the following:
<elmah>
<errorMail
from="..."
to="..."
subject="..."
async="true"
smtpPort="0"
useSsl="true"
/>
</elmah>
<system.net>
<mailSettings>
<smtp deliveryMethod="network">
<network host="smtp.gmail.com"
port="587"
userName="..."
password="..." />
</stmp>
</mailSettings>
</system.net>
Monday, April 27, 2009
#
The next four tutorials in my Hosting Tutorials on www.asp.net were published over the weekend. These tutorials walk readers through hosting an ASP.NET website with a web host provider and are aimed at beginning to intermediate ASP.NET developers interested in getting a small- to medium-sized ASP.NET application online. The first six hosting tutorials served as an introduction to the series and provided an overview of core concepts. These current four tutorials examine deploying a data-driven web application.
- Deploying a Database [VB | C#] - This tutorial starts by examining how to get a database's schema and contents from the development environment to the production environment.
- Configuring the Production Web Application to Use the Production Database [VB | C#] - It is not uncommon for configuration information to differ between the development and production environments. This tutorial explores ways to configure the production environment to include the appropriate connection string.
- Configuring a Website that Uses Application Services [VB | C#] - ASP.NET version 2.0 introduced a series of application services, which are part of the .NET Framework and serve as a suite of building block services that you can use to add rich functionality to your web application. This tutorial explores how to configure a website in the production environment to use application services (such as Membership, Roles, and Profile).
- Strategies for Database Development and Deployment [VB | C#] - When deploying a data-driven application for the first time you can blindly copy the database in the development environment to the production environment. But performing a blind copy in subsequent deployments will overwrite any data entered into the production database. Instead, deploying a database involves applying the changes made to the development database since the last deployment onto the production database. This tutorial examines these challenges and offers various strategies to assist with chronicling and applying the changes made to the database since the last deployment.
Enjoy!
-- Hosting Tutorials Homepage: http://www.asp.net/learn/hosting/
-- ASP.NET Vidoes, Tutorials, and Other Learning Material - http://www.asp.net/learn/
Friday, April 24, 2009
#
My Toolbox column in the May 2009 issue of MSDN Magazine is available online and includes the following reviews:
- SyncBack Pro - backups are an important part of any IT strategy. For large corporations with established IT departments, backups are automatically performed routinely, but if you work for a small company or work for yourself, backup responsibility falls on your shoulders. The good news is that creating, maintaining, and executing backup schedules is a breeze with SyncBack Pro. Backup to or from folders on your local computer, on a network share, over FTP, to CDs/DVDs, and even via e-mail! A freeware edition of SyncBack is available as well.
- VS Explorer - do you routinely find yourself toggling between Visual Studio and Windows Explorer? If so, check out VS Explorer, an affordable Visual Studio Add-In that integrates the Windows Explorer user experience as a window within the Visual Studio IDE. What's more, VS Explorer includes features not found in Windows Explorer, such as one-click access to the Solution or Project folder, as well as to the file currently displayed in the IDE.
- Tools for Multiple Monitors - want to increase your coding productivity? The easiest and most cost-effective way is to buy another monitor. I've blogged about my move from one to two monitors and from two to three. Unfortunately, there's not very rich support in Windows for multiple monitors. The good news is that there are a number of commercial and free tools for making the most of your multiple monitor setup. UltraMon ($40) is a must have - it extends the taskbar across all monitors, adds one click access to moving windows from one monitor to another, and so on. Another great tool is WinSplit Revolution, a free utility that adds keyboard shortcuts for repositioning and moving windows around the screen and across monitors. Once you install and start using WinSplit Revolution you'll wonder how you lived without it. And the most important configuration aspect of a multi-monitor environment is your desktop. Do you stretch one image across all three? Have unique images in each window? Have your pictures displayed in a montage? To make the most of your desktop space check out John's Background Switcher, a utility that periodically swaps out your desktop background. It works wonderfully on multiple monitors and can pull images from your hard drive or from image sharing sites like Flickr, Facebook, and Picassa.
- Blogs of Note: Signal vs. Noise - 37signals is a company that makes web-based applications with a simple design goal in mind - making simple software that makes it easy to do what you need and doesn't do anything else. Less is oftentimes more, after all. Signal vs. Noise is the company blog, where various employees post ruminations on marketing, usability, web design, and interesting anecdotes. It's a must read blog for web developers and designers alike.
There was no book reivew in this issue.
Enjoy! - http://msdn.microsoft.com/en-us/magazine/dd727507.aspx
As always, if you have any suggestions for products, blogs, or books to review for the Toolbox column, please send them to toolsmm@microsoft.com.
Friday, April 10, 2009
#
I have a new tutorial series on the www.asp.net website that looks at hosting an ASP.NET website with a web host provider. The tutorials are aimed at beginning to intermediate ASP.NET developers interested in learning the ins and outs on how to get a small- to medium-sized ASP.NET application online. As with my previous tutorials on the www.asp.net website (Data Access, Security, and Master Pages), these tutorials include both C# and Visual Basic versions. Each tutorial can be downloaded as a PDF for offline viewing or printing and each tutorial includes a working website that illustrates the concepts discussed in the tutorial (and can be downloaded as a ZIP file).
The first six hosting tutorials serve as an introduction to the series and provide an overview of core concepts.
- ASP.NET Hosting Options [VB | C#] - ASP.NET web applications are typically designed, created, and tested in a local development environment and need to be deployed to a production environment once it is ready for release. This tutorial provides a high-level overview of the deployment process and serves as an introduction to this tutorial series.
- Determining What Files Need to Be Deployed [VB | C#] - What files need to be deployed from the development environment to the production environment depends in part on whether the ASP.NET application was built using the Web Site Model or Web Application Model. Learn more about these two project models and how the project model affects deployment.
- Deploying Your Site Using an FTP Client [VB | C#] - The simplest way to deploy an ASP.NET application is to manually copy the necessary files from the development environment to the production environment. This tutorial shows how to use an FTP client to get the files from your desktop to the web host provider.
- Deploying Your Site Using Visual Studio [VB | C#] - Visual Studio includes tools for deploying a website. Learn more about these tools in this tutorial.
- Common Configuration Differences Between Development and Production [VB | C#] - In earlier tutorials we deployed our website by copying all of the pertinent files from the development environment to the production environment. However, it is not uncommon for there to be configuration differences between environments, which necessitates that each environment have a unique Web.config file. This tutorial examines typical configuration differences and looks at strategies for maintaining separate configuration information.
- Core Differences Between IIS and the ASP.NET Development Server [VB | C#] - When testing an ASP.NET application locally, chances are you are using the ASP.NET Development Web Server. However, the production website is most likely powered IIS. There are some differences between how these web servers handle requests, and these differences can have important consequences. This tutorial explores some of the more germane differences.
The next set of tutorials examines the challenges in deploying data-driven applications and maintaining development and production databases.
Enjoy!
-- Hosting Tutorials Homepage: http://www.asp.net/learn/hosting/
-- ASP.NET Vidoes, Tutorials, and Other Learning Material - http://www.asp.net/learn/
Saturday, March 21, 2009
#
My Toolbox column in the April 2009 issue of MSDN Magazine is available online. The March issue of MSDN Magazine has a focus on the Web and my reviews in Toolbox follow suit and include:
- The Microsoft Chart Controls - Did you know that Microsoft has released a free, robust set of charting controls for both WinForms and ASP.NET applications developed using the .NET Framework version 3.5? With this control suite you can add pie charts, line charts, bar graphs, and a host of other chart types to your .NET applications.
- Snippet Designer - Visual Studio 2005 introduced code snippets, which are task-oriented blocks of code that can include replaceable regions. In a nutshell, a code snippet can be used to inject common code blocks, such as the stock code for sending an e-mail message, or the skeleton of a try/catch block. Unfortunately, Visual Studio does not include much in the way of tool support for building these code snippets. Snippet Designer, an open-source project hosted on CodePlex.com, provides a straightforward user interface that integrates with the Visual Studio IDE and makes creating and editing snippets a much more intuitive and pleasant experience.
- Blogs of Note - Sara Ford: Sara Ford is a Microsoft employee who, over the years, published 382 tips on getting the most out of Visual Studio. Her blog serves as a great resource of Visual Studio tricks and tips. Spend an afternoon pouring through her old blog entries, and I guarantee you that you'll learn a few new things about Visual Studio.
The Bookshelf section reviewed two books: More Effective C#, by Bill Wagner, and Refactoring SQL Applications by Stephane Faroult and Pascal L'Hermite. An excerpt of Effective C# follows:
More Effective C# assumes the reader is already familiar with C# and language features like generics, LINQ, multithreading, and so on. You won't find any discussions on what generics are or the syntax for lambda expressions. Instead, the book states a specific guideline, such as "Distinguish between IEnumerable and IQueryable data sources," and then provides a deep and detailed discussion on the why of the guideline with illuminating prose and helpful code snippets. And each guideline stands on its own and can be read and digested without having first read other guidelines, meaning that you can jump around to what guidelines interest you the most or are the most relevant for your current projects. ... More Effective C# is a must-read for experienced C# developers who are already familiar with C# language features such as generics, extension methods, lambda expressions, anonymous types, and LINQ, but who want guidance on how best to use these features.
Enjoy! - http://msdn.microsoft.com/en-us/magazine/dd569763.aspx
As always, if you have any suggestions for products, blogs, or books to review for the Toolbox column, please send them to toolsmm@microsoft.com.
Saturday, March 14, 2009
#
Our esteemed House of Representatives passed a resolution earlier this week, designating today - March 14th - National Pi Day. This is an American-centric 'holiday,' as we colloquially denote our dates in MM/DD format, hence March 14th is 3.14, the first three digits of Pi. Most other countries start with the least significant date part and work their way to the most significant - DD/MM/YY - which would mean the International Pi Day should fall on the 3rd day of the 14th month (hrm) or the 31st day of the 4th month, i.e., April 31st (hrm, again). Of course, God-fearing computer scientists denote dates from the most significant to the least, always using four digits for the year - YYYY/MM/DD - which would place Computer Scientist Pi Day on May 9th, 3141 if you were being flexible on parsing the month and day and allowing either one or two characters.
As we all learned in elementary school, Pi is the ratio between the area of a circle and its radius, squared, or the ratio between the circle's circumference and its diameter, and approximates 3.14159. One of the shortcomings of mathematical education in our schools is that math is initially introduced in a way that suggests that its rules and results are handed down by some oracle. Furthermore, children are taught that learning math involves mindless memorization. I think this turns a lot of kids against math; they end up thinking that it's some stuffy, boring pursuit that is of little interest. But there are interesting ways to present math, and ways in which the child discovers first hand why certain things are the way they are. And explaining why Pi approximates 3.14159 is a great example of a more involved and interactive form of math education.
My daughter is 6 months old, but one day I plan on sharing the following math discovery with her. I don't know when this would be age appropriate. The first part - computing Pi as a ratio of the circumference and diameter - only requires understanding of division, and I imagine it could be introduced around age seven or eight. The second 'experiment' involves areas and necessitates understanding exponentiation and square roots, and would probably have to wait until age 10, or so.
Start by drawing some circles (with a compass) and talking about the components of the circle - the circumference, the area, the radius, the diameter. It's pretty clear that there's some relationship between these components. A bigger radius means a larger area and a longer circumference. Next, get out some string and measure some of the circles' circumferences. It becomes clear that a circle with twice the radius has twice the circumference. But given just the radius, can one arrive at the circumference? There is some missing number that we need to arrive at this, and this can be approximated empirically: using the string, measure out the circumference for a circle and then hold the string up to a ruler. Divide this measurement by the diameter and you should arrive at a value that approximates Pi. Using this newly discovered number, tackle the problem the other way around - starting from a known diameter, what should the circumference be? Compute it, then measure it with the string and see how the values align.
Can we devise some ratio between the radius and the area? When in doubt, get out the graph paper! Start by deciding on a radius and then determine what points on the graph paper are bounded by a circle with said radius. I'm not sure the best way to explain this to the pupil in a way that isn't along the lines of, "This is the way it is," but the square at coordinates (x,y) on the graph paper is bounded by the circle if the square root of x2 + y2 is less than or equal to the radius. Using that knowledge, visit each square on the graph paper and apply the formula. If the square root is indeed less than x2 + y2 then shade in the square, otherwise leave it empty. After enumerating the squares, count up the shaded ones and divide that total by the radius squared. And, lo!, the result is eerily similar to the number we were getting when dividing the circumference by the diameter. Repeat the graph paper process a couple times with larger radiuses. As the radius gets larger, the area is computed more accurately as the edges of the circle are less jagged. Consequently, the ratio of the area and the radius gets more and more refined and close to the true value of Pi.
And if my daughter enjoys computers and likes spending time giving them instructions (fingers crossed), the final part of the lesson would be to have the computer do the grunt work for us. Why spend all afternoon shading in graph paper squares when a computer can shade in millions of squares for us in seconds? Here's a snippet of C# that approximates Pi.
const int r = 10;
int A = 0;
for (int x = -r; x < r; x++)
for (int y = -r; y < r; y++)
if (Math.Sqrt(x * x + y * y) <= r)
A++;
Console.WriteLine("Enjoy a slice of {0}", Convert.ToDouble(A) / Convert.ToDouble(r * r));
You can adjust the value of r to see how the approximation becomes more refined. For example, when r = 10 the approximation is 3.15. With r = 100 it's 3.1415. Of course, too large of a radius results in an overflow, which is a great segue into a discussion on how computers represent numbers!
Friday, March 13, 2009
#
I oftentimes have a student or client remark, “I love how technology X does Y! However, I don't like X because it does Z.”
I don't know what else to say other than, “Ok,” or “I concur,” because after all, that's what computer science, and perhaps all of engineering, is all about - tradeoffs. There is no silver bullet. There is no panacea. Solutions are created to solve a specific problem, but the solution has shortcomings or deficits in other areas. That's life as a software developer.
If there were a silver bullet, if some technology existed that solved all the problems with no shortcomings elsewhere, we'd all be out of a job.
Sunday, March 08, 2009
#
Today marked the start of Daylight Saving Time (DST), the day of the year with the most missed airline flights.1 There's an esoteric ASP.NET issue that centers around Daylight Savings, and affects websites both at the very start of Daylight Savings and at the very end. ASP.NET's forms authentication feature assigns a forms authentication ticket to a user once they sign in, with the ticket serving as an identity token. This ticket is, by default, stored as a cookie on the user's browser and is sent back to the web server on each subsequent request to the site until it expires. The ticket's expiry is specified both in the Set-Cookie header and within the ticket itself. The expiry specified within the contents of the ticket is an absolute time that the ticket expires in terms of the web server's time zone. Can you see the problem? When DST starts or ends the expiry in the ticket remains constant, but the web server's clock is shifted. For a person signing on right near the start or end of DST, the the ticket is either rendered expired an hour earlier than expected or an hour later than expected.
I describe this issue in Forms Authentication Configuration and Advanced Topics, one of the tutorials in my Website Security Tutorials series:
The expiry stored in the authentication ticket is an absolute date and time value, like “August 2, 2008 11:34 AM.” Moreover, the date and time are relative to the web server’s local time. This design decision can have some interesting side effects around Daylight Saving Time (DST), which is when clocks in the United States are moved ahead one hour (assuming the web server is hosted in a locale where Daylight Saving Time is observed). Consider what would happen for an ASP.NET website with a 30 minute expiry near the time that DST begins (which is at 2:00 AM). Imagine a visitor signs on to the site on March 11, 2008 at 1:55 AM. This would generate a forms authentication ticket that expires at March 11, 2008 at 2:25 AM (30 minutes in the future). However, once 2:00 AM rolls around, the clock jumps to 3:00 AM because of DST. When the user loads a new page six minutes after signing in (at 3:01 AM), the FormsAuthenticationModule notes that the ticket has expired and redirects the user to the login page. For a more thorough discussion on this and other authentication ticket timeout oddities, as well as workarounds, pick up a copy of Stefan Schackow’s Professional ASP.NET 2.0 Security, Membership, and Role Management (ISBN: 978-0-7645-9698-8).
Happy Programming!
[1] This is a total guess, but based on some emperical evidence from a sample size of one. Back in 2001 I would have missed a flight on the day Daylight Savings Time started had my girlfriend at the time (now my wife) had not called me that morning to ensure that I was aware of the time change.
Wednesday, March 04, 2009
#
All successful software projects resemble one another; each failed project fails in its own way.
Sunday, March 01, 2009
#
Debugging code is a lot like the scientific method. Most importantly, both involve careful measurements and analysis of the resulting data. Be wary of the developer who is quick to announce the cause of an error. When an error occurs, a developer's first thought should be, "What data to I need to collect to better understand and analyze this error?" A less experienced developer is one whose first thought is, "Maybe the cause of the problem is (the database query|session timeout issues|invalid user input|etc.)?" This latter approach leads the developer down a series of dark alleys, many of which are dead ends.
Another important component of debugging and science are control groups and experimental groups. For the results of a scientific experiment to be sound, the researcher must have a control group that is not experimented upon, and an experimental group that differs from the control group by only one variable, namely by the "thing" that is being tested. In debugging, constructing the control group involves reproducing the error. If the QA department reports that an error occurs when entering a value longer than 50 characters into the Billing Address textbox on CheckOut.aspx, the first step in debugging is to visit CheckOut.aspx and enter an input longer than 50 characters into the Billing Address textbox to ensure that the reported error occurs. Likewise, the same steps should be repeated after the bug is fixed to help ensure that the fix has indeed solved the problem at hand.
Additionally, when debugging the practitioner must be careful not to taint the observations with his own preconceived notions or bias. The history of science is littered with examples of scientists who knowingly or unwittingly let their personal beliefs or the current societal mores color the data and influence their analysis. Johannes Kepler, the famous German mathematician and astrologer who penned the three laws of planetary motion, is a great example. Kepler started his astronomical career by using astronomical measurements to describe the motion of planets in our solar system. Although Kepler subscribed to Corpernicus's heliocentric model - that the sun was the center of the solar system rather than the Earth - he held to a rather convoluted theory that the planets orbited the sun based on different 3-dimensional polyhedra according to the Platonic solids. Kepler's problem was, in part, that he was approaching the problem backwards. Rather than taking the data at his disposal and asking, "What arrangement of the sun and planets would most sensibly explain these astronomical observations," he asked, "Can I construct a model that fits with the observations yet still maintains a semblance to the work done by the ancient Greeks and upholds my personal theological beliefs?" Fortunately, Kepler eventually abandoned his initial forays and came upon the a much simpler and, more importantly, a correct theory that proposed elliptical orbital paths with the sun as a focus.
A developer can fall victim to biasing observational data just as easily as Kepler did. A developer might be accustomed to bugs originating from a particular module, or from the code of a particular coworker. While such information is useful when deciding what data to collect, it is important to not let these preconceived notions influence the analysis of the data. While it may be mathematically probable that a particular error originated from a certain buggy module, don't ignore data that would suggest otherwise.
A corollary to Kepler's story is Occam's razor: that the simplest hypothesis is usually the correct one. If you find that you need to concoct an elaborate and complex scenario to explain the cause of the error, chances are you're barking up the wrong tree. More briefly, don't think too hard.
All this being said, debugging and science involves more than the mechanical process of gathering data and methodically interpreting it. There is an art form to the practice, and a certain wiliness and level of insightfulness that comes with much practice. But don't forget that the overwhelming bulk of any successful debugging session or any successful scientific experiment is keen measurement and straightforward, analytical interpretation of the data.
Thursday, February 26, 2009
#
My Toolbox column in the March 2009 issue of MSDN Magazine is available online. The March issue of MSDN Magazine has a focus on the Web and my reviews in Toolbox follow suit and include:
- The Ajax Data Controls Project - The Ajax Data Controls (ADC) project is an ASP.NET AJAX extension that marries the ease of the server-centric development model with the performance of the client-centric development model. ADC is a collection of controls that displays data in an Ajax-enabled web page. You can add the ADC to your page like you would any other web control, and set their properties through the Properties window. However, you work with the ADC controls programmatically via JavaScript. The net result is that the ADC result in significantly less markup between partial page postbacks than the built-in Web controls in an UpdatePanel, but provide a similar page developer experience.
- Fiddler - an HTTP traffic analyzer is a must-have tool for web developers. Such tools provide a clear picture of the low-level HTTP traffic coursing between the client and server. Moreover, such tools can be quite helpful in debugging or generating a pre-canned HTTP request (for testing server-side functionality) or response (when testing client-side functionality). My favorite HTTP traffic analyzer is Fiddler, a free tool created by Eric Lawrence. Check it out.
- Blogs of Note:
- Rick Strahl - Rick is an old-school FoxPro developer and ASP.NET developer who regularly shares his experiences, insights, tips, and tricks on his blog. Rick's blog posts primarily focus on Web topics, including ASP.NET, jQuery, AJAX, and Silverlight.
- Sam Larbi - Sam pens one of my favorite blogs, My Secret Life as a Spaghetti Coder. Sam works as a jack of all trades developer, dabbling in both Web and desktop applications and languages ranging from C++ to ColdFusion to C# and ASP.NET. Along with posts about specific technologies, Sam also routinely writes about the non-technology-related aspects of being a developer, including topics like meetings, working with others, personal development, and so on.
The Bookshelf section reviewed jQuery in Action by Bear Bibeault and Yehuda Katz. An excerpt follows:
Due to JavaScript's increasing importance in Web development, several frameworks have been created. One of the most popular ones is jQuery, a free, open-source, cross-browser JavaScript framework created by John Resig. (In fact, Visual Studio 2010 will ship with the jQuery library, making it even easier for ASP.NET developers to get started with jQuery.) ... jQuery in Action (Manning, 2008) ... is a great resource for leaning the ins and outs of jQuery and for mastering its terse and flexible syntax. jQuery in Action assumes the reader is already familiar with JavaScript and wastes no time covering the basics of the language. Instead, it starts with a quick introduction to the motivation behind jQuery and jQuery fundamentals and then moves on to using jQuery to accomplish common tasks. (Some of the more advanced JavaScript concepts that are used by jQuery are covered in an appendix.)
Enjoy! - http://msdn.microsoft.com/en-us/magazine/dd483223.aspx
As always, if you have any suggestions for products, blogs, or books to review for the Toolbox column, please send them to toolsmm@microsoft.com.