The AsyncOperationService and HttpWebRequest

In the previous post I droned on about how to apply the AsyncOperationService to an API conforming to the .NET Asynchronous pattern.  In this post I’ll be building a more real world example.  Well I say “real world” please don’t confuse that with something actually useful.  Its still a little contrived and is not an example of best practice but it is something you could actually build and test.

What are we going to build?

We are going to build an ambitious ground breaking Silverlight app that allows the user to enter part of a Stackoverflow user name and then searches for users based on the text entered.  Ok then <interlocks fingers, stretches arms forward palms facing out, knuckles crack> lets get started.

Create a new Silverlight Application in VS2010 and accept all the defaults so we have a host web application in the solution as well. 

The Contrived SearchUsers handler.

First we need to create in the web application a new “Generic Handler” item called “SearchUsers” (a file of type .ashx) that is going to access the Stackoverflow api on behalf of the Silverlight app.  The standard Stackoverflow API uses a “GET” request placing query parameters in the query string then returns results as JSON with gzip encoding.  Our “proxy” handler is going to instead accept a “POST” containing JSON and will return the inflated JSON response.   I did say it was a little contrived right?  Here is its code.

SearchUsers
    public class SearchUsers : IHttpHandler
    {
        public class Search { public string Filter { get; set; } }

        public void ProcessRequest(HttpContext context)
        {
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Search));
            Search search = (Search)ser.ReadObject(context.Request.InputStream);

            context.Response.ContentType = "application/json";
            context.Response.Charset = "utf-8";

            WebClient client = new WebClient();
            using (var result = client.OpenRead("http://api.stackoverflow.com/1.1/users?filter=" + Uri.EscapeDataString(search.Filter)))
            using (var inflated = new GZipStream(result, CompressionMode.Decompress))
            {
                inflated.CopyTo(context.Response.OutputStream);
            }
        }

        public bool IsReusable { get { return false; } }
    }

 

Lets just get the UI and other bits and pieces out of the way

The project is going to need the code for the core AsynchronousOperationService and the FromAsyncPattern method from previous blog articles.  You’ll note that I use a partial class so I don’t have to come up with a new class name to extend the service features.  Place the code from these code blocks in separate files or merge them together into one.

For the UI we just need a TextBox to enter the filter text, a “GO” button and ListBox to display the results.  Paste over the LayoutRoot of the MainPage.xaml with the folllowing code.

LayoutRoot of MainPage.xaml
    <Grid x:Name="LayoutRoot" Background="White">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="Auto" />
            </Grid.ColumnDefinitions>
            <TextBox x:Name="txtSearch" />
            <Button x:Name="btnSearch" Content="Go" Grid.Column="1" Click="btnSearch_Click" />
        </Grid>
        <ListBox x:Name="lstResults" Grid.Row="1" />
    </Grid>

 

The now obligatory imaginary bit

So now we want to write a method on the client which posts some JSON to the server containing filter text taken from the txtSearch text box and having received the JSON response display the results in the list box.  We are going to use HttpWebRequest to do that.  In WPF we could write all this code synchronously and it would look like the following (note: even though it is possible in WPF it still isn’t a good idea).

GetSearchResults Synchronous
        private List<string> GetSearchResults(string filter)
        {
            WebRequest req = WebRequest.Create(new Uri(Application.Current.Host.Source, "/SearchUsers.ashx"));
            req.Method = "POST";

            Stream reqStream = req.GetRequestStream();

            using (reqStream)
            {
                WriteFilterToStream(filter, reqStream);
            }

            WebResponse response = req.GetResponse();

            return GetUserNamesFromWebResponse(response);
        }

        void WriteFilterToStream(string filter, Stream stream)
        {
            JsonObject search = new JsonObject();
            search["Filter"] = filter;
            search.Save(stream);
        }

        List<string> GetUserNamesFromWebResponse(WebResponse response)
        {
            using (var stream = response.GetResponseStream())
            {
                JsonObject results = (JsonObject)JsonObject.Load(stream);
                return ((JsonArray)results["users"])
                    .Cast<JsonObject>()
                    .Select(jo => (string)jo["display_name"]).ToList();
            }
        }

 

Just paste the above code into MainPage.xaml.cs. Now before the MVVM police come and duff me up, let me just state I’m putting this code there for brevity, in real world code you would not be placing code like this in code-behind (actually I might if it suited me, I can be a bit of a non-conformist).

Of course this doesn’t work.  Visual Studio places redlines under GetRequestStream and GetResponse because WebRequest in Silverlight doesn’t have these methods.  In Silverlight we only have the asynchronous pattern to work with BeginGetRequestStream/EndGetRequestStream and BeginGetResponse/EndGetResponse.  We need to convert GetSearchResults into a method that can be run by AsyncOperationService and use the FromAsynPattern method to create AsyncOperation instances from these pairs of methods.

Creating WebRequestExtensions

Before transforming the GetSearchResults method we will introduce an extensions class for the WebRequest that wraps up the use of FromAsyncPattern.  This will help with code readability.   Add a new class to the project called WebRequestExtensions.cs and place the following code in it.

WebRequestExtensions.cs
using System;
using System.Net;
using CodingBloke.AsyncOperations;
using System.IO;

namespace CodingBloke.AsyncOperations
{
    public static class WebRequestExtensions
    {
        public static AsyncOperation GetRequestStreamAsyncOp(this WebRequest request, Action<Stream> returnResult)
        {
            return AsyncOperationService.FromAsyncPattern(request.BeginGetRequestStream, ar => returnResult(request.EndGetRequestStream(ar)));
        }

        public static AsyncOperation GetResponseAsyncOp(this WebRequest request, Action<WebResponse> returnResult)
        {
            return AsyncOperationService.FromAsyncPattern(request.BeginGetResponse, ar => returnResult(request.EndGetResponse(ar)));
        }
    }
}

 

Now replace the GetSearchResults method with the follow transformed version and include in the MainPage.xaml.cs a using for CodingBloke.AsyncOperations.

GetSearchResults Asynchronous
        private IEnumerable<AsyncOperation> GetSearchResults(string filter, Action<List<string>> returnResult)
        {
            WebRequest req = WebRequest.Create(new Uri(Application.Current.Host.Source, "/SearchUsers.ashx"));
            req.Method = "POST";

            Stream reqStream = null;
            yield return req.GetRequestStreamAsyncOp(r => reqStream = r);

            using (reqStream)
            {
                WriteFilterToStream(filter, reqStream);
            }

            WebResponse response = null;
            yield return req.GetResponseAsyncOp(r => response = r);

            List<string> result = GetUserNamesFromWebResponse(response);

            returnResult(result);
        }

This code satisfies my goal of having the asynchronous code looking very similar to the synchronous version.  Functions that originally retuned a value now simply call a lambda to provide the return value.  Other than that this code is identical to the synchronous version.

Finally wire up the button

To complete the code that “should” (assuming I’ve explained every thing well enough) make this code executable and operational place this final snippet in the MainPage.xaml.cs.

        private void btnSearch_Click(object sender, RoutedEventArgs e)
        {
            List<string> result = null;
            GetSearchResults(txtSearch.Text, r => result = r).Run((err) =>
            {
                if (err == null)
                {
                    lstResults.ItemsSource = result;
                }
                else
                {
                    MessageBox.Show("Oops something bad happened");
                }
            });
        }

 

This final snippet exemplifies another of my goals for AsyncOperationService.  The error handling story is robust.  Normally in production quality code you would have to ensure that all your callback/event methods catch and do appropriate things with any exception.  You would then need to communicate with anything else waiting for a callback that what was expected to happen hasn’t due to an error.

Whilst AsyncOperationService doesn’t eliminate all of that burden (if you peek back to the previous article you can see that FromAsyncPattern catches all errors) the pattern allows the sequence to be terminated and error be reported to a single high level point.  The code that actually does things we are interested in (the GetSearchResults in this case) still looks quite simplistic as if it needs further error handling yet it doesn’t, it is complete.

What’s next?

In my next article on the AsyncOperationService I’m going to apply similar techniques to making WCF calls.

Using AsyncOperationService with the .NET Asynchronous Pattern

This post is about using the AsyncOperationService with .NET Asynchronous PatternWarning: this is another article that is likely to give you a headache.  Its designed to provide full details of how things work.  If you don’t want the headache then, skim the article and copy’n’paste the code from the “FromAsyncPattern” box below (it assumes you already have AsyncOperationService code).  Subsequent articles will outline more real world uses which may (and I say “may” very tentatively) not be so headache inducing.

Concepts Recap

The objective of the AsyncOperationService is to allow developers to write code that appears to be synchronous even though it is in fact asynchronous. It does this by utilising the C# yield statement to convert what in pseudo-code is a synchronous sequence in to a list of AsyncOperation delegates that are then processed one after another by the AsyncOperationService.

What do we need?

We need to be able to take the Begin/End pair of methods that make up an asynchronous API feature and convert them into an AsyncOperation.  This is done by adding the following class to your project (assumes you already have the AsyncOperationService in the project).

FromAsyncPattern
using System;

namespace CodingBloke.AsyncOperations
{
    public static partial class AsyncOperationService
    {
        public static AsyncOperation FromAsyncPattern(Func<AsyncCallback, object, IAsyncResult> beginOp, Action<IAsyncResult> endOp)
        {
            return (completed) =>
            {
                AsyncCallback cb = (ar) =>
                {
                    try
                    {
                        endOp(ar);
                        completed(null);
                    }
                    catch (Exception err)
                    {
                        completed(err);
                    }
                };

                beginOp(cb, null);
            };
        }
        
        public static AsyncOperation FromAsyncPattern(Func<AsyncCallback, IAsyncResult> beginOp, Action<IAsyncResult> endOp)
        {
            return FromAsyncPattern((cb, o) => beginOp(cb), endOp);
        }
    }
}

 

If you’ve had a look a Microsoft’s Reactive Framework you may recognise this approach.  It takes two delegate parameters, one to begin the operation and another for the end of the operation.  The delegates have the most basic signature possible, one that matches an operation that takes no parameters and returns no value.  When AsyncOperation is execute the begin operation delegate is called and the callback it is provided with will invoke the end operation.  The call to the completed delegate is part of the AsyncOperationService plumbing to indicate that the next step can be taken.

How do we use it?

Lets just invent some nonsense .NET Asynchronous pattern interface.  It has two operations, a GetStringList which (surprisingly) returns a list of strings and a ProcessString which takes an input string and processes it in some unspecified way.   Using the .NET Asynchronous pattern the interface breaks both these operations into a Begin/End pair and ends up looking as follows.

Some Imaginary Interface
    public interface IMadeThisUp
    {
        IAsyncResult BeginGetStringList(AsyncCallback callback, object State);
        List<string> EndGetStringList(IAsyncResult asyncResult);

        IAsyncResult BeginProcessString(string input, AsyncCallback callback, object State);
        void EndProcessString(IAsyncResult asyncResult);
    }

 

Lets imagine that we need to retrieve a list of strings then process each of the strings in turn.  Yes I know its not the most realistic scenario but I’m trying to stick with the concepts for the moment.  In keeping with my methodology of writing a synchronous procedure first this is what such routine might look like if the interface contained the synchronous GetStringList and ProcessString methods.

Psuedo Synchronous Code
        public void GetAndProcessStrings()
        {
            IMadeThisUp processor = new SomeImplementor();

            List<string> valueList = processor.GetStringList();

            foreach (string value in valueList)
            {
                processor.ProcessString(value);
            }
        }

 

The above code is really straightforward, its very easy to look at that code reason out what its doing.  It would be nice if the real asynchronous version could look so straightforward.  Well it can’t but I think we can get close.  This what the asynchronous version looks like.

The Actual Asynchronous Code
        public IEnumerable<AsyncOperation> GetAndProcessStrings()
        {
            IMadeThisUp processor = new SomeImplementor();

            List<string> valueList = null;
            yield return AsyncOperationService.FromAsyncPattern(processor.BeginGetStringList, ar => valueList = processor.EndGetStringList(ar));

            foreach (string value in valueList)
            {
                yield return AsyncOperationService.FromAsyncPattern(cb => processor.BeginProcessString(value, cb, null), processor.EndProcessString);
            }
        }

 

If you are skimming to avoid headache just read this first paragraph

Fundamentally to go from “synchronous” to asynchronous code the function now returns an IEnumerable<AsyncOperation> that the AsyncOperationService can run.  At the points in the code where we need to change from the imaginary synchronous methods to using the Begin/End asynchronous pairs we are now yielding an AsyncOperation with the help of the FromAsyncPattern method.  Now here is the crucial aspect, even if a developer reading the above code had no idea how the AsyncOperationService works he or she would still be able to discern the intent of the code.  This is far cry from other asynchronous approaches which are almost entirely opaque until you grasp the asynch mechanisms involved.  This is especially true when loops are involved.

For the first operation, the GetStringList, the operation does not take any parameters, hence when calling FromAsyncPattern we can pass the BeginGetStringList directly to it since it conforms the most basic signature.  However since EndGetStringList returns a value it does not conform to the most basic signature.  Hence we pass in a lambda which does conform and which in turn calls the EndGetStringList assigning the returned value to the valueList variable.  Note valueList is assigned null initially, this is required by the C# compiler else it complains about the use of an unassigned variable.

If you are following this series of articles you will note this common pattern.  Where an ideal synchronous method would return a value (of type T) the asynchronous operation version must return an AsyncOperation instead so to compensate the final parameter passed to this asynchronous function will be an Action<T>.  It will be common to see a tight lambda of the form  r => resultVariable = r  passed to this parameter.  Any further processing of the returned value would then simply be placed following the call (and yield of) the asynchronous function just as it would have in synchronous code.

For the second operation, the ProcessString, the operation takes an additional String parameter and thus BeginProcessString does not conform to the most basic signature.  So in this case a lambda is passed to the FromAsyncPattern function’s first parameter.  It takes the standard AsyncCallback (cb) parameter and passes it in to the BeginProcessString along with the string value to be processed.  The EndProcessString method does conform to the most basic signature since it doesn’t return anything so in this case we can just pass it directly as the second parameter.

You might note that I’m not making any use of the “State” object that the .NET Asynchronous pattern places as the final parameter in the Begin methods which then appear as a property of the IAsyncResult.  In effect its the set of variables in the procedure which now form the “State”.  Whereas before we might pass an object instance around via the “State” object and at times we would even need to create a class to hold a set of properties needed from one call to the next.  All that is unnecessary when using AsyncOperationService, C# gives us all that for free via the yield statement and lambdas.

How is it called?

Very simply.

            GetAndProcessStrings().Run(err =>
            {
                if (err != null)
                {
                    // Final chance to deal with something bad that happened.
                }
            });

 

What’s next?

Ok so that was all very conceptual but how is it used in the real world?  In my next articles I’ll go into such uses starting with using the .NET Asynchronous Pattern API exposed be HttpWebRequest.

Simple Asynchronous Operation Runner – Revisited

Its been quite some time since I last post on the subject of the AsyncOperationService (in fact quite some since I posted period).

In real world use I found some common patterns emerge that has lead me to make a few small adjustments to eliminate some common duplication I was seeing in code consuming the service.  Here is the new code file for my ever so slightly improved AsyncOperationService in its entirety.

 

AsyncOperationService
using System;
using System.Windows;
using System.Collections.Generic;

namespace CodingBloke.AsyncOperations
{
    public delegate void AsyncOperation(Action<Exception> completed);

    public static partial class AsyncOperationService
    {
        public static void Run(this IEnumerable<AsyncOperation> asyncOps, Action<Exception> completed)
        {
            IEnumerator<AsyncOperation> enumerator = asyncOps.GetEnumerator();

            Action<Exception> disposeAndComplete = (exception) =>
            {
                enumerator.Dispose();
                Deployment.Current.Dispatcher.BeginInvoke(() => completed(exception));
            };

            Action executeNextOp = null;
            executeNextOp = () =>
            {
                bool asyncCallbackExecuted = false;
                bool sequenceIncomplete = true;

                try
                {
                    sequenceIncomplete = enumerator.MoveNext();
                    if (sequenceIncomplete)
                    {
                        enumerator.Current((asyncError) =>
                        {
                            if (!asyncCallbackExecuted)
                            {
                                asyncCallbackExecuted = true;

                                if (asyncError == null)
                                    executeNextOp();
                                else
                                    disposeAndComplete(asyncError);
                            }
                        });
                    }
                }
                catch (Exception syncError)
                {
                    disposeAndComplete(syncError);
                }

                if (!sequenceIncomplete)
                    disposeAndComplete(null);

            };
            executeNextOp();
        }

        public static AsyncOperation SwitchToUIThread()
        {
            return completed => Deployment.Current.Dispatcher.BeginInvoke(() => completed(null));
        }

        public static AsyncOperation SwitchToBackgroundThread()
        {
            return completed => System.Threading.ThreadPool.QueueUserWorkItem(o => completed(null));
        }

    }

}

 

Callback from Run method now executes on the UI Thread

One pattern I noticed was that in the delegate provided for the Run callback there was always some code to switch to the UI Thread. It seemed to me that it would be useful if the Run callback was always guaranteed to run on the UI thread thereby eliminating this duplication.

SwitchToUIThread Method

Sections of code executing within the main sequence (the function yielding AsyncOperations) will run in whatever thread the yielded operation called its completed delegate on.  As a result when code in the main sequence needed to modify UI elements it would often include an ugly one-liner to yield a AsyncOperation delegate that would switch code execution on to the UI Thread.  I thought encapsulating the one liner into static method on the service class would be useful, hence SwitchToUIThread was added.

SwitchToBackgroundThread Method

At least for sake of symmetry I thought it would also be good add a SwitchToBackgroundThread which would take the code execution off the current thread and into a background thread.  This would be handy when using some async components that always  complete on the UI Thread. In some cases there may still be some considerable processing to do before UI components need meddling with.  The SwitchToBackgroundThread allows the main sequence to jump out of the UI Thread.

 

Daft Demo

By way of a really silly demonstration do the following:

  • Create yourself an fresh new Silverlight Application project in Visual Studio
  • Add a code file called “AsyncOperationService” to the project and paste the above code into it
  • To the MainPage.xaml add a single ListBox and give it the x:Name “lstResults”
  • Now past the code below into MainPage.xaml.cs
MainPage.xaml.cs
using System.Collections.Generic;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using CodingBloke.AsyncOperations;

namespace SilverlightApplication1
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
            Loaded += MainPage_Loaded;
        }

        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            ExecuteDaftOperations();
        }

        string CurrentThreadID { get { return Thread.CurrentThread.ManagedThreadId.ToString(); } }

        IEnumerable<AsyncOperation> DaftOperations(List<string> result)
        {
            result.Add("Starting on thread: " + CurrentThreadID);

            yield return AsyncOperationService.SwitchToBackgroundThread();
            result.Add("Switched to background thread: " + CurrentThreadID);

            yield return AsyncOperationService.SwitchToUIThread();
            result.Add("Switched back to UI thread: " + CurrentThreadID);

            yield return AsyncOperationService.SwitchToBackgroundThread();
            result.Add("Switched back to background thread: " + CurrentThreadID);

            yield return AsyncOperationService.SwitchToBackgroundThread();
            result.Add("Switching from one background thread to another: " + CurrentThreadID);
        }

        void ExecuteDaftOperations()
        {
            var result = new List<string>();

            DaftOperations(result).Run(err =>
            {
                if (err == null)
                {
                    result.Add("Completed on thread: " + CurrentThreadID);
                    lstResults.ItemsSource = result;
                }
                else
                {
                    MessageBox.Show("Oops something bad happened");
                }
            });

        }
    }
}

 

When you run this app a few times you’ll notice that execution always starts and ends on Thread 1 (the UI thread) whereas the background thread chosen may vary.

You might wonder why we would ever want to switch to a background thread when we know we are already on a background thread.  Well in some cases code may be executing as a result of some callback or event that represents the completion of an expensive task.  This expensive task may well have significant resources allocated and is waiting for its callback or event to return before releasing them.  Yielding a SwitchToBackgroundThread allows the outstanding callback or event to return and the existing callstack to wind all the way back, thus releasing potentially significant resources.  In fact for that matter the same may also be true of SwitchToUIThread.

Visual Tree Enumeration

I feel compelled to post this blog because I find I’m repeatedly posting this same code in silverlight and windows-phone-7 answers in Stackoverflow.

One common task that we feel we need to do is burrow into the visual tree in a Silverlight or Windows Phone 7 application (actually more recently I found myself doing this in WPF as well).  This allows access to details that aren’t exposed directly by some controls.  A good example of this sort of requirement is found in the “Restoring exact scroll position of a listbox in Windows Phone 7”  question on stackoverflow.  This required that the scroll position of the scroll viewer internal to a listbox be accessed.

A caveat

One caveat here is that we should seriously challenge the need for this burrowing since it may indicate that there is a design problem.  Burrowing into the visual tree or indeed burrowing out to containing ancestors could represent significant coupling between module boundaries and that generally isn’t a good idea.

Why isn’t this idea just not cast aside as a no-no?  Well the whole concept of a “Templated Control”, which are in extensive use in these applications, opens the coupling between the content of the visual tree and the internal code of a control.   For example, I can completely change the appearance and positioning of elements that make up a ComboBox.  The ComboBox control relies on specific template parts having set names of a specified type being present in my template.  Rightly or wrongly this does kind of give license to writing code that has similar coupling.

Hasn’t this been done already?

Yes it has.  There are number of blogs already out there with similar solutions.  In fact if you are using Silverlight toolkit the VisualTreeExtensions class already provides this feature.  However I prefer my specific code because of the simplicity principle I hold to.  Only write the minimum code necessary to give all the features needed.  In this case I add just two extension methods Ancestors and Descendents, note I don’t bother with “Get” or “Visual” prefixes.  Also I haven’t added Parent or Children methods nor additional “AndSelf” methods because all but Children is achievable with the addition of some other Linq methods.  I decided to give Descendents an additional overload for depth hence a depth of 1 is equivalent to Children but this overload is a little more flexible than simply Children.

So here is the code:-

VisualTreeEnumeration
public static class VisualTreeEnumeration
{
    public static IEnumerable<DependencyObject> Descendents(this DependencyObject root, int depth)
    {
        int count = VisualTreeHelper.GetChildrenCount(root);
        for (int i = 0; i < count; i++)
        {
            var child = VisualTreeHelper.GetChild(root, i);
            yield return child;
            if (depth > 0)
            {
                foreach (var descendent in Descendents(child, --depth))
                    yield return descendent;
            }
        }
    }

    public static IEnumerable<DependencyObject> Descendents(this DependencyObject root)
    {
        return Descendents(root, Int32.MaxValue);
    }

    public static IEnumerable<DependencyObject> Ancestors(this DependencyObject root)
    {
        DependencyObject current = VisualTreeHelper.GetParent(root);
        while (current != null)
        {
            yield return current;
            current = VisualTreeHelper.GetParent(current);
        }
    }
}

 

Usage examples

The following are some examples of how to combine the above extension methods with Linq to generate the other axis scenarios that tree traversal code might require.

 

Missing Axis Scenarios
var parent = control.Ancestors().Take(1).FirstOrDefault();

var children = control.Descendents(1);

var previousSiblings = control.Ancestors().Take(1)
    .SelectMany(p => p.Descendents(1).TakeWhile(c => c != control));

var followingSiblings = control.Ancestors().Take(1)
    .SelectMany(p => p.Descendents(1).SkipWhile(c => c != control).Skip(1));

var ancestorsAndSelf = Enumerable.Repeat((DependencyObject)control, 1)
    .Concat(control.Ancestors());

var descendentsAndSelf = Enumerable.Repeat((DependencyObject)control, 1)
    .Concat(control.Descendents());

 

You might ask why I don’t just include these in the VisualTreeEnumerator.  I don’t on the principle of only including code that is actually needed.  If you find that one or more of the above  is needed in your code then go ahead and create additional methods.  One of the downsides to Extension methods is that they can make finding the method you actually want in intellisense harder.

Here are some real world usage scenarios for these methods:-

Real World Scenarios
//Gets the internal scrollviewer of a ListBox
ScrollViewer sv = someListBox.Descendents().OfType<ScrollViewer>().FirstOrDefault();

// Get all text boxes in current UserControl:-
var textBoxes = this.Descendents().OfType<TextBox>();

// All UIElement direct children of the layout root grid:-
var topLevelElements = LayoutRoot.Descendents(0).OfType<UIElement>();

// Find the containing `ListBoxItem` for a UIElement:-
var container = elem.Ancestors().OfType<ListBoxItem>().FirstOrDefault();

// Seek a button with the name "PinkElephants" even if outside of the current Namescope:-
var pinkElephantsButton = this.Descendents()
    .OfType<Button>()
    .FirstOrDefault(b => b.Name == "PinkElephants");

//Clear all checkboxes with the name "Selector" in a Treeview
foreach (CheckBox checkBox in elem.Descendents()
    .OfType<CheckBox>().Where(c => c.Name == "Selector"))
{
    checkBox.IsChecked = false;
}

 

The last couple of examples above demonstrate a common requirement of finding controls that have a specific name.  FindName will often not find these controls because they exist in a different namescope.

Hope you find this useful, if not I’m just glad to be able to link to this blog in future stackoverflow answers.

Simple Asynchronous Operation Runner – Part 2

In Part 1 I provided the code for the simple asynchronous operation runner.  In this post I’ll put it to some use.

First let me provide a real world scenario so that we have something to demonstrate with.

The Scenario

  • I have a desire to separate into resource dictionaries a common palette of colours from a set of styles that use these colours.  The goal being that I change a pair of colours in one place and all parts of the UI using that pair will use the new colour.
  • There may be multiple resource dictionaries holding styles that reference these colours or even a style that may be BasedOn a style in another dictionary.  I want to put these dictionaries outside of the Xap so that on deployment on a client site these files can be easily edited.
  • I want to allow the client add and remove dictionaries from the set and all this without any necessity for script support server-side.

The Challenges

The scenario presents a few challenges.  I need to download some sort of manifest for the set of dictionary files I need.  Then each dictionary needs to be downloaded and added to the application resources before the next dictionary because subsequent dictionaries may depend on foregoing dictionaries.   This is clearly a synchronous sequence where each step must be completed before the next.   The obvious tool to download these files is WebClient.  Imagine for the moment that WebClient had a synchronous DownloadString method.  The code to complete the scenario could look something like this:-

 

 

Imaginary Code
private void LoadExternalResourcesSync()
{
    WebClient wc = new WebClient();

    string manifestXml = wc.DownloadString(new Uri("External/ResourceManifest.xml", UriKind.Relative));

    XDocument manifest = XDocument.Parse(manifestXml);

    foreach (XElement resourceElem in manifest.Descendants("resource"))
    {
        Uri resourceUri = new Uri(resourceElem.Attribute("source").Value, UriKind.Relative);
        string resourceXaml = wc.DownloadString(resourceUri);

        var resource = XamlReader.Load(resourceXaml) as ResourceDictionary;
        Resources.MergedDictionaries.Add(resource);
    }
}

This looks like a fairly straight forward chunk of code that implements the sequence outlined above.  Sadly there is no such DownloadString method.  We only have DownloadStringAsync and converting the above code to achieve the same result gets real ugly real quick, so much so that I daren’t even present what the code would look like.

The design goal I had in mind for the Asynchronous Operation Runner was to be able to write code that looks likes it is synchronous (therefore not a million miles away from the code above) but would actually work asynchronously.

First order of business then looking at the code above is create an AsyncOperation that performs a DownloadString.  There is no magic here, I can’t actually create a synchronous DownloadString, it will still need a call back on completion but the goal is to approach the appearance of synchronous code.  Here is the implementation:-

 

DownloadString
private static AsyncOperation DownloadString(Uri source, Action<String> returnResult)
{
    return (completed) =>
    {
        WebClient client = new WebClient();
        client.DownloadStringCompleted += (s, args) =>
        {
            try
            {
                returnResult(args.Result);
                completed(null);
            }
            catch (Exception err)
            {
                completed(err);
            }
        };
        client.DownloadStringAsync(source);
    };
}

 

The above function doesn’t actually do anything when called, it just returns a delegate matching the AsyncOperation signature.   When the returned operation is eventually invoked by the AsyncOperationService it will download a string from the Uri provided then, when downloaded string becomes available, pass it to the returnResult call back.   Now how does this help “approach the appearance of synchronous code” ?  Compare the following real code with the imaginary block of code above:-

 

Real Code
private IEnumerable<AsyncOperation> LoadExternalResources()
{
    XDocument manifest = null;

    yield return DownloadString(new Uri("External/ResourceManifest.xml", UriKind.Relative),
        manifestXml => manifest = XDocument.Parse(manifestXml) );

    foreach (XElement resourceElem in manifest.Descendants("resource"))
    {
        Uri resourceUri = new Uri(resourceElem.Attribute("source").Value, UriKind.Relative);
        yield return DownloadString(resourceUri, resourceXaml =>
        {
            var resource = XamlReader.Load(resourceXaml) as ResourceDictionary;
            Resources.MergedDictionaries.Add(resource);
        });
    }
}

   

 

 

 

A quick scan of this real code shows that it doesn’t differ much from the original imaginary synchronous code.  The fundamental flow of downloading a manifest then iterating over its content downloading the various dictionaries is identical to the original.  On closer inspection we see that the calls to an imaginary DownloadString have been replaced with calls to the actual DownloadString method declared above.  The returned AsynchOperation delegates are yielded and the result string is handled by a lambda passed to the returnResult callback.

 

yield return

The “enabler” in all of this is the C# yield return construct.  If you are not familiar with it may I suggest you first read the documentation here.  When a yield return is found in a method then its return type is expected to be an IEnumerable<T> where T is the type of the expression in the return.

Its useful to know that none of the code in such a method will execute until the first call to MoveNext on an enumerator created from it is made.  Code will then run in the method normally until a yield is reached at which time that call to MoveNext completes, the execution of the method effectively pauses, its state is maintained (I won’t go into how that is well covered elsewhere).  Only when another call to MoveNext is made does code in the method continue from the point of the last yield.  This call can happen much later, possibly from another thread.

In this specific case I am “pausing” the method’s execution each time an asynchronous operation is needed and yield an instance of AsyncOperation that implements that operation.  This just leaves the AsyncOperationService with the task of running the method by iterating over this yielded set of AsyncOperations, the service calls MoveNext to move the code forward.  It only calls MoveNext when the current AsyncOperation has been executed and completed.

In part 1 I indicated that it would be important to handle errors generated when calling MoveNext.  When iterating a set of items provided via yield return the MoveNext represents much more than a trivial “increment to the next item”, instead some significant code can be run.

Also in part 1 I emphasised the need for the AsyncOperationService to properly dispose of the IEnumerator<AsyncOperation> that it is iterating over.  When yield return is used within a using block or a try..finally block then code execution can escape the block.  If an exception were to occur it could leave these blocks of code in limbo without the finally code having executed.  Ensuring proper disposal causes this finally code to be executed thereby releasing anything the ought be disposed in a timely fashion.

 

What’s next?

If I ever get round to writing a Part 3 I’ll look at other common scenarios where a simple synchronous chunk of code can be “rotated” to use yield return and AsyncOperation.  For example sending and retrieving a stream via HttpWebRequest/HttpWebResponse can be somewhat ugly.  Also a sequence WCF calls may well benefit from this treatment too.  If you have any suggestions for scenarios, please post them in a comment.

Simple Asynchronous Operation Runner – Part 1

I’ve been meaning to create a blog about asynchronous operations in Silverlight for sometime.  Specifically how to create code that looks and behaves much like synchronous code that actually depends on asynchronous operations.   I’ve seen quite a number of questions on Stackoverflow where developers have discovered that in many cases Silverlight only supports performing tasks asynchronously.

There are number of solutions that others, more able than I, have blogged about along with excellent explanations of the problem.  I’ll assume the reader is already familiar with the problem itself.

It seemed to me that the existing solutions I’d seen added more infrastructure than is needed to solve the fundamental problem.  Also some of the example implementations did not deal with exceptions as robustly as I would have liked.  My goal then is to create only enough code to actually solve the problem and handle exceptions well.

I felt that it ought to be possible to define each asynchronous operation as a simple delegate.  Here is the delegate definition I came up with:-

    
    public delegate void Operation(Action<Exception> completed);

 

An asynchronous operation would simply call the completed Action once it has (believe it or not) completed, it would pass any exception as a parameter or null if the operation succeeded.   To execute a sequence of these should be quite easy, the following is a naive attempt at a sequential runner for these operations (N.B. Don’t use this code).

 

        public static void NaiveRunner(IEnumerable<Operation> asyncOps, Action<Exception> completed)
        {
            IEnumerator<Operation> enumerator = asyncOps.GetEnumerator();
            Action executeNextOp = null;
            executeNextOp = () =>
            {
                if (enumerator.MoveNext())
                {
                    enumerator.Current((err) =>
                    {
                        if (err != null)
                            completed(err);
                        else
                            executeNextOp();
                    });
                }
                else
                {
                    completed(null);
                }
            };
            executeNextOp();
        }

 

This code becomes quite straight forward if you can visualise the two nested lambdas. The outer lambda assigned to executeNextOp gets the next operation and executes it.  The inner lambda is passed as the completed parameter when the operation is called.  Hence when the operation completes this inner lambda is executed which will in turn call executeNextOp if there was no error.  This continues until all items have been iterated.

There are a lot of problems with this code, I only included it so that the bare bones of the solution can be seen.  Here are the problems:-

  • What if the “synchronous bit” of the operation throws an error?  Say for example the operation is using WebClient.OpenReadAsync with a duff Uri.  Currently the above code doesn’t handle that scenario.
  • What if the MoveNext throws an error?  In part 2 I’ll come back to why that is a distinct possibility so it needs to be addressed.
  • What if the operation attempts to call the completed callback more than once?  A mechanism to prevent a massive tear in the time-space continuum would need to be in place here.
  • My personal favourite, the enumerator requires disposal.  Its not uncommon for the object returned by GetEnumerator to require correct disposal, the technique I’ll show in part 2 will certainly create such an enumerator.  The foreach statement which is the normal consumer of IEnumerables handles this even in error conditions.  The code above would need modifying to handle disposal correctly too.
    Taking all that on board here is my complete AsyncOp class which I believe is all the infrastructure you need to sequentially execute asynchronous operations.

 

AsyncOperationService
    public delegate void AsyncOperation(Action<Exception> completed);

    public static class AsyncOperationService
    {
        public static void Run(this IEnumerable<AsyncOperation> asyncOps, Action<Exception> completed)
        {
            IEnumerator<AsyncOperation> enumerator = asyncOps.GetEnumerator();

            Action<Exception> disposeAndComplete = (exception) =>
            {
                enumerator.Dispose();
                completed(exception);
            };

            Action executeNextOp = null;
            executeNextOp = () =>
            {
                bool asyncCallbackExecuted = false;
                bool sequenceIncomplete = true;

                try
                {
                    sequenceIncomplete = enumerator.MoveNext();
                    if (sequenceIncomplete)
                    {
                        enumerator.Current((asyncError) =>
                        {
                            if (!asyncCallbackExecuted)
                            {
                                asyncCallbackExecuted = true;

                                if (asyncError == null)
                                    executeNextOp();
                                else
                                    disposeAndComplete(asyncError);
                            }
                        });
                    }
                }
                catch (Exception syncError)
                {
                    disposeAndComplete(syncError);
                }

                if (!sequenceIncomplete)
                    disposeAndComplete(null);

            };
            executeNextOp();
        }

    }

This code takes the original naive attempt and expands upon it to solve all the issues I bulleted above.  As far as I can tell this meets my original goal of having a complete solution with just enough code and no more.

In Part 2 I will explore its usage and the inevitable creation of utility functions what might otherwise have already come with a fully-fledge “frameworked” solution.

Yet another blog about IValueConverter

After my previous blog on a Generic Boolean Value Converter I thought I might as well blog up another IValueConverter implementation that I use.

The Generic Boolean Value Converter effectively converters an input which only has two possible values to one of two corresponding objects.  The next logical step would be to create a similar converter that can take an input which has multiple (but finite and discrete) values to one of multiple corresponding objects.  To put it more simply a Generic Enum Value Converter.

Now we already have a tool that can help us in this area, the ResourceDictionary.  A simple IValueConverter implementation around it would create a StringToObjectConverter like so:-

StringToObjectConverter
using System;
using System.Windows;
using System.Windows.Data;
using System.Linq;
using System.Windows.Markup;

namespace SilverlightApplication1
{
    [ContentProperty("Items")]
    public class StringToObjectConverter : IValueConverter
    {
        public ResourceDictionary Items { get; set; }
        public string DefaultKey { get; set; }
        
        public StringToObjectConverter()
        {
            DefaultKey = "__default__";
        }

        public virtual object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value != null && Items.Contains(value.ToString()))
                return Items[value.ToString()];
            else
                return Items[DefaultKey];
        }

        public virtual object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return Items.FirstOrDefault(kvp => value.Equals(kvp.Value)).Key;
        }
    }
}

There are some things to note here.  The bulk of managing the relationship between an object instance and the related string key is handled by the Items property being an ResourceDictionary.  Also there is a catch all “__default__” key value which allows for only a subset of the possible input values to mapped to an object with the rest falling through to the default.

We can then set one of these up in Xaml:-

            <local:StringToObjectConverter x:Key="StatusToBrush">
                <ResourceDictionary>
                    <SolidColorBrush Color="Red" x:Key="Overdue" />
                    <SolidColorBrush Color="Orange" x:Key="Urgent" />
                    <SolidColorBrush Color="Silver" x:Key="__default__" />
                </ResourceDictionary>
            </local:StringToObjectConverter>

You could well imagine that in the model being bound these key names would actually be members of an enum.  This still works due to the use of ToString in the Convert method.  Hence the only requirement for the incoming object is that it has a ToString implementation which generates a sensible string instead of simply the type name.

I can’t imagine right now a scenario where this converter would be used in a TwoWay binding but there is no reason why it can’t.  I prefer to avoid leaving the ConvertBack throwing an exception if that can be be avoided.  Hence it just enumerates the KeyValuePair entries to find a value that matches and returns the key its mapped to.

Ah but now my sense of balance is assaulted again.  Whilst StringToObjectConverter is quite happy to accept an enum type via the Convert method it returns a string from the ConvertBack method not the original input enum type that arrived in the Convert.  Now I could address this by complicating the ConvertBack method and examining the targetType parameter etc.  However I prefer to a different approach, deriving a new EnumToObjectConverter class instead.

EnumToObjectConverter
using System;

namespace SilverlightApplication1
{
    public class EnumToObjectConverter : StringToObjectConverter
    {
        public override object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            string key = Enum.GetName(value.GetType(), value);
            return base.Convert(key, targetType, parameter, culture);
        }

        public override object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            string key = (string)base.ConvertBack(value, typeof(String), parameter, culture);
            return Enum.Parse(targetType, key, false);
        }
    }
}

 

This is a more belts and braces solution with specific use of Enum.GetName and Enum.Parse.  Whilst its more explicit in that the a developer has to  choose to use it, it is only really necessary when using TwoWay binding, in OneWay binding the base StringToObjectConverter would serve just as well.

The observant might note that there is actually no “Generic” aspect to this solution in the end.  The use of a ResourceDictionary eliminates the need for that.

A Generic Boolean Value Converter

On fairly regular intervals a question on Stackoverflow like this one:  Silverlight Bind to inverse of boolean property value appears.  The same answers also regularly appear.  They all involve an implementation of IValueConverter and basically include the same boilerplate code.

The required output type sometimes varies, other examples that have passed by are Boolean to Brush and Boolean to String conversions.  Yet the code remains pretty much the same.  There is therefore a good case to create a generic Boolean to value converter to contain this common code and then just specialise it for use in Xaml. Here is the basic converter:-

BoolToValueConverter
using System;
using System.Windows.Data;

namespace SilverlightApplication1
{
    public class BoolToValueConverter<T> : IValueConverter
    {
        public T FalseValue { get; set; }
        public T TrueValue { get; set; }

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value == null)
                return FalseValue;
            else
                return (bool)value ? TrueValue : FalseValue;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return value != null ? value.Equals(TrueValue) : false;
        }
    }
}

With this generic converter in place it easy to create a set of converters for various types.  For example here are all the converters mentioned so far:-

Value Converters
using System;
using System.Windows;
using System.Windows.Media;

namespace SilverlightApplication1
{
    public class BoolToStringConverter : BoolToValueConverter<String> { }
    public class BoolToBrushConverter : BoolToValueConverter<Brush> { }
    public class BoolToVisibilityConverter : BoolToValueConverter<Visibility> { }
    public class BoolToObjectConverter : BoolToValueConverter<Object> { }
}

With the specialised converters created they can be specified in a Resources property on a user control like this:-

<local:BoolToBrushConverter x:Key="Highlighter" FalseValue="Transparent" TrueValue="Yellow" />
<local:BoolToStringConverter x:Key="CYesNo" FalseValue="No" TrueValue="Yes" />
<local:BoolToVisibilityConverter x:Key="InverseVisibility" TrueValue="Collapsed" FalseValue="Visible" />

Silverlight IConvertible TypeConverter

I recently answered the following question on stackoverflow: 

Silverlight 3 custom control: only ‘int’ as numeric type for a property? [e.g. long or int64 seems to break]


I quickly knocked up the class ConvertibleTypeConverter<T> that I posted in the question (listed later here as well). Afterward I fully expected to find that of the usual clever “bods who blog” to have covered this probably with a better solution than I.  So far though I’ve not found one so I thought I’d blog it myself.

The Problem

Here is a classic gotcha I’ve seen asked more than once on stackoverflow :-

public class MyClass
{
    public float SomeValue { get; set; }
}

<local:MyClass SomeValue="45.15" />

This fails with the error  “Failed to create a 'System.Single' from the text '45.15'”  and results in much premature hair loss.  Fortunately this is SL4, in SL3 the error message is almost meaningless.  So what gives, how can it be that this fails when we can see other very similar values parsing happily all over the place?

It comes down the fact that the Xaml parser only handles a few of the primitive data types namely: bool, int, string and double.  Since the parser has no idea how to convert a string to a float we get the above error.

The Solution

The sensible solution is “use double not float” but lets not dwell on that, there has to be occasions where such an answer isn’t acceptable.

In order to achieve parsing of other types we need an implementation of TypeConverter for the type of the property and then we need to use the TypeConverterAttribute to decorate the property .  As an example the Silverlight SDK provides one for DateTime the DateTimeTypeConverter (yes I know DateTime isn’t really a primitive). The following class will parse in Xaml:-

public class MyClass
{
    [TypeConverter(typeof(DateTimeTypeConverter))]
    public DateTime SomeValue {get; set; }
}

So far though we would need to create a TypeConverter for each primitive type we are using, what if I had the following mad class to support in Xaml:-

public class StrangePrimitives
{
    public Boolean BooleanProp { get; set; }

    public Byte ByteProp { get; set; }

    public Char CharProp { get; set; }

    public DateTime DateTimeProp { get; set; }

    public Decimal DecimalProp { get; set; }

    public Double DoubleProp { get; set; }

    public Int16 Int16Prop { get; set; }

    public Int32 Int32Prop { get; set; }

    public Int64 Int64Prop { get; set; }

    public SByte SByteProp { get; set; }

    public Single SingleProp { get; set; }

    public String StringProp { get; set; }

    public UInt16 UInt16Prop { get; set; }

    public UInt32 UInt32Prop { get; set; }

    public UInt64 UInt64Prop { get; set; }

}

Then I want to fill an instance of StrangePrimitives with the following Xaml which of course fails.

<local:StrangePrimitives x:Key="MyStrangePrimitives"
                         BooleanProp="True"
                         ByteProp="156"
                         CharProp="A"
                         DateTimeProp="06 Jun 2010"
                         DecimalProp="123.56"
                         DoubleProp="8372.937803"
                         Int16Prop="16532"
                         Int32Prop="73738248"
                         Int64Prop="12345678909298"
                         SByteProp="-123"
                         SingleProp="39.0"
                         StringProp="Hello, World!"
                         UInt16Prop="40000"
                         UInt32Prop="4294967295"
                         UInt64Prop="18446744073709551615"
     />

I got to thinking, though, one thing all these primitive types have in common is that they all implement IConvertible so it should be possible to write just one converter to handle them all.  Here it is:-

The ConvertibleTypeConverter
public class ConvertibleTypeConverter<T> : TypeConverter where T : IConvertible
{
    public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
    {
        return sourceType.GetInterface("IConvertible", false) != null;
    }

    public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
    {
        return destinationType.GetInterface("IConvertible", false) != null;
    }

    public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
    {
        return ((IConvertible)value).ToType(typeof(T), culture);
    }

    public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
    {
        return ((IConvertible)value).ToType(destinationType, culture);
    }
}

I won’t bore you with an explanation of how it works, it simply adapts one existing interface (the IConvertible) and exposes it as another (the TypeConverter).   With that in place the previous strange primitives class can be modified as:-

public class StrangePrimitives
{
    public Boolean BooleanProp { get; set; }

    [TypeConverter(typeof(ConvertibleTypeConverter<Byte>))]
    public Byte ByteProp { get; set; }

    [TypeConverter(typeof(ConvertibleTypeConverter<Char>))]
    public Char CharProp { get; set; }

    [TypeConverter(typeof(ConvertibleTypeConverter<DateTime>))]
    public DateTime DateTimeProp { get; set; }

    [TypeConverter(typeof(ConvertibleTypeConverter<Decimal>))]
    public Decimal DecimalProp { get; set; }

    public Double DoubleProp {get; set; }

    [TypeConverter(typeof(ConvertibleTypeConverter<Int16>))]
    public Int16 Int16Prop { get; set; }

    public Int32 Int32Prop { get; set; }

    [TypeConverter(typeof(ConvertibleTypeConverter<Int64>))]
    public Int64 Int64Prop { get; set; }

    [TypeConverter(typeof(ConvertibleTypeConverter<SByte>))]
    public SByte SByteProp { get; set; }

    [TypeConverter(typeof(ConvertibleTypeConverter<Single>))]
    public Single SingleProp { get; set; }

    public String StringProp { get; set; }

    [TypeConverter(typeof(ConvertibleTypeConverter<UInt16>))]
    public UInt16 UInt16Prop { get; set; }

    [TypeConverter(typeof(ConvertibleTypeConverter<UInt32>))]
    public UInt32 UInt32Prop { get; set; }

    [TypeConverter(typeof(ConvertibleTypeConverter<UInt64>))]
    public UInt64 UInt64Prop { get; set; }


}

This results in the previous Xaml parsing happily.  Now it seems such an obvious thing to do that one may wonder why such a class doesn’t already existing in Silverlight or at least in the SDK.   I would not be surprised if there were some very good reasons hence use the ConvertibleTypeConverter with caution.  It does seem to me to be a useful little class to have lying around in the toolbox for the odd occasion where it may be needed.

Hello, World!

I realise that the topic above is likely not the most original but that’s best I could come up with.  Apparently it is customary to use the first blog to introduce oneself so that’s what I’m doing here.

My name is Anthony Jones, I live in a town called Halesowen part of what is known as the Black Country in England.  I currently work for Union Square Software primarily with ASP.NET, C#, JavaScript and sometimes even Silverlight. 

I have been cutting code for the best part of 30 years (yes I do count the time I laboriously entered the machine code for Lunar Lander into a Kim 6502 trainer kit, aged 13).  My background is in Electronic Engineering however I did not attend university and only did college on a day release scheme as part of a 4 year apprenticeship, I maintain to this day that is was best career choice I ever made (of course one would need a time machine in order to prove that).

Solarton Instruments

I went straight from school at the age of 16 into an electronics apprenticeship  with what was then known as Solartron Instruments now called solartron analytical.  As an apprentice I got to do things that many developers never get the chance to do.  I worked on a project developing new silicon, I’m not talking PLAs or such things but from the ground up custom silicon.  Not that I claim to have really understood much of what to boffins there were doing but it was fascinating to be part of it.

As part of a competition with teams of other apprentices in other companies, I designed an embedded microcomputer system from discrete components.  It was an embarrassing disaster yet felt like a triumph.  In fact it makes a good anecdote to illustrate common programming folly today so I’ll leave it at that for now so that I can use it in a later blog.

I spent the last year and a half of my apprenticeship working on the 1253 Frequency Response Analyser writing 6809 assembler code.  Its extremely gratifying to see that this remains a product some 20 years later.

I then moved to the Automated Test Systems department where I was using Fortran, Basic and Assembler to develop a scripting language for putting various instruments through their paces.  Here I was exposed to VAX/VMS (David Cutler, the man behind VMS, went on to join Microsoft and Windows NT was born) and the joys of System Admin.

There were also these new-fangled PCs that needed wiring up to something called a Local Area Network.  Of course such things were not worthy of much attention by the DP department with their big iron IBM systems.  Hence muggins here spent a great deal of time up tall ladders that would give Heath & Safety a fit these days fitting chunky drop cables to equal chunky Ethernet coaxial.  I became completely by accident the company-wide unofficial PC support guy.

Why have concentrated so much in these first 6-7 years at Solartron?  Because they were very formative of what I am now and I’m very grateful of the opportunities my time there afforded me and what it has eventually lead me to.  But time moves on and so did I.

Being a system admin

Imagine working in an environment where most of the key line of business systems (Order Entry, Stock control, Dispatching, Sales analysis, Invoicing) are written in-house yet the developer responsible for those systems is also on the end of the phone when the any user wishes to report “a funny message on their screen”.   Let me tell you systems admin and software development do not mix.  Still I was young and enthusiastic and loved being that guy for awhile.  Also MS Access 2.0 rocked don’t let anyone tell you different.

Ok enough of this suffice to say, various other positions and 4GL, VB3-6, …., ASP, SQL Sever, JavaScript, HTML, XML, C#, ASP.NET, Silverlight later brings us to current (at time of writing that is).

Silverlight

Why have I highlighted Silverlight?  Because that is what I am most interested in working with.  I think it has potential for great things especially on the Windows Phone platform.  For that reason, at least initially many of my posts will be about Silverlight.

Right then, got that out of the way, I can get on with actually blogging what I intend to blog.

«May»
SunMonTueWedThuFriSat
293012345
6789101112
13141516171819
20212223242526
272829303112
3456789