Mobile != NetworkConnected

By | July 9, 2012

Unlike all the coding you’ve been doing for a desktop, when writing for mobile applications (i.e.: not becoming a COBOL programmer) you need to keep in mind that your end user won’t always have network connectivity.

“Well duh, just wrap your stuff in an if statement”

Right, so do you really want your code to look like this?

try
{
	// do your network stuff
}
catch
{
	// oops you're not connected do some stuff
}

or

            if (!System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
            {
                // oops you're not connected do some stuff
            }
            else
            {
                // do your network stuff
            }

I can see that getting pretty damn messy really quick. Not to mention, what happens when Windows Phone 8 comes out and you have a different call to make? Or want to build this same source code base on Windows 8? Now you’ve got to search all your code for every check and add something, delete something, change something, add an #ifdef, bah.
But wait! There’s a better way. Enter our super-awesome built-in class Action<T>()!
I wrote this handy little class when I first started mobile dev and have used it ever since. It cleans up my code a ton, and ensures that it all works the way it’s supposed to:

	public static class ConnectedExecution
	{
		public static void Run(Action action, Action failureHandler)
		{
			if (!System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
			{
				if (failureHandler != null)
				{
					failureHandler();
				}
			}
			else
			{
				action();
			}
		}
	}

Usage looks like:

			ConnectedExecution.Run(() =>
			{
				// my cooler-than yours network stuff
			},
			() =>
			{
				// user prompt that stuff ain't connected
			});

Now you’ve got one class that controls your network accessibility check.
Hope you find this useful. Remember, consider the fact that you’re not always able to get out to the internet in your app! This little ditty can help you do that.

Enjoy

UPDATE
After reading this post, my good friend Sebastian over at DotNetApp.com suggested I combine my handy-dandy class w/ his NetworkInformationUtility class. “A splendid idea!” I said (right, Sebastian?)
I took Sebastian’s code (attached at the end of this post) and Async’d it all up, added 15 pieces of flair, and came out w/ this sweet usage:

		async public static void RunAsync(Action action, Action failureHandler, int timeoutMs = 1000)
		{
			var checkResult = await NetworkInformationUtility.GetNetworkTypeTaskAsync(timeoutMs);
			if (checkResult.HasInternet)
			{
				action();
			}
			else
			{
				failureHandler();
			}
		}

Which you call now from client simply by doing:

				ConnectedExecution.RunAsync(
					() =>
					{ // connected code
					},
					() =>
					{ // disconnected code
					},
					timeoutMs: 3000);

Attachments
ConnectedExecution.zip