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.

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.

Weekend Hacking – A Private Wiki

I decided to spend some time this weekend researching some of the solutions out there to the problem of all my fragmented notes, code snippets, interesting articles etc. I like to keep all this stuff handy in one place, usually in a folder on the desktop of my laptop.

This poses a few problems. Firstly, I’ve never been great to do backups, so I’m really relying on my laptop behaving and my hard disk not crashing. Secondly, I don’t always have that particular machine with me. I don’t know how many times I’ve had to revert back to Google to find something I know is in my notes somewere. The obvious solution to all of this, is to mantain a privately hosted Wiki.

To my surprise, there are not many solutions out there designed specifically for this purpose (that are free anyway). I initially had a look at TiddlyWiki. This is a Wiki like solution, but stores the entire application and all your information in a single HTML file. It looked great when I tried it out on my laptop – really easy to add and search information. But, as it wasn’t really designed to be a hosted solution, I had problems saving my edits once I deployed it to my web server, due to permissions issues etc. Also, as it’s using JavaScript, the security prompts from IE were getting quite annoying.

After some more searching to no avail, I decided to settle for MediaWiki. MediaWiki is the software on which Wikipedia runs, and was designed specifically for this purpose. I had used MediaWiki before, but didn’t consider it initially as I thought it may be a bit too advanced for the simple solution I required. How wrong I was! I installed it and was up and running in less than ten minutes, and it’s actually the perfect solution to my problem.

I’m now in the process of migrating all my notes etc. to this knowledge base, which I will be able to access from anywhere.

A good weekends work I think!

What to learn next?

I’ve been a bit all over the place recently in terms of what to learn next. The main languages I’m proficient in at the moment are C#, and web programming languages like PHP. (Aside: If I hear one more person refer to HTML as a programming language I may get angry). The thing about the software industry is that something you spend a long time mastering may be obsolete in 5 years. If you’re not continuously learning, you can fall behind very fast.

Over the next 6 months to 1 year, I’ve decided to focus on certain technologies/areas in an effort to become someway proficient in them.

I’ve decided on:

  • C++ – The expert consensus is that this will not be replaced in the next 50 years.
  • Mobile Development – But I’m unsure of which platform. iOS development interests me as I own an iPhone, but it has the extra added learning curve of Objective C, of which I have little experience. I’m thinking Android or Windows Phone 7 (should it be accepted by the masses), since I’m familiar with both Java and C#.
  • ‘Newer’ Microsoft technologies such as Silverlight, WPF etc. from the last few years that I haven’t looked at.

I feel if I apply myself I can certainly become proficient in the above areas in less than a year. By ‘proficient’ I mean be able to develop applications from the ground up as I can do in C# at the moment, not ‘master’. I’m fully aware that languages like C++ take thousands of hours to learn and many years of hands on experience to fully master.

No doubt I’ll be posting here of my experiences learning each.

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.

iPhone Application Development

I’m currently learning the application development process for the iPhone OS. A book that caught my eye recently while browsing Amazon was “Building iPhone Apps with HTML, CSS, and JavaScript: Making App Store Apps Without Objective-C or Cocoa” by Jonathan Stark. Since I don’t own a Mac currently, and don’t really feel I’d get any value from learning Objective-C, this sounded like the perfect place to start.

First off, I think the title is perhaps a little misleading. The author advocates building iPhone applications as web applications, rather than native iPhone OS applications. This has all the obvious advantages of any web application, (faster development cycles, real-time bug fixes etc.), but has a few unique advantages from the iPhone developers perspective. First off, you dont need to register (and pay!) to become an Apple developer. Secondly, your web application will not need to through Apple’s approval process as you will not need to submit it to the App Store in order to deploy it to your users.

Obviously, there are also some serious challenges to overcome if you make your application web based, with the main one being you will need to implement your own payment system if you wish to charge for your application.

The book contains many good tips for optimizing your web based application for the iPhone OS specifically. In Chapter 6, there’s also information on how to convert your web based application to a native iPhone app, using PhoneGap, although you do need a Mac to do this. Then your application will have to go through the Apple approval process in order to be made available on the App Store. It may be refused – but while you work on this and make any modifications necessary etc, your web based version is still available.

I’ve found this book a great starting point, now all I need to do is get the time to complete my app! I’ll be posting a release note here once I do, so stay tuned…