Category Archives: Thor Project

Ways to Interact Asynchronously with C#

NOTE: All of this code is available at my Github Project “Remembering” (https://github.com/Adron/Remembering). Feel free to fork it, share it, or send me corrections or pull requests.

While working on the Thor Project there have been numerous situations where I need to fire off an asynchronous callback in C# while maintaining good responsiveness in the actual user interface. Benjamin (@bvanderveen) has been using Reactive Extensions with subscriptions to do this in the Objective-C code for the Cocoa based OS-X Thor user interface. See my previous blog entry for an example of what he’s doing.

For a good example of asynchronous calls against Cloud Foundry I setup the following project using the Iron Foundry Project VCAP Client Library. The first thing I setup was a static class with a few constants to use across the examples for the URI, username and password for the Cloud Foundry Account.

public static class YourSecrets
{
    public const string Username = "youremail@someplace.com";
    public const string Password = "AnAwesom3HardPassw0rd!";
    public const string Uri = "http://api.yourpaas.com";
}

Next step was to setup the delegate and method I’d use for calling out to the Cloud Foundry environment and retrieving data in parallel to my active console or user interface. That code snippet looked like this. I also added a private variable _finished for use in tracking when the request was completed in the begin and end invoke example below.

private bool _finished;

IEnumerable TheMethodToConnectThatWillTakeLongTime(string uri)
{
    var client = new VcapClient(uri);
    client.Login(TheSecretBits.YourSecrets.Username, TheSecretBits.YourSecrets.Password);

    _finished = false;

    return client.GetApplications();
}

delegate IEnumerable MethodDelegate(string uri);

Once I had that setup I was ready to create my baseline method that would make a synchronous call. A synchronous call is one that makes the call as if it just called the method directly. There’s no real reason to create one like I’ve done here, but I was just using it to provide a basic example of calling the delegate.

public void SynchronousCall()
{
    var starting = DateTime.Now.ToLongTimeString();

    var delegateMethod = new MethodDelegate(TheMethodToConnectThatWillTakeLongTime);
    var returnedBits = delegateMethod(TheSecretBits.YourSecrets.Uri);

    var ending = DateTime.Now.ToLongTimeString();

    Console.WriteLine(string.Format("The delegate call returned \n\n{0}\n\nstarting at {1} and

ending at {2} which takes a while of waiting.",
        returnedBits, starting, ending));

    _finished = false;
}

That gets us a baseline. If you run a synchronous call against anything with a console application or a windows app, WPF or whatever it will lock up the calling thread while it is waiting for a response. In any type of user interface that is unacceptable. One of the best options is to fire of an asynchronous callback. The way I did this, which is an ideal way to make calls with the Iron Foundry Client Library against a Cloud Foundry Environment, is shown below.

This is my asynchronous call.

public void DemoCall()
{
    Console.WriteLine("Callback:");
    var delegateMethod = new MethodDelegate(TheMethodToConnectThatWillTakeLongTime);

    var callbackDelegate = new AsyncCallback(MyAsyncCallback);

    Console.WriteLine(" starting...{0}", DateTime.Now.ToLongTimeString());
    delegateMethod.BeginInvoke(TheSecretBits.YourSecrets.Uri, callbackDelegate, delegateMethod);
    Console.WriteLine(" ending...{0}", DateTime.Now.ToLongTimeString());
}

Now the simple callback.

public void MyAsyncCallback(IAsyncResult ar)
{
    Console.WriteLine("Things happening, async state calling.");

    var delegateMethod = (MethodDelegate)ar.AsyncState;

    Console.WriteLine(" called...{0}", DateTime.Now.ToLongTimeString());

    var returnedBits = delegateMethod.EndInvoke(ar);

    Console.WriteLine(" end invoked...{0}", DateTime.Now.ToLongTimeString());

    foreach (Application application in returnedBits)
    {
        Console.WriteLine("Application {0} is in {1} state...",
            application.Name, application.State);
        Console.WriteLine(" with {0} running instances, {1} memory per instance, {2} disk allocated...",
            application.RunningInstances, application.Resources.Memory, application.Resources.Disk);
        Console.Write(" hosted at ");
        foreach (var uri in application.Uris)
        {
            Console.Write(uri + " ");
        }
        Console.WriteLine(".");
    }
}

That’ll get the call running on a parallel thread and when it is wrapped up it returns the data.

The User Interface Interaction Issue

This is all fine and dandy for the command console. But if you want to give control back to the UI thread in a UI application and make sure that the background thread can actually update a control when fired off, do the same thing as I’ve discussed here except set the control up to invoke the dispatcher, so that the “threads don’t cross” when trying to return information to a control that needs updated. In order to do this take the control that needs updated and set the Dispatcher Invoke method as shown below.

private void Write(string updateText)
{
    UpdatingTextBlock.Dispatcher.Invoke(
    System.Windows.Threading.DispatcherPriority.Normal,
        new Action(delegate
    {
        UpdatingTextBlock.Text += updateText;
    }
    ));
}

For more on the Iron Foundry Project and the library I’ve used here, check out the Iron Foundry Blog & Site. For more information on Thor and to follow or get involved check out the Thor Project Site (Hosted with Cloud Foundry at Tier 3!).

All of this code is available in my Github Project “Remembering” (https://github.com/Adron/Remembering). Feel free to fork it, share it, or send me corrections or pull requests.

Adam & Krishan Got Me Motivated Today… to toss the trash conversations

I was speaking with Krishan Subramanian (@krishnan) and Adam Seligman (@adamse) today. I love talking to these guys. They’re both smart, intelligent and upbeat guys. They see the positive things we’re all working toward and accomplishing in the technology space, specifically around PaaS, Cloud Computing and around the cultural implications of stronger technology communities, involvement of individuals. We all can see the positives, of how the industry is moving forward so that corporations aren’t the only enablers that are juxtaposed against developers or consumers but instead act to serve consumers based on the progress that individuals make themselves. There’s so much to do and so much progress to be made, the venders can simply follow the community and step up to provide points of leadership.

Absolutely great talking with these guys…

On that topic, what is it that we discussed that has me so motivated? Well there’s a few things that I’m done with and I’m going to make every effort to just throw away the trash. Here’s a few of these things that we discussed and I challenge everybody out there, drop the trash talk and let’s move forward because there is a LOT of awesome things to accomplish. Here’s the two things I’m just dropping…  cold. No reason to discuss them anymore.

  • Toss the language and framework religious wars. It is far simpler than it is sometimes perceived. We have a polyglot industry now where we can easily use the right tool for the job, the right framework, or the language that handles our particular domain the best. There is literally no reason to argue about this anymore. Of course we can talk semantics, debate best use cases, and of course we’ll talk accomplishments and what various things do well. That’s exactly what the focus should be on, not the harping on my X is better than your Y nonsense.
  • The culture war is basically over. Sure there are the hold outs that haven’t gotten a clue yet. But it’s an open source world at this point. Even the dreaded and horrible Oracle has generally conceded this and is frantically waving its marketing arms around trying to get attention. But at the core, mysql, java and the other things that they’ve purchased they’re keeping alive. They’re active participants in the community now, albeit in a somewhat strange way. Considering that even Oracle, Microsoft, Apple and so many others contribute back to the open source community in massive ways, that war can be considered won. Victory, the community and every individual in that community!
  • Lockin is basically dead. The technological reasons to lock in are gone, seriously. There’s some issues around data gravity that are to be overcome, but that’s where a solid architecture (see below) comes in. Anything you need can be contributed to and derived from the development community. Get involved and figure out how technology can be a major piece of your business in a positive way. If you design something poorly, lock in becomes a huge issue. Use the rights tools, don’t get into binding contracts, because in the polyglot world we’re in now there’s no reason to be permanently locked in to anything. Be flexible, be where you need to be, and make those decisions based on the community, your support systems, and your business partners. Don’t tie yourself to vendors unless there is mutual reasons to do exactly that. Lock in is a dead conversation, just don’t, time to move on.

So what are the key conversations today?

  • Ecosystem Architecture – If you’re deploying to AWS, Heroku, Tier 3, AppFog or Windows Azure it all boils down to something very specific that will make or break you. Your architecture. This is where the real value add in the cloud & respective systems are, but there are many discussions and many elements of the technology to understand. This is a fundamentally key conversation topic in the industry today. Pick this one up and drop the other trash.
  • Movement & Data Gravity – How do you access your data, how do you store it, where and how do you derive insight from that data? This is one of the topics that came up in our discusssion and it is huge. The entire computer industry basically exists for the reason of insight. What should we eat today, how do I shift my investments, how is my development team doing, what’s the status of my house being built, where is my family today and can I contact them! All of these things are insights we derive from computer systems. These are the fundamental core reason that computers exist. As an industry we’re finally getting to a point were we can get some pretty solid insightful, intelligent and useful information from our systems. The conversation however continues, there is so much more we can still achieve. So again, drop the wasteful convo and jump on board the conversations about data, information and insights!
  • Community Involvement – I’ve left the key topic for last. This is huge, companies have to be involved today. Companies aren’t dictating progress but instead the community is leading as it should. The community is providing a path for companies to follow or lead, but the community, the individuals are the ones that are seen and known to be innovating. This is so simple it’s wild that it is only now becoming a known reality – companies don’t innovate, people do. Companies don’t involve, people do. Individuals are the drivers of companies, the drivers of Governments, they’re the ones driving innovation and progress. The focus should now and should have always been on the individuals and what they’re working toward to accomplish. So get involved, get the companies involved as a whole and keep the semantic ideal of individuals and the progress they can make core to the way you think of communities. The idea of the “company” innovating is silly, let’s talk and build community with the people that are working around and innovating with these technologies.

Of course there are more, I’d love to hear your take on what the conversations of today should be about. What do we need to resolve? How do we improve our lives, our work and the efforts we’re working toward on a day to day basis?

Thor – Cool Objective-C Bits, Libraries and Code Snippets [[TheSeries alloc] init];

Benjamin Van Der Veen (@bvanderveen) has been working with me to build out the Thor Application  based on Nathan Young’s (@nathanyoung) awesome designs. We’ll be releasing open source real soon. I wanted to cover some of the cool libraries, specific code snippets and such. These are a few of the things that have come in very useful as the coding deluge began.

Reactive Cocoa (AKA Reactive Extensions)

When you need to compose and transform sequences of values (kind of like Reactive Extensions for .NET) this is your library when working in Objective-C land. Reactive Cocoa or “RAC” for short can observe on key values to provide a key value for compliant properties. RAC helps to keep mutability under wraps (which is really really needed in Objective-C), pulls together behaviors and relationships between properties, and helps tremendously with asynchronous actions. The last bit we have a good amount of occurring with Thor since it talks to the Cloud Foundry web service API end points.

An example I snagged from the github site is below. It watches for changes on the username property.

[RACAbleSelf(self.username) subscribeNext:^(NSString *newName) {
    NSLog(@"%@", newName);
}];

Which serves, as pointed out in the README.md (be sure to read it if you’re going to use the library), as a wrapper around KVO. It goes on to show further sequences on complex actions.

[[[[RACAbleSelf(self.username)
    distinctUntilChanged]
    take:3]
    where:^(NSString *newUsername) {
        return [newUsername isEqualToString:@"joshaber"];
    }]
    subscribeNext:^(id _) {
        NSLog(@"Hi me!");
    }];

For some that write C# all the time this might seem like a “meh” moment. But considering the work that would be needed in Objective-C usually this could take significantly more lines of code, such as setting an observer, using a property or something to watch the value, monitor the non-distinct changes, and then bounce the value of the property for every non-distinct value. Yeah, and it still isn’t done. But anyway, that’s just the icing, the cake is delicious. If you’re in Objective-C land much, it is worth checking out.

Check it out on Github.