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.

Windows Phone 7 Development – First Impressions

Since my Christmas leave from work has begun, I’ve had some time to really look at Windows Phone 7 development over the last 2 days, and have gotten really excited about it all. I’ve been meaning to do this for ages (since WP7 was released actually), but have always either been too busy or suffered procrastination (thanks Zen Habits!).

Some positives:

  • Development Environment – I think Microsoft has done an excellent job on Visual Studio 2010, and the WP7 development tools plug in seamlessly. If you don’t already have Visual Studio 2010, Microsoft is offering a special Express Editon for Windows Phone.
  • Developer Resources – There are a huge amount of resources available on Microsoft’s App Hub (often called ‘MarketPlace’ – the equivalent of Apple’s ‘App Store’), ranging from tutorials, walkthroughs of some key concepts and full application code examples.
  • The Windows Phone Emulator – This is installed as part of the developer tools, and it really is state of the art. I haven’t purchased an actual device running WP7, but have been using the emulator to test my inital application effort. There are some obvious things that won’t work on the emulator, for example anything to do with the accellerometers (the emulator assumes it is lying on a flat surface), but it’s perfect for testing your inital Windows Phone 7 applications.
  • Familiarity – If you’ve ever developed using C# on the Windows platform, you already have a huge start in WP7 development.
  • Developer Subscription – The cost of a yearly developers subscription, a mere 99 Euro, can easily be covered with very little downloads of your applications (should you even be bothered about it).

The only ‘negative’ I’ve found so far is that I’ve had to purchase a (long overdue) brand new Dell running Windows 7 in order to create my development environment. My previous machine, running Windows XP, is not supported by the Windows Phone 7 development tools, which seems strange to me, since XP is not scheduled to be EOL’d until 2014. It seems to be another move by Microsoft to push people to move to Windows 7 or (shudder) Windows Vista.

Windows Phone 7 development is one of the three areas I want to become proficient with in the first half of 2011. I had initially focused on the iOS platform, but when I thought about it, it didn’t make much sense, since I’m already familiar with C# and didn’t feel I’d gain any real advantage by learning Objective C. Also, rumours began to circulate this week regarding Microsoft getting into bed with Nokia, so WP7 will surely gain more momentum in the first half of 2011.

My first application, (well under way!), will be a simple Twitter client. The reason I chose this is that it will encompass many of the key concepts I’ll need to learn, such as designing user interfaces for WP7, storing information locally on a WP7 device, and accessing external information via API’s. I plan to complete this over Christmas – screenshots to follow once it is.

Aside: If you’re interested in getting into developing on the Windows Phone 7 platform, check out Jeff Blankenburg’s 31 Days of Windows Phone, it’s the best introductory article series I’ve found so far.

C# – Using Bing’s Translation Web Service

Microsoft’s Bing Translator provides a translation web service which can be called via C#. In this post I’ll outline the steps to use this web service, and create a simple application to perform translations.

First, you’ll need to create a valid application ID for your application. This is required in order to be able to call the web service. Head over to Bing’s Developer Centre and sign in with your Windows Live ID. Follow the steps to create a new ID for your application, it’s a simple process and shouldn’t take you any more than 2 minutes.

Next, create a new project in Visual Studio, (I’ve created a simple Windows forms application to demonstrate this, but you could just as easily create a simple console application). You’ll need to add a service reference to your application either way. Do this by right-clicking on your solution and selecting ‘Add Service Reference’. Under ‘Address’, add this:

http://api.microsofttranslator.com/V1/SOAP.svc

Under ‘namespace’, be sure to enter a descriptive name for the service reference. Now, for the code to perform translations (You’ll need to add in the application ID you created earlier in order for this to work):

// Translating from English to German

string textToTranslate = "Hello, world";
string sourceLanguage = "en";
string targetLanguage = "de"
string translatedText = "";

try
{
BingTranslatorService.LanguageServiceClient client = new BingTranslatorService.LanguageServiceClient();
translatedText = client.Translate("Your App ID", textToTranslate, sourceLanguage, targetLanguage);
MessageBox.Show(translatedText);
}
catch (Exception ex)
{
MessageBox.Show("An error has occurred: " + ex.ToString(), "Error");
}

‘BingTranslatorService’ above is whatever you called the service reference added earlier. I’ve created this sample application to show how easy it is to create a simple translation application:

Simple Translation Application

Download the full source code, here. You’ll need to add in your application ID in order for this to work properly.

Localization of C# Applications – Short Introduction

If you plan on releasing your C# application in non-English speaking markets, you will obviously want the UI to display localized strings. When developing applications using .NET, it’s relatively simple to achieve this. In this post, I’ll outline the steps involved in localizing a simple C# application.

.NET applications store string resources in .resx files. These are XML format, with the main advantage being they are human readable and can be opened in any text editor, unlike resource DLL files for example. The only item not human readable in a .resx file, may be an embedded object, like a Bitmap file for example.

Start off by creating a simple Windows Forms application from Visual Studio, it will create an initial form for us to work on.  Select the form and on the ‘Properties’ dialog look for the ‘Localizable’ property and set it to ‘true’. You may also notice the ‘Language’ property, leave this set to ‘Default’ for the moment.

Next, add a button to the form and add some text to it, something simple, for example:

Simple Localizable Form

If you take a look under your form in ‘Solution Explorer’, you will notice a .resx file has been created. It will be named FormName.resx, open this up and search for the string on your button and you will see how it is stored. Now to add the equivalent German strings (or any other language you fancy!).

Recall the forms ‘Language’ property mentioned earlier, you will find it under ‘Properties’ when you’ve got the form selected. In the dropdown, change the value to ‘German’. You will not notice any visible changes, but you can now edit the strings on the form to represent the German equivalents. Do this for as many languages as you want to. Once you’ve done this, take a look under your form in ‘Solution Explorer’, you will notice that a new .resx file has been added automatically, FormName.de.resx. This will contain your German strings. You should note here that you can also change the layout of the form to include any required changes, in the event some strings are longer in certain languages, e.g. Greek.

Now when your application is run on a German operating system, the strings displayed will be automatically taken from FormName.de.resx, rather than FormName.resx.

A note about locale selection

The UI language used in Windows is a function of the CurrentUICulture setting. In order to see the German strings actually display, you would need to install a German language pack, and change your regional settings, or we could just set our locale programmatically in our application.

In order to test your German strings display correctly, first add the following imports:

using System.Globalization;
using System.Threading;

Then add the following code to your form initialization function, (before InitializeComponent()):

// Sets the UI culture to German (Germany).
Thread.CurrentThread.CurrentUICulture = new CultureInfo("de");

This will make our application believe it’s running on a German locale. Now run your application, you should see your German strings displayed:

German Strings Displayed

This post outlined the very basics of localizing .NET applications. In future posts, I plan on expanding this a bit to advanced topics such as avoiding common internationalization issues.

Retrieve settings from COM+ components via C#

Recently, I had a requirement to be able to retrieve settings information from a number of COM+ components running on a server, such as the Constructor String etc. The idea behind this was to give us a snapshot of a servers configuration, and also allow easy comparisons between different servers in the event of issues. This is tedious and time consuming to do manually, especially if you’ve got a large number of components within each COM+ application, so I resolved to write a small C# program to do this for me and write the data to a file.

COM+ provides an administration object model that exposes all of the functionality of the Component Services administrative tool, so by adding a reference to the necessary library, you can achieve anything you can do through the graphical administrative tool, programmatically. To get started, you’ll need to add a reference to the necessary library – ‘COM + 1.0 Admin Type Library’. This can be found under the ‘COM’ tab when you go to add a reference to your project in Visual Studio.

You’ll need to add the following import also:


using COMAdmin;

First, we’ll need to create an Object to store the catalog of COM+ components installed on the machine. Here’s the code to create this catalog, and also retrieve a list of all the COM+ applications it contains:


COMAdminCatalog catalog;
COMAdminCatalogCollection applications;

// Get the catalog
catalog = new COMAdminCatalog();

// Get the list of all COM+ applications contained within this catalog
applications = (COMAdminCatalogCollection)catalog.GetCollection("Applications");
applications.Populate();

Now we have an Object above, ‘applications’, which contains all the data regarding what COM+ applications are installed on this machine. To go a little deeper, and see which components each application contains, it’s just as easy:


foreach (COMAdminCatalogObject application in applications)
{
COMAdminCatalogCollection components;
components = (COMAdminCatalogCollection)
components = (COMAdminCatalogCollection)applications.GetCollection ("Components", Application.Key);
components.Populate();

foreach (COMAdminCatalogObject component in components)
{
Console.WriteLine("Component: " + component.Name);
}
}

The above code shows you how to get a list of COM+ applications and their components, but what about retrieving or setting the values of specific component settings like the Constructor String of a component?

Here’s how:


// Set the value of a constructor string
component.set_Value("ConstructorString", "127.0.0.1");
// Get the value of a constructor string
component.get_Value("ConstructorString"));

That’s a quick overview, I leave it as an exercise to the reader to explore the other functionality of the ‘COMAdmin’ library, but if you just need to retrieve values of settings from specific components, the above will get you started.

As per normal, MSDN has some great documentation here.

LINQ to XML – What I’ve been missing

Ok. You may laugh. I’ve just today used LINQ for the first time to parse an XML file, and I’m seriously blown away at how easy it was. I’m a little embarrassed, since LINQ has been available since .NET 3.5 was released around November 2007.

If you are like I was, (LINQ-less!!), I’ll give a brief introduction here. LINQ (Language INtegrated Query), is a component that adds native data querying capabilities to .NET languages. It can be used to read, parse and write XML files (and also SQL, which I may cover in a future post). Take a look at the example below to see how easy it is to use this technique to read data from an XML file.

Reading data from an XML file is a very common scenario. I always used .ini file as configuration files for any applications I wrote, but .NET doesn’t provide any built in support for .ini, and hence wants you to use XML.

Consider the following XML file:

In order to read this using LINQ to XML, you need to ensure you have specifed the correct header files:


using System.Linq;
using System.Xml.Linq;

Now for the easy part, here’s the code to read data from the XML file, and print out the values to the console:


XDocument xmlDoc = XDocument.Load(@"example.xml");
var servers = from server in xmlDoc.Descendants("server")
select new
{
     Name = server.Element("name").Value,
     IP = server.Element("ip").Value,
     Owner = server.Element("owner").Value,
};


foreach (var server in servers)
{
     Console.WriteLine("Server Name: " + server.Name);
     Console.WriteLine("Server IP: " + server.IP);
     Console.WriteLine("Server Owner: " + server.Owner);
}

Easy huh? The line beginning with ‘var servers=…‘ may look strange to you if you’ve never seen it before, (it did to me). This is an anonymous type declaration. If you’ve never heard of anonymous types in C#, MSDN has some great documentation here.

Happy coding.