Website & App Accessibility for the Visually Impaired

Share this post...

The internet is an important and mandatory part of modern life, including the 285 people million worldwide who have some form of visual impairment (1.4 billion web users worldwide have accessible needs). However, those with visual impairments are often unable to use much of the internet as many sites demand that lack features necessary for low or no vision users. The lack of sight isn’t the only issue as approximately 8% of the male population experiences one of the three forms of color blindness. Visually impaired users comprise of a large segment of the population, usually around 10%. It’s important to provide an accessible site so that you can reach all your customers without inadvertently adding challenges for some. Additionally, there are laws that US government websites as well as websites at some companies or sectors must adhere to defined by Before jumping into the technical aspects of accessibility, let’s look at how visually impaired users “see” your web pages.

How the Visually Impaired Use the Internet

The internet is largely visual, and that can exclude people who have visual impairments from accessing its contents. Low vision users often require the use of assistive technology, usually in the form of a screen reader. While most people need to increase the browser’s font size frequently, those with severe impairments must use a screen reader such as JAWS, NVDA, Window Eyes, or one of the many others. If you’ve never used a screen reader, you can watch this video about how a blind student uses the internet that should give you a sense of what it’s like. Screen readers are quite robust in their capabilities, but they do have limitations, and cannot completely substitute for the visual experience, especially in a graphic laden site. That’s because screen readers cannot read videos or image data, only textual data and DOM elements. Additionally, low vision and blind users rely heavily on using the keyboard, since a mouse demands high fidelity eyes as well as hands to work. That means non-mousers use Tab/Shift keyboard combination in a Windows system to move between heading level tags, named anchors, and form elements, sometimes while waiting for the reader to catch up. This is the opposite of a sighted person who’s eyes can quickly scan away from redundant menus or ads to get to the good content.

Others may have a contrast sensitivity rather than, or in combination with, low or no vision. When one has a visual issue that affects contrast, the eye has reduced ability to distinguish between similar shades and levels of brightness. That makes the experience of color different from that of what we classify as normal vision. In fact, the popular social networking site Facebook uses color code #3b5998 (dark blue), because its founder Mark Zuckerberg is colorblind. Eye diseases such as Retinitis Pigmentosa, Retinopathy, Cataracts, and Glaucoma all lead to sharp decreases in contrast and/or color sensitivity. The colors actually look different to folks with contrast sensitivities. What you see as red might look brownish or even gray to someone else. This article at MSDN reveals how users with varying colorblindness and contrast sensitivities see web pages.

Accessible Content and Design

When building accessible web pages, we can do many things that will enable their usage for people with assistive technology. The first and easiest step to take in creating visually accessible web pages is to increase the default font size! Most of the citizens of the world do not have 20/20 vision, so increasing the font size is a tremendous gain with only a single line of code to change in the site’s default CSS file. When crafting hyperlinks be sure to set the link text (i.e., the text between the anchor tags) to something descriptive that matches the link target. Avoid generic text such as the words “Click here”, and be sure to include a complete description of what the user can expect on the other side of the link. Applying the name attribute to anchor tags means users can use the keyboard to skip through to that hyperlink.

Two colors that have low contrast might be fine to someone with normal vision, but it is likely harder to distinguish between the colors, letters, and symbols for someone who is colorblind. Quite possibly the most important design concept for accessibility is to keep the site clean of clutter, and navigable with alternative methods of input than a mouse. You can ensure your color schemes and contrast work well by visiting these sites: and

Screen readers must read everything on the page they can access (usually DOM and text), and that includes headers and footers that show on every page in the website. It can take several minutes to plow through a menu that a sighted user can scan in just one second. To remedy this, we use Skip Links. Skip links are HTML anchros that allow the speech software or braille user to bypass redundant information, such as navigational menus. Speech and braille users generally read the page from top to bottom,  and consequently are subjected to repeated information before reaching the heart of the page. All you need are two lines of code. Just put an anchor before the repeated HTML (usually a menu), or right at the beginning of the page, like this:

<a href=”#content”><img src=”empty.gif” height=”15″ border=”0″ alt=”Skip Main Navigation” width=”5″></a>

Then place a named anchor at the beginning of the unique content, where the reader’s eyes would normally skip to:

<a name=”content”></a>

Then you have a skip link. This tag can exist anywhere in the page that you think the screen reader should land, so it can continue reading from there. Adding something as simple as skip links in your source enables the machine reader to save a significant amount of time on behalf of the user. Check out the skip links at WebAIM. They work perfectly.

Accessible HTML Layout and Elements

You can craft accessible HTML with little to no extra effort than you normally use in your daily development tasks. Simple things like using header tags, <h1> through <h6>, make the page navigable via keyboard, as low vision users may have difficulty seeing where to mouse. Avoid using <div>, <span>, or <p> tags with larger fonts, as they don’t allow for keyboard navigation or work well with assistive technologies. Besides, <h1>-<h6> are meant for headings. When displaying media, each <img> element must have clear and succinct alt attribute value, as this is the only way assistive technology such as screen readers and braille machines can convey what is inside the image. This is an easy coding task. When laying out sections of pages with HTML <tables>, be sure to include the <th> elements for navigation and assistive technology, rather than using <td> tags for column headings.

The Web Accessibility Initiative established WAI-ARIA, the Accessible Rich Internet Applications Suite, as a way to make Web content and sites more accessible to people with disabilities of any sort that makes computing unnecessarily difficult. WAI-ARIA published a set of standard attributes so that HTML can integrate with assistive technologies.

Many popular websites, especially news sites, will be disheartened to hear that JavaScript cascading menus and JavaScript popup ads (jQuery lightboxes) make it an order of magnitude harder for low vision and blind users. Often, ads fly in from the top, bottom, and sides of a page, and march across the screen making it impossible for assistive technology to translate what’s going on to the user. Screen readers and braille machines can’t do their jobs properly under these conditions. When this happens, low vision users must leave the site as it becomes simply unusable. Considering the numbers of visually people internet is 10% of your user base, you’re turning away a big chunk of your user base just by using popups. There are better ways to advertise.

Accessible HTML Forms

Submit and reset buttons as well as the <button> element automatically work with assistive technology. You must make some minor modifications to other form elements though. Using the <label> element is a very effective way to enable screen readers and braille machines to present the text and meaning of any HTML input tag. When building HTML forms in general, be consistent with the placement of labels and input fields, and be sure to explicitly state required fields and validation. While it is a common practice to indicate which items are required fields with a non descript red asterisk or icon, it is not very accessible. Adding the word “Required” or a precise description of the validation message to the label makes validation rules clear to readers and devices. Label all input elements of the form. Below is a sample of the proper way to label for accessibility:

<label for=”fullName”>Full Name </label><input id=”fullName” type=”text” />

Notice that the <label>’s for attribute matches the <input>’s id attribute. Without this connection, visual assistants cannot determine which labels belong to which element. When working with dropdowns, label the entire dropdown as well as each individual item in the dropdown by placing text between the <option> elements.. 

<label for=”favoriteLanguage”>Choose your favorite programming language:</label>
<select id=”favoriteLanguage” name=”select”>
    <option value=”1″>C#</option>
    <option value=”2″>VB</option>
    <option value=”3″>JavaScript</option>
    <option value=”4″>Ruby</option>
    <option value=”5″>Lisp</option>

Checkboxes only need that you use the <label> element, and they’ll work with readers. The American Association of the Blind recommends avoiding Radio buttons, stating that many of the assistive programs out there do not support them well. Since radio buttons often represent simple binary data or yes/no answers, a checkbox should work fine as an alternative. You can move to a drop-down for three or more items.

<label for=”yesNoAnswer”>Is C# your favorite language?</label><input id=”yesNoAnswer” type=”checkbox” />

In addition to open standard HTML, the WAI-ARIA standards provide ARIA tags that you can use to enhance assistive technologies, especially in HTML forms. You can apply the aria-label attribute to elements that have no text, such as an image or a submit button. Form elements that you require the user to fill in should have the aria-required attribute set to “true”. Our previous example that creates a text box to contain a full name can be expanded like this:

<label for=”fullName”>Full Name </label><input aria-label=”Full Name” aria-required=”true” id=”fullName” type=”text” />

It’s not just HTML elements that affect accessibility. While it’s a common practice to set the cursor’s focus to a starting field with JavaScript in HTML forms, doing so interferes with screen readers. The same goes for AJAX scripts that run upon form submissions. Having client side scripts are Ok as long as you don’t forget to test the pages to make sure they work with the keyboard as well as assistive technology, and do not intrude on the user’s workflow. You can read more in depth about techniques for HTML form accessibility at WebAIM online.


The American Association of the Blind has many resources for creating visually accessible web sites. Hide your mouse away while testing web pages to force yourself to be a keyboard user, and test for harmony with assistive technology. You can do so by trying out a few of these 10 free screen readers, or the Web Anywhere browser based screen reader that requires no software installation. Before you publish your web site check out the Web Accessibility Evaluation Tool (WAVE). This tool lets you plug in a URL and it will show that same page with annotations specifying its level of accessibility compliance. Finally, Microsoft has released an Accessibility Center where you can learn about various development techniques and tools to help you reach all of your customers.

Share this post...

Use SignalR to Build Real-Time Connectivity into Your Software

Share this post...

You want to write software that works just like popular social networking sites do, with lively, immediate information. That means building real-time high-frequency updates into your software, because users want their data and they want it now. In some situations, moving data in real-time is essential to the success of the app as it gives an upper hand to the business that does so. Not just that, but let’s face it – it’s cool to be the developer who writes the high tech websites. If you want to build these modern websites and apps with live, two-way communication, then SignalR is something you should seriously consider.

What is SignalR and why should you use it?

SignalR is a set of libraries that facilitate easy development of these kind of real-time websites and apps. It is open source, and you can get it here: GitHub. It works across all the major platforms. SignalR the newest member of the ASP.NET family, that enables developers to write incredibly simple real-time, two-way websites and apps. Two-way communication means that both the server and client share an open channel in which they can initiate contact with each other.  This channel is high-speed and works both directions between server and client. Many kinds of software can benefit from the real-time, two-way, communication system of SignalR. They include high traffic finance and stock apps, auctions, voting, quizzes and polls, lotteries, games, and many more. If your app’s not in the list, you still might want to investigate Signal, as UXs with high-frequency updates tend to be the ones that the users prefer (and rate higher for those in app stores).

SignalR is built to the OWIN specification. OWIN, short for Open Web Interface for .NET, is a set of standards for constructing a pluggable, modular, Web server architectures. Fortunately as SignalR developers, we don’t really need to dig into the specs to write SignalR code, most of the time.

Conceptually, SignalR works like a hub and spoke, or hubs and clients, as we call them. This means that the client can call the server, like we normally see in a HTTP Request-Response model, but now the server can contact the client, and one client can contact other clients (through the server). This is not the kind of programming that web developers usually do. SignalR contains two primary components: Hubs and Clients. Hubs, as you might expect, are server side and they behave a lot like super fast switchboard operators (oxymoron?). Clients, on the other hand, behave the same, except that now they can also receive calls from the server. This is where SignalR differs from customary Web programming, in that both sides can initiate communications between each other once the client initially opens the pipeline.

SignalR uses Websockets technology everywhere that it possibly can, and when it’s not possible, it uses an algorithm to determine the best possible transport. It supports the following transports: WebSockets, Long Polling, Server Side Events, and Forever Frame. As developers, we barely need to know cursory information about these frameworks to benefit from SignalR.

Get Started With SignalR Development

Since SignalR is an ASP.NET product, we’ll need to create an ASP.NET project in Visual Studio (unless you self-host, but we’ll stick with ASP.NET here). You can go with either Web Forms or MVC, as SignalR is also ASP.NET, and it all works together. Then install the “Microsoft ASP.NET SignalR” package into the ASP.NET project, using either the GUI or the Package Manager console. When you install the generic “Microsoft ASP.NET SignalR” package, it installs a few dependencies. Those are both server and client side components that work in tandem so that SignalR can do its thing. You can verify the installation by checking for references to Owin under the project references and jquery.signalr-2.0.3.js and similar files under the Scripts node in Solution Explorer.

Every site needs a starting point, and for SignalR apps, we need to hook into the OWIN pipeline of modular architecture. That means that we need to run a quick bit of code during startup. To do so, put the following code in a class in App_Start. This tells ASP.NET that the SignalR OWIN modules will be part of the regular IIS pipeline. Below is sample startup code for a voting app. The app loads several images and allows users to vote on one or more items.

[assembly: OwinStartup(typeof(VoteR.App_Start.Startup))]

namespace VoteR.App_Start
    public class Startup
        public void Configuration(IAppBuilder app)

Once we insert the startup code, we can move to our centerpiece of activity, the hub.


Hubs enable developers to write code to accept calls from clients and call methods on clients. When many people are voting, the action happen incredibly fast, so it’s a perfect candidate for real-time connectivity. Not to mention that users want to see the vote total updating in real time. Let’s see this in action by examining the VoteHub class. The VoteHub class inherits from the Microsoft.AspNet.SignalR namespace. In this class is the Vote public method that that the clients can call, and when they do, it is syntactically similar to an ASMX Web Service call, meaning that it uses standard dot notation (see the Clients section of this post). The private AddVote method is just a method that public or other private methods call. It accesses some static members to track which client has the highest bid.

public class VoteHub : Hub
    private static List<Item> VoteItems = new List<Item>();
    private static VoteRContext db = new VoteRContext();

    public void Vote(int id)
        // AddVote tabulates the vote        
        var votes = AddVote(id);
        // Clients.All.updateVoteResults notifies all clients that someone has voted and the page updates itself to relect that
        Clients.All.updateVoteResults(id, votes);
    private static Item AddVote(int id) {

        // If the item is in VoteItems, we’re tracking it, so just increment and return
        var voteItem = VoteItems.Find(v => v.Id == id);       
        if (voteItem != null)
            return voteItem;
        // If the item wasn’t in VoteItems, it’s the first time someone voted for it.
        // Add it to VoteItems and increment from zero
            var item = db.Items.Find(id);
            return item;  
    public override Task OnConnected()
        // Send voting history to caller only so they can see an updated view of the votes  
        return base.OnConnected();

Any custom public method (not overrides) in that you add to your Hub class is callable via dot notation from the client, via a special property. Notice that in the above code sample that there is no need to write code to deal with concurrency or transport negotiation, SignalR does it all for you.

Something that is a bit different from standard web development are the calls to Clients.Caller.joinVoting and Clients.All.updateVoteResults. By accessing the Clients property of the Hub class, we can effectively use that open pipeline to call the joinVoting and updateVoteResults methods on the client using dot notation. You can pass simple or complex arguments, as shown in the code above. SignalR does all the serialization of objects such as the List<T> automatically. Let’s see how to define these methods on the client in JavaScript and how SignalR connects Hub and Client code. The Clients property of the Hub contains the following methods: All, AllExcept, Client, Caller, Group and a few other methods that you can use to send messages to specific clients or groups of clients through the Hub. This gives you a granular way to deal with client-client connectivity.


When using ASP.NET MVC, we can render some the data on the server in Razor views, and add JavaScript for rich client interactions. Below is a Razor view that loops through an IEnumerable<VoteR.Models.Item> object rendering the name, image, number of votes, and a voting button. After every 4th item, the loop moves to the next row. The <script> tags render at the end of the page. Default.js contains SignalR code that votes on behalf of the user and updates the screen with the current number of votes. Because SignalR is real-time, the current number of votes will be up to date. None of the ASP.NET MVC code is different than we normally write. This is a plain MVC view. We’ll use JavaScript to take data from the view and send to the server.

@model IEnumerable<VoteR.Models.Item>
        @{var i = 1; }
            @foreach (var item in Model)
                <td style=”border:1px solid #000; width=”200px”>
                    <div><img src=”@Url.Content(item.Image) width=”125″ height=”125″ /></div>
                    <h4>Votes: <span data-itemid=”@item.Id“>0</span></h4>
                    <button id=”@item.Id“>Vote For This</button>
                if (i % 4 == 0)

@section scripts {
    <script src=”~/Scripts/jquery-1.10.2.js”></script>
    <script src=”~/Scripts/jquery.signalR-2.0.3.js”></script>
    <script src=”~/signalr/hubs”></script>
    <script src=”~/Scripts/default.js”></script>

With script, we first must obtain a connection to the VoteHub and store it in the voteHub variable. Notice the syntax , $.connection, is a static reference. This is a proxy that SignalR automatically creates for us at the /signalr/hubs location. You need do nothing special for the proxy to work.

In the JavaScript below, in the assignment of voteHub property, the $.connection.voteHub part might look like a typo, but SignalR uses camelCasing on the client following popular JavaScript notations. This means that the default manner in which you reference the VoteHub class is voteHub. You can change this by adding the HubName attribute to the Hub class (server side) and specifying the exact name and case of the class, like this: HubName(“VoteHub”). The it changes the proxy to reflect the casing.

After obtaining a connection to the hub, we must start the hub if it isn’t already started. This is a good time to wire up any events such as click events where you’ll be calling hub methods. After wiring up calls to the hub, it’s time to declare methods that the server will call. In the example below, these methods are voteHub.client.joinVoting and voteHub.client.updateVoteResults. Notice their declaration uses the hub.client.method syntax, hanging the methods off of the client property of the reference to the hub. To call code on the server, just use the server property of the client side hub object. In this case, that is The code passes the value of to the method. “This”, in this case is the button containing the ID of the item the user is voting for.

$(function () {
    var voteHub = $.connection.voteHub;
    $.connection.hub.start().done(function () {
        $(“button”).click(function () {

    voteHub.client.updateVoteResults = function (id, vote) {
        var voteFor = $(“span[data-itemid='” + vote.Id + “‘]”);
        voteFor[0].textContent = vote.Votes;

    voteHub.client.joinVoting = function (votes) {    
        for (i = 0; i <= votes.length – 1; i++) {
            var voteFor = $(“span[data-itemid='” + votes[i].Id + “‘]”);
            voteFor[0].textContent = votes[i].Votes;

When a new user connects, the OnConnected method in the Hubs example calls the client side joinvoting and passes in voting history. This way the new voter is current, as joinVoting also displays all the information about all the votes in progress. Examining either the voteHub object or Hub class, you’ll see the server and Clients properties. These are the properties that enable the two-way real-time communication between the hub and the client. All you do is attach public methods to them and make the calls using the hub.server.method syntax. Finally The updateVoteResults method does the UI update, so each item’s <span> element displays how many votes it has.


There are many kinds of websites and apps that can benefit from SignalR’s real-time, two-way, communications model. Perhaps a stockbroker needs financial information to buy the right stock at the right time and get a promotion. Or maybe someone is building the next big thing in social networking and the “likes” need to happen right away. That high-action game that everyone is addicted to needs to be in real-time or people wouldn’t enjoy it as much. If it’s an app, enjoyment and a rich experience translate directly to ratings, which in turn translates to more visibility and revenue.

While in this article I’ve only mentioned Hubs and clients, there is lower level of abstraction that SignalR offers called a Persistent Connection. If you, for whatever reason, need to perform more of the lower level tasks regarding connection management, the PersistentConnection class is what you’d use. If you check out the members of the PersistentConnection class, they look a lot like the Hub class but with more members regarding connectivity. It gives you more granular control, but for most scenarios, hubs and clients will work just fine.

Download sample code: 



Scott Hanselman on SignalR

Share this post...

Designing and Programming Accessible Websites and Apps

Share this post...

All too often, popular websites and apps fail to design for accessibility, unknowingly resulting in a huge loss of potential customers who cannot consume or access the site. This is all too often due to overestimating the amount of work it takes to make a website accessible, while also underestimating how many users require accessible content. As you’ll see here, there are a few basics you need to know about designing websites and writing code that considers accessible users as first class users.

Web Accessibility Overview

WebAIM says that about 20% of the population has some sort of disability that affects their lives, and often it affects the way they use the internet. That means 62.8 million Americans and 1.4 billion people worldwide.

There are four main types of disabilities that one might contend with, and that you can consider when designing  websites and apps.

  1. Visual : Vision impairments range from a slight loss of vision to complete blindness. Contrast sensitivity and colorblindness are also common visual impairments.
  2. Auditory: Often, those with hearing impairments cannot discern background noise from important sounds, or have any degree in loss of hearing, or a combination thereof.
  3. Motor : Diseases such as dyslexia, ALS, and Parkinson are often behind a motor impairment. Neurological and spinal damage contribute as well to motor impairments.
  4. Cognitive : ADHD, Dyslexia, and other disorders contribute to the challenges these folks face in using the web.

In other words, there is no “normal”. For every human quality or behavior runs across spectrum. Some can navigate a site easily where others need help. The majority of the population might see red one way, but those with color vision differences will not. People from every walk of life and corner of the planet range in their ability and opportunity. As developers who create websites that can theoretically reach almost the entire world, we should ensure that as many as users possible can access our products that we build, be they websites or native apps. Good developers want to make it as easy as possible for all (or as many as possible) users.

At some point, everybody will need some assistive technology, even if it is what you’d consider a primitive one.



(Image says: I just used the accessibility settings on my iPhone to change the systemwide font to BOLD. Pure win. Give it a try.)

Me too. I must increase fonts on most websites and the default zoom in all browsers to clearly read any text. Sometimes something small like a font increase makes a big difference. Even to those who are considered able bodied like Scott and myself.

Designing with Accessibility in Mind

Way back in the beginning days of the internet, browsers and BBS software displayed little more than text. Fast forward a few decades and now the Web is largely visual. That means that a large percentage of data that crosses the internet is in the form of a image, video, or audio file, often to accompany, and as frequently to replace textual data. This change in data format is due to the wide availability of broadband connectivity. It has also contributed to many sites relying only on graphic data, which shuts out or limits a significant portion of the population from consuming the content. Below is a quick laundry list of things to consider when designing with accessibility (any of the above impairment types) in mind. Notice that most of these things will make it easier for those without disabilities as well.

  • Fonts should be large, clear, and have a high contrast
  • Use HTML5 semantic elements
  • Colors should have high contrast
  • Use a consistent and clear navigation scheme
  • Provide alternate ways to interact with the user instead of just the mouse and keyboard
  • Field tab orders should be straight forward
  • Label fields and elements such as buttons using the <label> element
  • Images should have alt attributes set to something quick and descriptive
  • Movies and animations should provide captions or transcripts
  • Organize content into distinct sections with clear headings

The list of techniques and suggestions above reveal not just things to do to make your site more accessible but these are indeed best practices in the realm of proper standard UX design. That’s because users should be able to access content from their favorite browser, OS, or device, including those with accessibility needs.


I’ve authored a few articles on designing and programming for accessibility at Internet Explorer’s Modern.IE site, that expand on this post by going into more depth about programming for visual, auditory, motor, and cognitive impairments.

Both WebAIM and Microsoft have an online Accessibility Center containing lots of great information about designing an accessible web.

Share this post...

Use the W3C Geolocation API to create location aware web sites

Share this post...

Location aware services and applications are becoming more important than ever before, as smartphones, tablets, and other fully featured mobile devices become ubiquitous. The W3C Geolocation API gives developers an easy way to integrate client side location aware services within their web pages.

Hello, location aware world!

With the advent of geolocation services and mapping APIs, web sites and applications are popping up daily providing the following types location aware software:

  • Games and social applications, (e.g., Foursquare, Twitter, Trip It, Facebook, etc…)
  • Search applications for local services (e.g., restaurants, shops, entertainment, etc…)
  • Navigation & maps
  • Package shipping/tracking & transportation services
  • Personal health & fitness
  • More…

Notice there’s a good mix of both business and consumer applications that benefit from using geolocation. Fortunately, for developers, location aware web sites and apps are easy to create with web standards like HTML5, JavaScript, and CSS. On top of that, APIs like Bing  or Google Maps make great companions to these sites – and don’t forget 3rd party APIs such as Foursquare or Yelp.

How location aware web sites work

Geolocation apps work by detecting the user’s location via positional data that it receives from a geolocation source.

There are three basic steps to the process:

  1. The client browses to a web page that attempts to access the geolocation source.
  2. The app requests permission to send access the geolocation source.
  3. If the user permits, the app or web site can access and use the user’s positional data. (If not, an error occurs. See below

Once you have obtained the user’s coordinates from the API, you can display maps, give directions,show nearby points of interest

However, keep in mind that the device is the deciding factor regarding the accuracy of the positional data. For example, using a 3G smart phone should yield more accurate results than a desktop machine that connects through an ISP a mile away, using an IP address based method. Devices can use one or more of these methods:

  • Coordinate triangulation
  • Global Positioning System (GPS)
  • Wi-Fi with MAC addresses from RFID, Wi-Fi, and Bluetooth
  • IP address
  • GSM or CDMA cell phone IDs
  • Custom sources: Some phone manufacturers like Nokia

Many smart phones provide a way for users to switch between sources such as 3G or WIFI.

Obtaining the user’s positional data using the HTML5 Geolocation API.

For creating web sites either straight-up JavaScript or jQuery will work fine with the geolocation API. It’s quite small, with only three methods:

Method Description
clearWatch Stops listening for updates to the current geographical location.
getCurrentPosition Obtains the geographic position, in terms of latitude and longitude coordinates.
watchPosition Begins listening for updates to the current geographical location of the device running the client. Use this method to listen for location updates.

Before obtaining the user’s coordinates, a call to Modernizr performs feature detection for geolocation support. If the browser supports geolocation, the code calls the watchPosition() method, and passes success and error callback methods as arguments. Below is the code sample outlining  the call to watchPosition().

$(function () {
    var watchID;
    $("#watch").click(function () {
        if (Modernizr.geolocation) {
            var nav = window.navigator;
            if (nav != null) {
                var geoloc = nav.geolocation;
                watchID = geoloc.watchPosition(successCallback, errorCallback);
        { $("#message").text("You'll need to enter your address manually."); }

A successful completion of the watchPosition() method triggers the successCallback() method. At this time, the code can access the positional data returned from the Geolocation service in order to display Bing maps, list nearby attractions, or whatever is required. Below shows code that obtains the user’s coordinates, then displays the latitude and longitude in a web page <div> element (<div id=”message”>). Notice that the position argument  is populated with data, however not all the properties will contain values (e.g., altitude), depending on the capabilities the device and service.

function successCallback(position) {
    var latitude = position.coords.latitude;
    var longitude = position.coords.longitude;
    $("#message").text("There you are at " + latitude + " " + longitude);

Of course, the code won’t always run successfully. There are many things that can get in the way: bad weather, permission denied, timeouts, no cell reception, and gremlins, to name a few.

Dealing with errors and timeouts

The errorCallback() function does what you might expect, it runs when an error occurs. There are three frequently occurring errors to look for when the errorCallback() executes:


A switch statement works nicely to determine the error source and take corrective action, as each case checks value in the error.code property against a set of constants that correspond to error numbers.

function handle_errors(error) {
    switch (error.code) {
        case error.PERMISSION_DENIED: 
            alert("User did not share geolocation data");
        case error.POSITION_UNAVAILABLE: 
            alert("Could not detect current position");
        case error.TIMEOUT: 
            alert("Time out");
            alert("Unknown error");



Location aware web sites are becoming more important than ever before, and since the W3C Geolocation API is a standard, it works with any technology ranging from plain HTML to ASP.NET.

To get started creating location aware sites, check out the following resources:

W3C Geolocation Introduction

Geolocation APIs & client side frameworks on Code Project

Share this post...

Upload and download files using ASP.NET MVC

Share this post...

Uploading and downloading files are common functions you’ll see in most websites and apps. Fortunately, it’s easy to write code to upload and download files using ASP.NET MVC. To start, we need a view and controller pair to upload a file. This is the same HTML and MVC code that you already know. However, there is no need for the model portion of the MVC pattern if you are only uploading files to disk and not working with a database. Otherwise, files can be a property of a model, for example, a profile picture.

The upload view

First, we must start in the view by creatingan HTML <form> element. You can create the form with the Html.BeginForm helper and pass in the following arguments, in the following order (for this particular overload signature):

  1. Action method name : Action method that processes uploaded file
  2. Controller name : Controller that belongs to above action method
  3. FormMethod : Any acceptable HTTP verb
  4. enctype : Appropriate encoding type

Using Helpers is a great way to take advantage of built in features of the ASP.NET MVC framework such as accessing routing information to create a link or using strongly typed objects to render HTML. In the case of the Html.BeginForm helper, we are rendering a <form> element. The Html.BeginForm helper expects an enctype attribute that designates that the form can send binary data as well as textual data in the HTTP POST request. Since the default encoding type is “text-plain” the HTTP Request will not send binary data (that means files!) to the server along with the usual textual form data, so you must set the enctype attribute to multipart/form data or it will not work!

Below is a complete sample of an MVC view containing a form with a file input and submit button:

@using (Html.BeginForm("Upload", "Home", FormMethod.Post, 
    new { enctype = "multipart/form-data" } )) 

        <legend>Upload a file</legend>
        <div class="editor-field">
            @Html.TextBox("file", "", new { type = "file" })    
       <div class="editor-field">
            <input type="submit" value="Upload" />

ASP.NET Web Forms has a FileUpload Control, but in ASP.NET MVC our options are either a plain HTML element such as <input type=”file” /> or the TextBox and TextBoxFor Html Helpers (or any helper that outputs a file field). Any Html Helper that outputs an <input type=”file”> tag works. In the example above, the type, id, and name attributes of this tag are all set to “file”. A quick look in the browser using the IE Developer Tools illustrates what the Html.BeginForm and TextBox helpers from the above code sample have rendered:


When the user clicks the submit button, it causes an HTTP POST submission to /Home/Upload, which maps to the Home Controller’s Upload action method. The Upload action method receives the file and form data and from there you can perform the actual upload and save the file to disk or put in the cloud.

The upload action method

Action methods of MVC Controllers accept incoming HTTP requests for processing. Each HTTP request has a certain way, or method (POST GET PUT DELETE etc..) that it sends data to the server. The receiving action method must expect that type of request in order to process it. Since HTTP GET is the default, you must apply the HttpPost attribute to the Upload action method. This, of course, matches the method=”post” attribute of the HTML <form> element.

You can access uploaded files in the action method by querying the argument that is of type HttpPostedFileBase . The name of this argument, “file” in the below sample, must match the name of its corresponding file input in the HTML form (i.e., <input type=”file” name=”file”>). This allows ASP.NET MVC’s model binding to occur for file uploads. Ensuring the names match is using a concept called Convention over Configuration and leads to more readable code.

public ActionResult Upload(HttpPostedFileBase file)
        if (file.ContentLength > 0)
            var fileName = Path.GetFileName(file.FileName);
            var path = Path.Combine(Server.MapPath("~/App_Data/Images"), fileName);
        ViewBag.Message = "Upload successful";
        return RedirectToAction("Index");
        ViewBag.Message = "Upload failed";
        return RedirectToAction("Uploads");

If you need to upload multiple files, use IEnumerable<HttpPostedFileBase> instead of a single HttpPostedFile and loop through the collection to access individual files. When completing an upload, be sure that you have the correct permissions to write to the directory you want, then use classes from System.IO to access the file system and save the file.

System.IO.Path.GetFileName retrieves a file name including its extension, and System.IO.Path.Combine combines two or more strings to create a complete path. Because we’re working with an uploaded file from HTTP, we need Server.MapPath to map a virtual path (HTTP) to a physical directory (C:\) . In this case the mapping is from the webroot, i.e., “~/” to the <project root>\App_Data\Images directory. I’m saving files to the App_Data directory to demonstrate concepts, but in real world sites it is unlikely that internet users would have privileges to save files there, so check with your sys admin or Web hoster as to where you should upload and download files

The sample code above also overwrites any existing files, so if that’s an issue you can generate a unique file name by spinning up a Guid and using that as the name, as shown here:

var guid = Guid.NewGuid();

If the file to upload is accompanying form data, the controller action method signature should contain the model type and an HttpPostedFileBase type for the file. For instance, if the file is a user’s profile picture and part of a Person model, the action method signature should look like the following:

public ActionResult Upload( Person Person, HttpPostedFileBase file ) {… }

If you are using Convention over Configuration then model binding will take care of everything and all you do is access the method’s arguments.

In order to download, we need the same MVC components – a view and a controller. We’ll start at the controller.

The Download Action Method

Usually the UI presents a list or grid of links or images in which the user can click to download an image or file. What we’ll use for this example is a simple list of links of images to download. We can do this by creating a List<string> to store the file names in hyperlinks for download. The code below shows obtaining the directory and file information and adding the file names to the list of strings. The method then returns the list of strings as a model to the view.

public FileActionResult Downloads() 
    var dir = new System.IO.DirectoryInfo(Server.MapPath("~/App_Data/Images/"));
    System.IO.FileInfo[] fileNames = dir.GetFiles("*.*");            
    List<string> items = new List<string>();
    foreach (var file in fileNames)

    return View(items);           

The view accepts the list of strings and displays them in the page.

The Download View

Notice that the model for this view is a List<string> type instead of a custom object as usual. Of course, this the view consists of a simple for loop that cycles through a list of strings containing the file names and displays them in <label> and <a> tags. The hyperlinks render so that they point to the Home controller’s Download action method, and pass in the name of the file as a URL parameter. Cycling through a list of strings means that you can use array syntax (i.e., @Model[i]) to access each member in the list.

@model List<string>

        <th>File Name</th>
    @for (var i =0; i <= Model.Count -1; i++) {
                @Html.ActionLink("Download", "Download", new  { ImageName=@Model[i].ToString() })           

The image below is what the download view produces. The ActionLink Helper renders links that point to the Home controller’s Download action method, passing in the image name as a query string. I’m using the defaults but you might want to consider configuring Routing so that the URL looks friendlier.


As users click on the download link, the Download action method returns a FileResult:

 public FileResult Download(string ImageName)
return File(“<your path>” + ImageName, System.Net.Mime.MediaTypeNames.Application

However, you can also return a FileContentResult, FilePathResult, or  FileStreamResult (don’t forget to match the action method’s return type to the type you will use):

FileContentResult : Use this when want to use a byte array to access the file. In this scenario, you might have obtained the file as a byte array from a database call.

return new FileContentResult(byteArray, “image/jpeg”);

FilePathResult  : Returns a file on disk when you must access via a file path. In the FilePathResult you can return a File type or a FileStreamResult.

return new FilePathResult(“~/App_Data/Images/” + ImageName, System.Net.Mime.MediaTypeNames.Application.Octet);

FileStreamResult : Sends a stream out to the response.

return new FileStreamResult(new FileStream(“<your path>”, FileMode.Open), “image/jpeg”);

The various ways to return a file are very similar but allow sufficient customizations to meet the needs of most scenarios. Sometimes the file is from a stream or byte array, or sometimes you only have a simple file path. Media types as well as the System.Net.Mime.MediaTypeNames enum are available so you can designate the file type for download, as the above samples demonstrate.


Code for uploading and downloading files are mandatory tasks for Web developers at some point in time. We want to allow users to safely upload and download files to go along with other data, and using ASP.NET MVC means you can use Html Helpers as an easy way to provide this functionality.

More on the dev tools:

Profile & Tune Web Pages Using IE Developer Tools

Investigate Web Pages Using IE Developer Tools

More on the Razor view engine:

Introducing ASP.NET MVC development w/the Razor view engine

Share this post...