August 2010 - Posts

Enhancing the Store Locator ASP.NET MVC Application to Include Directions
27 August 10 10:44 PM | Scott Mitchell | 2 comment(s)

The info popup includes a Directions link.Earlier this year I wrote an article on 4GuysFromRolla.com showing how to build an ASP.NET WebForms store locator application using Google Maps. Recently, I ported the store locator application to ASP.NET MVC and detailed building the application in Implementing the Store Locator Application Using ASP.NET MVC.

Recently, a reader wrote in and asked what steps would be necessary to include a “Directions” link with each marker in the map so that, when clicked, the user would see the driving directions from the address they entered and the store of interest. I decided to update the ASP.NET MVC application to include this new feature request. Now, the results page shows a “Directions” link in both the grid of nearby stores and in the info window that pops up when you click a map marker. Clicking the “Directions” link opens a new browser window and loads Google Maps, showing the directions from the user-entered address to the selected store’s address.

To show the driving directions I send the user to the following URL: http://maps.google.com/maps?f=d&source=s_d&saddr=startingAddress&daddr=destinationAddress.

When the user is sent to the store locator page, the user-entered address (a/k/a, the starting address) is passed through the querystring via a field named Address, so we already know the starting address. But how do we get our hands on the destination address? Recall that view is passed a model that is a collection of NearbyStoreLocation objects; the NearbyStoreLocation class has properties like Address (the street address), City, Region, PostalCode, and so forth. We can build up the address by concatenating these various address parts.

Rather than requiring the view to build up the address, I added a new read-only property to the NearbyStoreLocation class named FormattedAddress, which returns an address Google Maps can parse by piecing together the address-related properties into a string.

public string FormattedAddress
{
    get
    {
        var addrPieces = new List<string>(5);
        if (!string.IsNullOrEmpty(this.Address))
            addrPieces.Add(this.Address);
        if (!string.IsNullOrEmpty(this.City))
            addrPieces.Add(this.City);
        if (!string.IsNullOrEmpty(this.Region))
            addrPieces.Add(this.Region);
        if (!string.IsNullOrEmpty(this.CountryCode))
            addrPieces.Add(this.CountryCode);
        if (!string.IsNullOrEmpty(this.PostalCode))
            addrPieces.Add(this.PostalCode);

        return string.Join(", ", addrPieces.ToArray());
    }
}

In the view, the link to the directions can be build like so:

<a target="_blank" href="http://maps.google.com/maps?f=d&source=s_d&saddr=<%=Server.UrlEncode(Request.QueryString["Address"]) %>&daddr=<%=Server.UrlEncode(store.FormattedAddress) %>">Directions</a>

And that’s it! Adding the Directions link to the info popup window is a tad more involved because the quotation marks must be escaped using \”.

To get your hands on the complete, working code, go to: http://www.4guysfromrolla.com/code/GoogleMapsMVC.zip

Happy Programming!

I’m Teaching Two Upcoming Training Classes in San Diego
19 August 10 09:45 PM | Scott Mitchell

Once a year (or so) I teach a handful of one-day, four hour classes in San Diego on various ASP.NET topics. I’ve got two such classes lined up for Saturday, September 11:

  • Get Started with ASP.NET MVC8 AM to Noon
    Traditionally, ASP.NET websites have been designed using the Web Forms model; ASP.NET MVC is an alternative model that uses the Model-View-Controller pattern. In a nutshell, ASP.NET MVC gives developers much finer control over the markup rendered by their web pages, a greater and clearer separation of concerns, better testability, and cleaner, more SEO-friendly URLs. This four hour class introduces ASP.NET MVC, explores how to build ASP.NET MVC applications, covers key differences between Web Forms and ASP.NET MVC, and highlights the benefits of ASP.NET MVC. During the class, we will build a real-world ASP.NET MVC application from start to finish.
  • Build Responsive Web Applications with Ajax, jQuery, and ASP.NET1 to 5 PM
    Ajax-enabled web applications use JavaScript and streamlined client/server communications to offer a highly interactive and responsive user experience. jQuery is a free, popular and powerful JavaScript library that ships with Visual Studio 2010 and greatly simplifies building Ajax-enabled web applications. This four hour class examines key Ajax concepts and techniques and walks through building a real-world Ajax-enabled web application using jQuery and ASP.NET.

Each class is $249 per student, but there is an ongoing early bird special price of $199 (available until August 28th). Students receive electronic access and printed copies of the training materials. Coffee, snacks and lunch are provided. The classes are held at the Sorrento Mesa Center (directions), which is located in Sorrento Valley and has free parking.

If you are interested in signing up or would like detailed course outlines, visit www.fuzzylogicinc.net/InDepth. If you have any questions about the class, material, or logistics, shoot me an email at mitchell@4guysfromrolla.com.

Hope to see you there!

Signup: www.fuzzylogicinc.net/InDepth

Hot Off the Presses – Teach Yourself ASP.NET 4 in 24 Hours
18 August 10 08:27 PM | Scott Mitchell

Teach Yourself ASP.NET 4 in 24 Hours Yesterday I received the author copies of my latest book, Teach Yourself ASP.NET 4 in 24 Hours. When signing the author agreement many, many months ago, there is typically a clause that promises the author X copies of the finished book. Getting these author copies is the final chapter in the book writing process – there is literally no more work to be done. No more writing, no more editing, no more author reviews. It signifies the true completion of the work and results in a physical product you can put your hands on and say, “Here it is. Thank goodness that’s over. Someone please slap me if I ever decide to do this again.”

As with my previous installments of Teach Yourself ASP.NET in 24 Hours, this book is intended for beginner to intermediate developers who are interested in learning ASP.NET 4. The book presumes no prior experience with ASP.NET, databases, or even HTML, although familiarity in those technologies in a plus. Over the course of 24 “hours” (or chapters, as I’m wont to call them), the reader is:

  • Introduced to ASP.NET and the client/server model inherent in every web application,
  • Given a crash course in using Visual Web Developer to create, design, and test ASP.NET websites,
  • Presented an overview of the Visual Basic programming language (for those new to programming),
  • Introduced to ASP.NET’s WebForms model and the most common and germane Web controls,
  • Taught the basics of working with relational databases, including a crash course in SQL,
  • Given an overview of working with databases from ASP.NET pages, including how to display data and how to insert, update, and delete data,
  • Shown how to use ASP.NET features like Membership, the site map, and master pages,
  • Introduced to the ASP.NET Ajax Library and how to create Ajax-enabled web applications using the server-centric model, and
  • Walked through deploying a website to a web hosting company.

If you are a seasoned ASP.NET developer, please refrain from buying this book for yourself – it is not written for you. This book is written for the beginner to intermediate developer who is new to or getting started with ASP.NET. So, if you’re getting started with ASP.NET, consider yourself a beginner-level ASP.NET developer, or if you have a colleague who’s learning ASP.NET, I hope you’ll pick up a copy of Teach Yourself ASP.NET 4 in 24 Hours.

Happy Programming!

Using the GeneratedImage Control in ASP.NET MVC
14 August 10 03:44 AM | Scott Mitchell | 6 comment(s)

One of the free, open-source controls on the ASP.NET team’s CodePlex page is the GeneratedImage control. In a nutshell, the GeneratedImage control is a combination of an ASP.NET Web Control and a set of classes that facilitate programmatically creating, serving, caching, and transforming images. If you store images in the database that need to be served from a web page, if you need to create images on the fly, or if you need to resize, add watermarks, or perform some other image transform, then the GeneratedImage control can help. For more information on the GeneratedImage control and its capabilities, see my articles Dynamically Generating and Caching Images in ASP.NET with the GeneratedImage Control and Image Transforms with the ASP.NET Generated Image Control.

GoogleMaps10Previously, my experience with the GeneratedImage control was in WebForms applications. However, I recently ported my Store Locator ASP.NET application from WinForms to ASP.NET MVC 2 (a two-part article series on porting this application from WinForms to ASP.NET MVC is forthcoming). As the screen shot to the right shows, the store locator results page uses the GeneratedImage control to dynamically create markers for the store locator map, namely a navy circle displaying a white number - 1, 2, 3, and so - to illustrate where on the map a particular store resides.

This image is dynamically generated from an HTTP Handler named NumberToImageHandler.ashx. Specifically, the text to display is passed through the querystring and this HTTP Handler generated and returns the image content. For example, pointing your browser to NumberToImageHandler.ashx?number=1 would create and return the binary content for the 1 image, whereas NumberToImageHandler.ashx?number=2 would create and return the binary content for the 2 image, and so on. This HTTP Handler is a class that extends the Microsoft.Web.ImageHandler class, which is part of the GeneratedImage control library.

For my ASP.NET MVC store locator application I wanted to utilize this existing code, but use a more natural route for accessing the content. Having a .ashx extension just seems so passé. What I wanted instead was to reference these images using routes like:

  • Images/1
  • Images/2
  • ...

Here’s what I ended up doing:

  1. Added a new route in the RegisterRoutes method in Global.asax for the URL pattern Images/{number}.
    routes.Add(
        "ImageRoute",
        new Route(
            "Images/{number}",
            new RouteValueDictionary(),
            new RouteValueDictionary {{ "number", "\\d+" }},
            new NumberRouteHandler()
        )
    );
    Note the constraint that only matches this route if the number parameter is one or more digits. Also note the RouteHandler class that is responsible for handling this route, NumberRouteHandler.
  2. Created the NumberRouteHandler class. This class’s sole responsibility is to return an instance of the HTTP Handler that will handle this request. The code for this class is simple, it just returns an instance of the NumberToImageHandler class:
    public class NumberRouteHandler : IRouteHandler
    {
        public IHttpHandler GetHttpHandler(RequestContext requestContext)
        {
            return new NumberToImageHandler();
        }
    }
  3. Created the NumberToImageHandler class. This class contains virtually the same code as the NumberToImageHandler.ashx file in the WebForms application. The only difference was instead of reading the number to display from the querystring I read it from the Request object’s RouteData collection. Here’s the line of code that determines which number to display in the image:
    string numberText = HttpContext.Current.Request.RequestContext.RouteData.Values["number"] as string;

With this code in place, anytime a request comes in for Images/1, say, the ASP.NET Routing system dispatches the request to the NumberRouteHandler class, which returns an instance of the NumberToImageHandler class, which reads in the number (1, in this case), dynamically creates the image, and returns it back to the requestor. Pretty slick, eh?

For more information on ASP.NET Routing see URL Routing in ASP.NET 4 and ASP.NET Routing (the technical docs). You can download the ASP.NET MVC version of the store locator from http://www.4guysfromrolla.com/code/GoogleMapsMVC.zip. As noted earlier, there is a two-part article series in the works that walks through porting the store locator from WebForms to ASP.NET MVC and will be published on 4GuysFromRolla.com later this month.

I Am Now Tweeting (Or is it Twittering?)
10 August 10 07:12 AM | Scott Mitchell | 3 comment(s)

Last week I received an email from Srikanth Pragada, a .NET trainer in southern India, asking why I did not have a Twitter account. I had two excuses. First, I am somewhat of a Luddite when it comes to social technologies like cell phones and web apps like LinkedIn, Facebook, etc. Also, I have the knack of verbosity, in that I can - and often do! - take 100 words to describe a point that could have been made in 50. Consequently, Twitter's 140 character limit sort of grates against my natural tendency to write as if I was being paid by the word.

But excuses be damned, for I have started tweeting! (Or is it, "I have started Twittering?" I need a teenager so that I can have the answers to questions like these.) You can follow me @ScottOnWriting. Like with this blog, my intent it to use this Twitter account exclusively for discussing and sharing information about ASP.NET and related technologies/topics. No tweets about what I had for breakfast or that my flight is delayed, promise!

Filed under:
Two Upcoming ASP.NET Local User Group Talks in August
05 August 10 01:00 AM | Scott Mitchell

This month I will be giving two talks to .NET user groups here in San Diego.

  • Take Control of Your Website's URLs with ASP.NET Routing - Tuesday, August 17th at 6:00 PM at the ASP.NET Special Interest Group at the Microsoft Office in UTC
    Did you know that ASP.NET has a powerful URL routing framework built into it? This talk explores the ASP.NET Routing system and how to use it to create SEO-friendly, human-readable URLs in both MVC and Web Form applications.

  • ASP.NET Tips, Tricks, Traps, and Tools - Tuesday, August 24th at 6:00 PM at the San Diego .NET User Group at the Intuit Campus
    Explore a variety of ASP.NET tips, tricks, traps, and tools with author, consultant, and trainer Scott Mitchell.

Hope to see you there!
Filed under:
More Posts

Archives

My Books

  • Teach Yourself ASP.NET 4 in 24 Hours
  • Teach Yourself ASP.NET 3.5 in 24 Hours
  • Teach Yourself ASP.NET 2.0 in 24 Hours
  • ASP.NET Data Web Controls Kick Start
  • ASP.NET: Tips, Tutorials, and Code
  • Designing Active Server Pages
  • Teach Yourself Active Server Pages 3.0 in 21 Days

I am a Microsoft MVP for ASP.NET.

I am an ASPInsider.