Interacting with web pages using Selenium WebDriver for C#

I’ve been using Selenium WebDriver for C# a lot lately, for a number of projects that involved interacting with a web browser in some manner. I’ve used a lot of applications and libraries over the past few years that provide this functionality, but I’ve never come across one as intuitive and reliable as Selenium WebDriver – if you work on any projects that involve interacting with a web browser to automate some process, you need to read this post.

In this post I’ll take you through the process of using Selenium WebDriver to automate some interaction with a web browser and hopefully show you how powerful Selenium is. We’ll take a simple scenario as an example – submitting a request to the Google search engine.

Boot up Visual Studio and create a new C# console application. You’ll need to download the Selenim WebDriver for C# ZIP from Google Code, and add the DLL’s it contains as references to your project. For this example, you are only required to add WebDriver.dll and Newtonsoft.Json.Net35.dll. You’ll need to add the following using statements also:

using OpenQA.Selenium;
using OpenQA.Selenium.IE;

Now your ready to write some code that can drive your web browser. First, we’ll need to create the object that can do just that. With Selenium WebDriver, that is an IWebDriver object. This object can be instantiated to control Internet Explorer, Firefox, or Chrome. In this example, I’m going to use Internet Explorer.

IWebDriver driver = new InternetExplorerDriver();

You could also use ChromeDriver or FirefoxDriver above.

Next, let’s navigate to the Google website. The following code will handle this. One of the nice things about Selenium is that this call won’t return until the page is loaded in the browser. Other frameworks and libraries return immediately, requiring you to add waits/sleeps in your code to ensure the page is actually loaded, which is a terrible approach.

driver.Navigate().GoToUrl("http://www.google.com");

Aside – Internet Explorer Problems

One setting has to be changed in Internet Explorer in order for Selenium WebDriver to work correctly. Your security zones need to have protected mode either enabled or disabled – it doesn’t matter which, as long as it’s the same for each zone. I’ve got it set to on for each zone on my machine. To achieve this follow these steps:

  1. Open IE and go to Internet Options.
  2. Go to the ‘Security’ tab.
  3. Click on each of the zones, i.e. ‘Internet’, ‘Local intranet’, ‘Trusted sites’ and ‘Restricted sites’ and ensure that the ‘Enable Protected Mode (requires restarting Internet Explorer)’ check box is checked.

At this point, build your project in Visual Studio and run it. If you have followed the above steps correctly you will see Internet Explorer open, and navigate to Google automatically.

Now to actually interact with the open web page, Google in this case. In order to submit a search term, we’ll need to interact with the search term text box (to enter a search term), and the ‘Google Search’ button (to submit the request).

To do this, we’ll need to look at the source code for the page, to find the information we’ll need to interact with these controls. From looking at the source code, we can see that the markup for these controls looks like the following (formatted and commented for clarity):

Google Search

So, lets define the search term text box, and enter a search search:

IWebElement searchTermTB = driver.FindElement(By.Name("q"));
searchTermTB.SendKeys("jimmy collins blog");

Take note of what we’re doing here – we’re using the browser object we defined earlier to find an element with the name ‘q’. This is another great thing about Selenium – we can use just about any element attribute to try to find it, you could also use the ID, class name, tag name, or even the XPATH to find an element on the page.

Now build and run your application – you will once again see Internet Explorer opening up, but this time you’ll also see the search term being entered.

The final step is to actually click the ‘Google Search’ button and submit the query. The same approach that we used to find and interact the search term text box is followed:

IWebElement searchBtn = driver.FindElement(By.Name("btnG"));
searchBtn.Click();

Running your application now will open up Google, enter your search term, and hit the search button. The final thing to do is some cleanup – you will notice that currently when your application runs, the browser is left open once it completes. All we have to do to close the browser is:

driver.Close();

That’s how easy Selenium is to use. The ideal scenario is that you have interaction with your development team, and get them to agree to providing static IDs on all controls, that don’t change between versions of your site (unless in the case of a substantial UI revamp). That would make it a simple task to provide re-usable automation that can automatically verify changes to your site, or be used for regression testing.

Some Useful Android Debug Bridge Commands

As I mentioned in a previous post, the Android Debug Bridge is a hugely useful command line tool which installs with the Android SDK, to the ‘platform-tools’ directory.

If your doing any development or testing on Android devices, this is a must to have installed on your machine. I recommend adding it to your Windows PATH variable, as once you begin to use it, you’ll find yourself coming back to it more and more.

In this post, I’ll outline some of the most useful commands I’ve been using in my interactions with Android so far. First off, ensure you have an Android device connected to your machine, or an emulator running.

adb provides a command for determining what Android devices are detected to your machine, ‘adb devices‘:

adb devices command

Use the above command to ensure that adb detects your device or emulator. For example, it may not detect a physical device if you don’t have the correct USB drivers installed.

Here are some of the other commands that should prove useful to you when working with Android devices. Note that for some of these commands to work, you will need to a rooted Android device.

Install an APK file

adb install path_to_apk_file

Uninstall an APK file

adb uninstall com.myapp.main

View the device log buffers

adb logcat

Switch locale on the device (to German in this example)

adb shell “su -c ‘setprop persist.sys.language de; setprop persist.sys.country de; stop; sleep 5; start’

Start intent e.g. your applications main Activity

adb shell am start -a android.intent.action.MAIN -n com.myapp.main/.activities.MainActivity

Run all Instrumentation tests in a Java class against an application

adb shell instrument -e class com.myapp.tests.UITests -w com.myapp.test/android.test.InstrumentationTestRunner

Get a dump of the devices configuration (useful to include in bug reports)

adb bugreport

These are the commands I’ve found most useful when working with Android so far, view all available commands by typing adb -h from the command line.

Happy New Year.

Java Needs Automatic Properties

One of my main grievances with the Java programming language is it’s lack of Automatic Properties. These have existed in C# since .NET 3.0.

Automatic Properties make property-declaration more concise when no additional logic is required in the property accessors. For example, let’s say we want to implement a simple Book abstraction in an application, with four simple properties for arguments sake.

This is how it may look in C#:

public class Book
{
    public string Name { get; set; }

    public string Author { get; set; }

    public string ISBN { get; set; }

    public string Genre { get; set; }
}

Nice and simple, and written in about 1 minute when coupled with Visual Studio’s intellisense etc.

Now, lets take a look at a class offering the same basic functionality in Java:

public class Book 
{
    public String Name;
    public String Author;
    public String ISBN;
    public String Genre;
    
    public void setName(String name)
    {
        Name = name;
    }
    
    public String getName()
    {
        return Name;
    }
    
    public void setAuthor(String author)
    {
        Author = author;
    }
    
    public String getAuthor()
    {
        return Author;
    }
    
    public void setISBN(String isbn)
    {
        ISBN = isbn;
    }
    
    public String getISBN()
    {
        return ISBN;
    }
    
    public void setGenre(String genre)
    {
        Genre = genre;
    }
    
    public String getGenre()
    {
        return Genre;
    }
}

Just on a lines of code basis, it’s easy to see that C# wins overall. I understand that the designers of Java may not want to add this functionality to the language due to potentially breaking millions of current Java applications – but I’m sure it could be added in such a way that new applications could use it without breaking legacy applications.

Hell, a third party library, Project Lombok, already provides support for using Automatic Properties in Java, so it’s definitely possible.

I find this limitation really frustrating when working with Java.

Back To Java & Some Android Test Automation

I’ve been getting back into some Java programming lately, and for the most part, have enjoyed it immensely. I say ‘for the most part’, because I initially had the misfortune to install the Eclipse IDE. What an absolutely horrible application. OK, it’s great that it’s a free development environment, and for the most part works as expected, but it’s not the most intuitive application to use. One of my main annoyances also was the large amount of Eclipse related project files created for simple projects.

For example, for a simple application created in Eclipse, my ‘.metadata’ folder contain 546 files! I honestly have no idea what 95% of these files were for, and they changed. They changed a lot. For reasons I have no idea of. This really annoyed me as I use SVN as my source control system, and had permanently red folders – I’ve got a touch of OCD when it comes to knowing exactly what files I’ve changed and for what reason. Eclipse lasted three days on my system (two of those were the weekend).

Enter NetBeans 7.0.1. Having last used NetBeans around version 4 (around 2007 I think), I was expecting radical changes. There are some major changes, but to my surprise, all for the better. The simplicity of the IDE has been retained – everything was either where I remembered it, or where I expected it to be – a far superior machine to the aforementioned Eclipse.

My main reason for interacting with Java again, is related to one of my current work projects. I don’t have to say that the mobile applications arena has exploded in the last few years – that statement is quickly becoming a clichĂ©. One of the areas which needs to receive significant attention in my opinion is the area of mobile test automation. Some great tools already exist, but many are in their infancy. The problem also grows when you think of the requirement for any mobile test automation system to work across multiple versions of Android, and also multiple languages.

Doing some research on Friday afternoon, I came across MonkeyRunner. This is an Android supported API that provides the ability to interact with and control Android devices (physical or an emulator).

Deciding to take a look, my first hurdle was setting up my NetBeans IDE to work with the Android SDK. The Android developers documentation is heavily biased towards Eclipse, why I’m not sure. Having been sure someone had faced this challenge before, I turned to Google, and sure enough Binary Wasteland had an excellent article on setting up the Android SDK in NetBeans.

Next question – which test automation requirement to try to implement? The answer – the ability to take screen captures of applications running on an Android device. Our localization department use screen captures heavily, for unit testing of localized UI’s, screen shots for documentation, marketing requests etc. So such a feature would have to be included in any mobile test automation system.

To digress for a moment, I have to mention ADB. The Android Debug Bridge is an excellent command line tool that installs with the Android SDK. It allows you to connect to your Android device (wired or over WiFi), and install applications, remove applications, get certain properties of the device (e.g. the language), dump the entire configuration from the device for use in bug reports, along with many other features. Take a look in the ‘platform-tools’ directory in your Android SDK folder, adb.exe will be located in here. I suggest adding this directory to your Windows PATH variable, as you will find yourself using it a lot.

But back to the feature for taking screen captures of an Android device. This is quite simple. Some examples I found on the internet seem to be out of date since Android 4.0 (Ice Cream Sandwich) was released. There seems to be a new package called ‘ChimpChat’, which contains a wrapper for the ADB, and also the functionality for taking a screen capture previously contained in the MonkeyRunner package.

Time for some code:


import com.android.chimpchat.core.*;
import com.android.chimpchat.adb.*;

public static void main(String[] args) 
{ 
        AdbBackend adb = new AdbBackend();
        IChimpDevice device = adb.waitForConnection();
        
        IChimpImage image =  device.takeSnapshot();
        image.writeToFile("C:\\Test.png", "png");
        
        device.dispose();
}

The above code will do the following:

  • Create a new instance of the ADB wrapper.
  • Create an IChimpDevice, and wait for a connection.
  • Take a screenshot, and save it to the location specified.
  • Close the connection to the device.

I have some questions though. ADB seems to only support one connected device, and always connects to the first one it finds if more than one device is connected. What if I want to interact with a number of Android devices, e.g. a mobile phone and a tablet? I need to look into this.

I also need to figure out how we will interact with our complex mobile application UI’s, how specific UI elements will be identified, and if we can programmatically switch the language settings on attached Android devices.

But the above is a good start towards a re-usable mobile test automation system.

Google Search Results Weirdness

Over on Twitter, @semperos has brought an interesting point to my attention. My posts from this blog, when indexed by Google, have the date ‘August 29th 1997′ in the meta data relating to the result. This gives the impression that posts were written on this date:

Google Search Results

It seems that GoogleBot is taking the date from the text in the banner on my site:

My website banner

(From one of my favourite movies)

This is contrary to everything I’ve read, which states that Google’s crawler is either smart enough to recognise the date of your last post, or this is the date of the last crawl. The above screen captures obviously rule out both of these possibilities.

It looks, to the Google outsider like myself, that GoogleBot is just taking the first date it finds on a page it is crawling, and using that in the description on the search results page.

If anyone from Google happens to read this – I’d love an explanation or clarification…

Taking screenshots with Selenium WebDriver

Time to do something a bit more useful using Selenium WebDriver. Taking screenshots as we cycle through our web pages has obvious advantages for unit testing. Firstly we can just run an application overnight, have it visit every page on our website, and review the screenshots for obvious bugs the next morning before releasing to QA. Secondly, we can screenshot our localized websites, and have them linguistically reviewed, or hand off the English screenshots to our translators to provide context during the translation process.

Taking screenshots with WebDriver is exceptionally easy. The thing I like about it most, is that it takes a screenshot of just the area of the browser in which the content resides – no IE/FF/Chrome toolbars etc. But, it also takes the entire webpage – even content not visible on the screen at that time. This is a great feature. I’ve had the problem in the past with long web pages, ones for example that contain a EULA or other long document, where the screenshots had to be taken at intervals as the page scrolled. Obviously not the best process, and not very reusable code.

As mentioned in a previous post, I’m using the Selenium Client Driver for C#. I’ve created a library into which I’m adding useful functions like taking screenshots etc.

The code to take a screenshot is not complex:

using OpenQA.Selenium.IE;
using OpenQA.Selenium;
using System.Drawing.Imaging;

public void TakeScreenshot(IWebDriver driver, string saveLocation)
{
    ITakesScreenshot screenshotDriver = driver as ITakesScreenshot;
    Screenshot screenshot = screenshotDriver.GetScreenshot();
    screenshot.SaveAsFile(saveLocation, ImageFormat.Png);
}

The libraries referenced can be found in the Selenium Client Driver for C# package which can be downloaded from the Selenium website. These will need to be added to your C# project.

Notice in the above function we pass an ‘IWebDriver’ Object, as opposed to a specific InternetExplorerDriver, FirefoxDriver etc. This means this function can be used regardless of which browser you are dealing with.

Using the function is also a trival matter. Let’s browse to Google and take a screenshot, saving it in the root of the ‘C:\’ drive:

IWebDriver driver = new InternetExplorerDriver();
driver.Navigate().GoToUrl("http://www.google.com");
TakeScreenshot(driver, @"C:\screenshot.png");

Note that the TakeScreenshot function can be customized to use any image format – in fact it should probably be a function parameter. I chose PNG simply because of the small size of the generated image.

Running Selenium Tests with C# & NUnit

Something I’m working on currently requires some automation of a web browser, so what a perfect opportunity to get some exposure to Selenium.

In this post I’ll outline the basics of creating and running a simple Selenium test using Selenium and NUnit. The implementation language will be C#. To get started, you will need to download the following:

Extract the Selenium Client Driver files, these DLL’s will be referenced in the Visual Studio project we create. Install NUnit using the .msi installer.

Now, let’s create the actual test:

  1. Launch Visual Studio 2010 and create a new class library project.
  2. Add a reference to nunit.framework.dll. This can be found under the NUnit installation directory at ‘bin\net-2.0\framework’.
  3. Add references to all the DLL’s contained in the Selenium Client Driver package you downloaded earlier.
  4. We’re now ready to add the code that will run a Selenium test. Add the following code to your class library project:
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.IE;

namespace FirstSeleniumTest
{
    [TestFixture]
    public class SeleniumTest
    {
        private IWebDriver driver;

        [SetUp]
        public void SetUp()
        {
            driver = new InternetExplorerDriver();
        }

        [Test]
        public void TestGoogle()
        {
            driver.Navigate().GoToUrl("http://www.google.com");
        }

        [TearDown]
        public void TearDown()
        {
            driver.Quit();
            driver.Dispose();
        } 
    }
}

The above code should be pretty easy to understand. Notice the annotations around the functions.

  • [SetUp] – This is where any test setup should be completed. In the above example we’re creating a new instance of InternetExplorerDriver, setting it up for our test to run later.
  • [Test] – This is where the test steps are defined. In this example, we’re just navigating to Google.
  • [TearDown] – In this section, any steps to be taken to cleanup the environment after your test has run can be defined. Here, all we’ll do is close Internet Explorer

Now that we have written a simple test, let’s try running it using NUnit. Before moving on, ensure that the above code builds successfully in your environment.

To run the test it’s just a matter of launching NUnit and opening up the DLL built from the Visual Studio project created above. You should see the ‘TestGoogle’ test listed. Simply select the test and hit the ‘Run’ button to initiate the test. You will see Internet Explorer launch, and then close.

NUnit

One thing you may need to do, depending on your IE version, is to disable protected mode for Internet and Restricted Zones in Internet Explorer Security Settings (don’t forget to re-enable these once you’ve finished experimenting with Selenium).

In a future post, I’ll outline how to do more complex tasks during your tests such as taking screenshots and navigating around web pages under tests.

Refactoring horrible nested if-else statements

I wrote this at some point this week, I was looking back at it tonight and released how truly awful it looks:

if(filePath.Contains(".CSS"))
    return true;
else
    return false;
else if(filePath.Contains(".JS"))
    return true;
else
    return false;
else if(filePath.Contains("_STR"))
    return true;
else
    return false;
else if(filePath.Contains(".VBS"))
    return true;
else
    return false;
else if(filePath.Contains(".HTM"))
    return true;
else
    return false;
else if(filePath.Contains(".BMP"))
    return true;
else
    return false;
else if(filePath.Contains("GIF"))
    return true;
else
    return false;

Terrible huh? What was I thinking?

How much better does this look:


bool copyFile;

copyFile = (filePath.Contains(".CSS"))      ? true:
               (filePath.Contains(".JS"))   ? true:
               (filePath.Contains("_STR"))  ? true:
               (filePath.Contains(".VBS"))  ? true:
               (filePath.Contains(".HTM"))  ? true:
               (filePath.Contains(".BMP"))  ? true:
               (filePath.Contains("GIF"))   ? true:
                                              false;
return copyFile;

I like it, impressed with that one for a Friday.

Handling Exceptions on Windows Phone 7

In this post I’ll outline how to deal with exceptions in a Windows Phone 7 application. Ideally when an exception happens, we want to display some meaningful information to the user that can be provided to the developer to aid in the debugging of the issue. The worst thing that can happen is for the application to crash and just exit. This can lead to frustration on the users part (as I’ve experienced with the official Twitter application on iOS 4.0), or worse dissuade a user from purchasing any other applications bearing your name.

In this example, when an exception occurs, we’ll ensure that we navigate to an error page, and display the stack trace. Aside, this is obviously not the best thing to display to an end user. The best approach may be to display a generic error message with an option to report the error, which then emails the exception information to your support address. I leave that as an exercise to the reader, in this example, we’ll just display the stack trace information directly to the user:

1. Add a new Windows Phone Portrait Page to your Windows Phone 7 project in Visual Studio. For the purpose of this example, I’ve named the page ‘Error.xaml’.

2. In ‘Error.xaml’, locate the ‘LayoutRoot’ Grid element, and replace its content with the following:















3. The page you created above will act as the container for any exceptions that we need to display. Next, open up ‘Error.xaml.cs’, and add the following code:


using System.Windows.Navigation;
...
...

public static Exception Exception;

// Executes when the user navigates to this page.
protected override void OnNavigatedTo(NavigationEventArgs e)
{
ErrorText.Text = Exception.ToString();
}

This sets up an Exception Object that is hooked up to ErrorText.Text upon navigating to the page.

4. Finally, we need to hook up an event handler that ensures that we navigate to this page whenever an unhandled exception occurs. This is done from ‘App.xaml.cs’. Open up ‘App.xaml.cs’, and replace the content of the ‘Application_UnhandledException’ function with the following code:


if (System.Diagnostics.Debugger.IsAttached)
{
// An unhandled exception has occurred; break in the debugger
System.Diagnostics.Debugger.Break();
}

// Running on a device / emulator without debugging
e.Handled = true;
Error.Exception = e.ExceptionObject;
(RootVisual as Microsoft.Phone.Controls.PhoneApplicationFrame).Source =
new Uri("/Error.xaml", UriKind.Relative);

If you have completed the above steps correctly, then whenever an unhandled exception occurs in your application, the application will navigate to this page, and display the exception stack trace.

To verify these steps, add a button to your ‘MainPage.xaml’ and have it link to a page that doesn’t exist, e.g.


NavigationService.Navigate(new Uri("/NotHere.xaml", UriKind.Relative));

Launch the application in the emulator, and click the button you just created, (You’ll need to launch without debugging). The result should be navigation to ‘Error.xaml’ with the exception details:

Windows Phone Error Example

WPF – Binding Data in an XML file to a ComboBox

Some things in WPF are very different from Windows Forms programming. Lately, I’ve been working on my first real UI in which I’ve used WPF over Windows Forms. Using XAML takes a little bit of getting used to, but I’m finding that I have a lot more control over the UI, along with the obvious advantage of seperating the UI presentation from the actual application logic.

Just the other day I needed to create a ComboBox control on a section of my UI, the items in which would need to be loaded from an XML file at runtime. The XML file was to be included as a resource.

The XML file looked something like this:






...

I wanted the ‘name’ attribute from each Language node to be bound to my ComboBox. In order to do this, first we need to define the XML file as a resource in our XAML:





...
...

Then, we just need to add the ItemsSource, SelectedValuePath, and DisplayMemberPath to the ComboBox XAML, specifying the resource we declared earlier, and the attribute that we want to bind:




Note the ‘SelectedItem’ can be set as well from the XAML, It’s set to ‘Arabic’ in the above example.

SharpSVN: A Gentle Introduction

SharpSVN is a really useful library which encapsulates the functionality of the Subversion client so we can leverage it programmatically from .NET applications. I can think of many uses for this. In the past, in some of the automation frameworks I’ve worked with, updating the source code from SVN has been a manual task ran weekly. Using SharpSVN, we could write a simple console application to accomplish this. It could also be useful to automate repetitive SVN tasks in a development environment.

In this post, I’m going to outline the basics of using SharpSVN, and in the process create a simple C# console application to check-out some source code.

For starters, we’ll need to download the SharpSVN package from here. Next, create a C# console application in Visual Studio. You’ll need to target .NET 2.0.

Unzip the SharpSVN package, and add ‘SharpSVN.dll’ as a reference to your console application. Next, add the following code. We’ll pass the location we want to check-out from as an argument to the application:


string Repository = string.Empty;

if (args.Length != 1)
{
Console.WriteLine("Usage: SharpSVN ");
}
else
{
Repository = args[0];
}

I’m assuming here that you’re already authenticated with your SVN server. Now the code to actually perform the check-out, which is really simple:


using (SvnClient client = new SvnClient())
{
try
{
SvnUriTarget target = new SvnUriTarget(Repository);

if (client.CheckOut(target, @"C:\Working"))
{
Console.WriteLine("Successfully checked out '" + Repository + @"' to 'C:\Working'");
}

}
catch(Exception e)
{
Console.WriteLine("Error occurred during check out: " + e.ToString());
}

That’s it. The above code will check-out the source code from the SVN repository you passed as an argument to ‘C:\Working’.

The only downside I’ve seen with SharpSVN, is that it only seems to work when I target .NET 2.0. Maybe I could download the source and try to compile it under .NET 4.0, but I haven’t tried that.

I see huge usage for this library in future projects, and it’s certainly better that a previous solution I had implemented using the command line interface to the TortoiseSVN client.

Happy Coding…

C# – Logging to the Windows Event Viewer

In the past for any applications I’ve written in C#, I’ve always logged any information I needed to in a .txt file in the Windows %temp% directory. This was really quite a messy approach when I consider it now.

Logging from your applications can be useful for a couple of reasons:

  • Auditing: Depending on your level of logging, you can get a step by step view of what’s happening with your application. I find this useful for testing as I write code.
  • Diagnostics: This is the more obvious use of logging from your application – capturing a stack trace or other useful information in the event of any issues.

Using the Windows Event Viewer to capture auditing or diagnostic logging is a much better approach, as you can specify when you log what type of event this is, i.e. ‘Information’ (for auditing), or ‘Warning’ and ‘Error’ (for diagnostic logging). This makes it a lot easier to find errors, and makes any logging you do highly readable.

I’ve created this class which wraps the logging to the Event Viewer functionality:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Diagnostics;

namespace EventLoggingExample
{
public class LoggingHelper
{
private string Application;
private string EventLogName;

///

/// Constructor
///

/// The application doing the logging /// The log to write to in the Event Viewer public LoggingHelper(string app, string log)
{
Application = app;
EventLogName = log;

// Create the event log if it doesn't exist
if (!EventLog.SourceExists(Application))
{
EventLog.CreateEventSource(Application, EventLogName);
}

}

///

/// Write to the event log
///

/// The message to write public void WriteToEventLog(string message, string type)
{
switch (type.ToUpper())
{
case "INFO":
EventLog.WriteEntry(Application, message, EventLogEntryType.Information);
break;
case "ERROR":
EventLog.WriteEntry(Application, message, EventLogEntryType.Error);
break;
case "WARN":
EventLog.WriteEntry(Application, message, EventLogEntryType.Warning);
break;
default:
EventLog.WriteEntry(Application, message, EventLogEntryType.Information);
break;
}
}
}
}

To use it, just create an instance and log at will:


LoggingHelper log = new LoggingHelper("MyApplication", "MyAppLog");
log.WriteToEventLog("Some application information", "info");
log.WriteToEventLog("This is your first warning!", "warn");
log.WriteToEventLog("An error has occurred...", "error");

This is definetely something I’ll be adding to my utilities library.

Windows Phone 7 – Check if first run

Many of the applications I’ve been looking at developing during my Windows Phone 7 endeavours have a common requirement – the ability to check if this is the first run of the application. For example, if you are designing an application that will access a service like Twitter or Facebook, you’ll need to gather the users login details in order for your application to function.

For example, on the first run of the application, we’ll want to display a login dialog, gather the users information and store it. We can use the isolated storage facility on Windows Phone 7 devices to store this information. If you’re unfamiliar with isolated storage, check out my previous post here.

Step 1 – Store a value to track if this is the first run

I added this code to the ‘Application_Launching’ function. This function is called each time your application is launched.


// Code to execute when the application is launching (eg, from Start)
// This code will not execute when the application is reactivated
private void Application_Launching(object sender, LaunchingEventArgs e)
{
// Set if this is the first run of the application or not
if (!settings.Contains("firstRun"))
{
settings.Add("firstRun", (bool)true);
}
else
{
settings["firstRun"] = (bool)false;
}
}

Step 2 – Intercept navigation to your main page, redirect if necessery

Next, we need to create an event handler to intercept any navigation the your main page, and redirect to your ‘first run’ page (login or whatever) if necessery.

First we check if we’re navigating to our main page, if we’re not the function just returns and navigation proceeds as normal. If we are, we’ll ensure that if it’s the first run of the application, the user will be redirected to a login page etc.


///

/// Event handler to intercept MainPage navigation
///

/// the frame /// navigation args void RootFrame_Navigating(object sender, NavigatingCancelEventArgs e)
{
// Only care about MainPage
if (e.Uri.ToString().Contains("/MainPage.xaml") != true)
{
return;
}

// Check if this is the first run of the application
if ((bool)settings["firstRun"])
{
e.Cancel = true;
RootFrame.Dispatcher.BeginInvoke(delegate
{
RootFrame.Navigate(new Uri("/FirstRun.xaml", UriKind.Relative));
settings["firstRun"] = (bool)false;
});
}
else
{
RootFrame.Dispatcher.BeginInvoke(delegate
{
RootFrame.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
});
}
}

Step 3 – Ensure the event handler is called when navigation occurs

Finally, we need ensure that the event handler we created in step 2 above is actually called when any navigation occurs. To accomplish this, all we need to do is add the following code in the constructor of the ‘App.xaml.cs’ file:

// Add this code to the constructor in App.xaml.cs

// Route the user to the login screen if it's the first run of the application
RootFrame.Navigating += new NavigatingCancelEventHandler(RootFrame_Navigating);

That’s pretty much it, I’ve successfully used the above mechanism in two different applications, hope this saves you some time!

ASP.NET MVC – Creating a DropDownList

I’ve been looking at the ASP.NET MVC framework for the past two weeks, and it has occurred to me that some of the simple things we may want to do when creating a web application may seem confusing to someone new to ASP.NET MVC – for example the task of creating a DropDownList control on a form. ASP.NET MVC provides a number of ‘HTML Helpers’ which we can easily use to construct the form items. ‘DropDownList’ is one of these HTML helpers we can use.

Let’s create a simple example form using some of these HTML helpers. To begin a form, we can use a helper, we just need to add this code to our View:


<% using (Html.BeginForm()){ %>

// Form data will go here

<% } %>

This creates the basic form code for us – no need to explicitly write any HTML code. Before adding the DropDownList control, we need to decide where we want to get the data which will bind to the list. We can either hard code the items, or use LINQ to SQL to grab them from a database at runtime.

Method 1 – Hardcoding the form items

With this approach, we just add the items to a list, and pass this list to ViewData, so we can access it from the View:


List items = new List();
items.Add(new SelectListItem
{
Text = "Apple",
Value = "1"
});
items.Add(new SelectListItem
{
Text = "Banana",
Value = "2",
Selected = true
});
items.Add(new SelectListItem
{
Text = "Orange",
Value = "3"
});

ViewData["DDLItems"] = items;
return ViewData;

Then, to actually display the DropDownList, we’d just need to add a single line to our View code, utilizing the DropDownList HTML helper:


<%= Html.DropDownList("DDLItems") %>

Method 2 – Using LINQ to SQL to get the data at runtime

We could also retrieve the list data from a database table at runtime using LINQ to SQL. In order for this approach to work, you will need to have generated LINQ to SQL classes for your database using the wizard in Visual Studio. Then we can easily write the code to retrieve the data:


// Get the list of supported languages (for example) from the DB
var db = new TransDBDataContext();
IEnumerable languages = db.trans_SupportedLanguages
.Select(c => new SelectListItem
{
Value = Convert.ToString(c.ID),
Text = c.Name.ToString()
});

ViewData["SupportedLanguages"] = languages;
return View();

Again, to display the DropDownList, we’d just need to add a single line of code to the View:


<%= Html.DropDownList("SupportedLanguages") %>

From the above, you can see how easy it is to render form items using the HTML helpers provided by ASP.NET MVC.

For a full list of the helpers, check out the MSDN documentation here.

Windows Phone 7 – Storing & Retrieving Information

I’m planning on doing a series of posts called ’2 Minute Tutorials’. I always get frustrated when searching for information on the Internet. Sometimes, I just want a simple explanation, and a code example that I can utilize immediately. This is what I hope to provide in this series of posts, which will be mostly related to Windows Phone 7, C#, and C++.

In this particular installment, I’m going to take you through the process of storing and retrieving information on the Windows Phone 7 platform – a certain requirment should you intend developing a WP7 application. You can store information on the phones local file system quite easily. This may be required for saving such things as user information like usernames and passwords to services such as Twitter, or application specific preferences such as a preferred language or orientation.

This functionality is provided by the IsolatedStorageSettings class contained in the System.IO.IsolatedStorage namespace. It’s ‘isolated’, because it can only be accessed by your application, not by any others. If you need to share information between applications, you’ll need to store it on the web somewhere – this offers local, isolated storage only.

IsolatedStorageSettings allows you to store name/value pairs in a dictionary. This data will always be there, even after powering off the phone. It will remain in the file system until you either remove it, or you uninstall the application to which it belongs.

Here’s an example of storing an item called ‘username’:

using System.IO.IsolatedStorage;
...
IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
settings.Add("username", "jimmy");

Simple. It’s just as easy to retrieve the data again:

string username = (string) settings['username'];

Some important things to remember:

  • Your application will throw an exception if you try to retrieve a value that is not present so you should always handle this case.
  • You can save anything, even Objects.
  • You have to explicitly cast your data when you retrieve it.

That’s it. It’s that simple to store and retrieve information on the local file system of a device running Windows Phone 7.

See here for the MSDN documention on IsolatedStorageSettings.