Aug 242016
 

This post is one of those brief ones I put out here as a reminder to myself and as a potential help to anyone else experiencing similar grief.

Recently, out of nowhere, I started getting the error “No valid combination of account information found” when executing a parse on a connection string for an Azure Storage Account.  Specifically, the failure occurred on

CloudStorageAccount.Parse(storageSetting);

Come to find out, in the midst of a huge merge of code, someone had inadvertently changed the connection string in the Web.config file of my ASP.NET site.  The string changed from

“DefaultEndpointsProtocol=https;AccountName=**************;AccountKey=*********

to

“DefaultEndpointsProtocol=https;Accountname=**************;AccountKey=*********

With this library, case matters and “AccountName” was changed to “Accountname”, which caused the error.

So beware, Microsoft.WindowsAzure.Storage is picky when it comes to casing.

Jan 112015
 
The Void - That's where your test results have gone

The Void – That’s where your test results have gone

Recently, I have been writing integration tests that cover async functions. During this work, I have encountered a quirky pain (of my own making) that I wanted to document. The purpose of the documentation is two-fold. First, the shame and self-deprecation of calling myself out will help to reinforce this point in my mind, and second, you might be able to avoid this goof up yourself.

The spoiler and 5 second take-away: When writing any function that uses async in C#, you must NEVER return void. The async keyword means that you intend to return something upon which the caller will await. That’s it. Lesson over.

If you want to know how weird things can get if you do this wrong in integration testing, read on…

So, I wrote a function that asynchronously returns a Task of string. Something like this:

public class Foo
{
    public async Task GetAStringFromIO()
    {
        // This is, presumably, a task that will take some time, so
        // we're going to await it.
        return await GetTheString();
    }

    private static Task GetTheString()
    {
        return Task.Run(() =>
        {
            // Simulate some really slow IO
            Thread.Sleep(1000);
            return "A String";
        });
    }
}

…and to test that, I wrote something along these lines:

[TestClass]
public class MyTests
{
    [TestMethod]
    public async void CanGetTheStringFromIO()
    {
        var foo = new Foo();
        string myString = null;
        myString = await foo.GetAStringFromIO();
        Assert.IsNotNull(myString);
    }
}

To my annoyance and great dismay, the test didn’t seem to run and my breakpoint wasn’t hit. The test wasn’t shown in the TestExplorer window. No bueno.
TestExplorer When Running Function returning void
The problem here, quite obviously, is that the async test function is returning void. The test runner expects something back on which it can await, but I am giving it nothing. This causes the test runner to exit. I wish it were more obvious, but there is no success, error, or inconclusive result – just a Test Explorer window without my test function.

After correcting the test by simply changing the return type to Task, life is good again. The Test Explorer shows my test and I can set breakpoints which actually pause execution of the test:
TestExplorerWithTask

Again, when writing any function that uses async in C#, you must NEVER return void. The async keyword means that you intend to return something upon which the caller will await. It’s just that easy.

If you are interested in a deep dive on this topic, I would recommend that you check out this article by Stephen Cleary: http://msdn.microsoft.com/en-us/magazine/dn818493.aspx. He has published books, articles, and blog posts surrounding all things C# asynchronous programming.

Dec 082014
 

In my last post, I showed a way to generate unit tests for existing code where a pattern exists using .NET’s System.Reflection library. The post showed an executable that would take the paths to a dll and an output file as input parameters where this executable would then tear through the assembly, looking for string properties for which I wanted tests. The exe would generate stub code to ensure that I wouldn’t miss any of the string properties.

I was discussing this with a colleague who suggested that I consider generating a T4 text template within Visual Studio to do this same work.  I had never used the templates before, but have found them to be amazingly simple, yet very useful tools to have in the arsenal.  I was able to take the code from the exe that I described in the last post, incorporate it into a template, and have it generate the same test code in about 5 minutes.

The benefit to using T4 text templates is that they are meta-code that reside within your Visual Studio project.  The cool thing is that the meta code regenerates the output file from the template during builds and after edits to the template.  Because of this close relationship with code in their project, these templates can be used to auto-generate output files that respond to changes in the code.  This can be particularly handy if you are creating schema files, config files, tests, or other forms of output that need to be kept fresh as your code changes.

I took the project that I used in the last post and added the T4 text template.  To do this, I simply added a new Text Template:

AddNewTextTemplate

After adding the template, you can see the template in the Solution Explorer window.  You can also see the generated code file as a child of the text template, as shown here:

TemplateInSolutionExplorer

When you first generate a text template, it puts header information in the .tt file for you that you have to edit.  You’ll notice that code that is to be evaluated is placed inside of <# #> bracketing.  The text within these delimiters will not be shown in the output file, but will contain the code needed to output something useful to the file.

<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ output extension=".txt" #>

You can see that the default output extension is .txt. I changed that to .cs. You can also see that the template is generated with assembly and import directives. Assembly is like adding a reference to a project and import is analogous to a using directive in a C# file. Since I already knew my dependencies from my prior project, I modified this information to look like this:

<#@ template debug="false" hostspecific="true" language="C#" #>
<#@ output extension=".cs" #>
<#@ assembly name="System"#>
<#@ assembly name="System.Xml"#>
<#@ assembly name="System.Xml.Linq"#>
<#@ import namespace="System" #>
<#@ import namespace="System.Xml.Linq"#>
<#@ import namespace="System.Reflection" #>

This block is code that the template will use when run. It is the list of references (assembly tag) and usings (import tag) that the code I will add later will use.

Next I will add the using statement block that I want my output file to have. This text will not be inside the <# #> delimiters because I actually want to see this code in my output file. Note that this text is not the usings that the template will need to run. Since it is outside of the delimiters, it is seen as simple text to be output:

using System;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;

Next, since I was writing a unit test file generator, the namespace and class declaration needed to be added. These were in funky functions in executable in my prior post. These functions added “header” and “footer” information, for lack of better terminology. This was awkward, but here it is quite elegant because I am actually writing this one-time-output text as it will be seen in the output.

namespace MyProject.Tests
{
    [TestClass]
    public class MyTests
    {
    }
}

After this, I extracted the code from the executable I built in the prior post and put it into the template. You’ll notice the <#= stuff #> where I wanted to emit text generated from code into the output file. This is the final text template file:

<#@ template debug="false" hostspecific="true" language="C#" #>
<#@ output extension=".cs" #>
<#@ assembly name="System"#>
<#@ assembly name="System.Xml"#>
<#@ assembly name="System.Xml.Linq"#>
<#@ import namespace="System" #>
<#@ import namespace="System.Xml.Linq"#>
<#@ import namespace="System.Reflection" #>
using System;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace MyProject.Tests
{
	[TestClass]
	public class MyTests
	{
		<#
		var a = Assembly.LoadFrom(@"c:\temp\ProjectToTest\ProjectToTest.dll");
        foreach (var type in a.GetTypes())
        {
            // get all public static properties of MyClass type
            var propertyInfos = type.GetProperties();

            // sort properties by name
            Array.Sort(propertyInfos,
                delegate(PropertyInfo propertyInfo1, PropertyInfo propertyInfo2)
                {
                    return propertyInfo1.Name.CompareTo(propertyInfo2.Name);
                });

            // write property names
            foreach (var propertyInfo in propertyInfos)
            {
                if (propertyInfo.PropertyType == typeof(string))
				{

		#>
[TestMethod]
		public void MyTests_<#=  type.Name.Replace("`", "") #>_<#= propertyInfo.Name #>()
		{
			// Put in code here for your test
		}
		<#
				}
            }
        } 
		#>
	}
}

If you’ll notice, the “[TestMethod]” indention looks a little nutty in the text template file. I found that I had to play a little to get the indention right. Also, you can see that I have hard-coded the path to the dll that I wanted to reflect. This could be made better via a project variable somehow.

After the final updates to the template file, Visual Studio automatically generated this output when I saved the template:

using System;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace MyProject.Tests
{
	[TestClass]
	public class MyTests
	{
		[TestMethod]
		public void MyTests_Class1_String1()
		{
			// Put in code here for your test
		}
		[TestMethod]
		public void MyTests_Class1_String2()
		{
			// Put in code here for your test
		}
		[TestMethod]
		public void MyTests_Class1_String3()
		{
			// Put in code here for your test
		}
		[TestMethod]
		public void MyTests_Class1_String4()
		{
			// Put in code here for your test
		}
		[TestMethod]
		public void MyTests_Class1_String5()
		{
			// Put in code here for your test
		}
		[TestMethod]
		public void MyTests_Class1_String6()
		{
			// Put in code here for your test
		}
		[TestMethod]
		public void MyTests_Class2_String1()
		{
			// Put in code here for your test
		}
		[TestMethod]
		public void MyTests_Class2_String2()
		{
			// Put in code here for your test
		}
		[TestMethod]
		public void MyTests_Class2_String3()
		{
			// Put in code here for your test
		}
		[TestMethod]
		public void MyTests_Class2_String4()
		{
			// Put in code here for your test
		}
		[TestMethod]
		public void MyTests_Class2_String5()
		{
			// Put in code here for your test
		}
		[TestMethod]
		public void MyTests_Class2_String6()
		{
			// Put in code here for your test
		}
		[TestMethod]
		public void MyTests_Class3_String1()
		{
			// Put in code here for your test
		}
		[TestMethod]
		public void MyTests_Class3_String2()
		{
			// Put in code here for your test
		}
		[TestMethod]
		public void MyTests_Class3_String3()
		{
			// Put in code here for your test
		}
		[TestMethod]
		public void MyTests_Class3_String4()
		{
			// Put in code here for your test
		}
		[TestMethod]
		public void MyTests_Class3_String5()
		{
			// Put in code here for your test
		}
		[TestMethod]
		public void MyTests_Class3_String6()
		{
			// Put in code here for your test
		}
			}
}

If I had some severely repetitious checks to make, I could make this file regenerate and change with every change to my code. This is interesting for unit testing, but really has cool applications in other areas, like schema generation, documentation, etc.

Much thanks to my colleague for pointing T4 text templates out to me! This is another cool tool to keep handy.

Nov 202014
 

There are times when you need to write unit tests and it is important to ensure that you get full code coverage.  That first sentence alone will tip you off to the fact that this is not a TDD scenario, but rather a situation where you need to create test cases for pre-existing code.  It is easy to overlook methods or properties when backfilling tests, so it would be nice to have a tool to help in these situations.  Thankfully, you can use .NET reflection to trawl through your assemblies, writing stub code, looking for the properties and/or methods that you have interest in and making sure that you don’t overlook important items.

I have written a quick example to illustrate how useful reflection can be in auto-generating tests and test stubs. The point here is not that I have written the be-all-end-all test generator, but to show that you can quickly cover some ground in brownfield testing with the proper application of the System.Reflection library.

In this quick example, I have 3 classes that each have some string properties:

namespace AssemblyToTest
{
    public class Class1
    {

        public string String1 { get; set; }
        public string String2 { get; set; }
        public string String3 { get; set; }
        public string String4 { get; set; }
        public string String5 { get; set; }
        public string String6 { get; set; }

    }
    
    public class Class2
    {
        public string String1 { get; set; }
        public string String2 { get; set; }
        public string String3 { get; set; }
        public string String4 { get; set; }
        public string String5 { get; set; }
        public string String6 { get; set; }
    }

    public class Class3
    {
        public string String1 { get; set; }
        public string String2 { get; set; }
        public string String3 { get; set; }
        public string String4 { get; set; }
        public string String5 { get; set; }
        public string String6 { get; set; }
    }
}

Let’s say that you’re interested in looking for all public string properties in classes in your assembly to ensure that you have proper string validation.  In TDD, you would have already written the tests before writing the code, so problem solved!  However, in many cases, you may find yourself retrofitting old code with new tests.  In this example, you can use reflection to load the assembly in which you are interested, loop through all of the types in the assembly, and then loop through the properties of each type.  Armed with this information, you can then use a writer to generate a unit test code file, complete with stubs.  You could even generate some of the test code, if you have enough domain information.

Check out this simple program for generating stub tests:

using System;
using System.IO;
using System.Linq;
using System.Reflection;  // reflection namespace

namespace UnitTestGenerator
{
    /// <summary>
    /// This program returns/generates a list of all properties for all classes in the given assembly that are of type string.  
    /// This program borrows from code found at the following sites:
    /// http://www.csharp-examples.net/reflection-property-names/
    /// http://stackoverflow.com/questions/1315665/c-list-all-classes-in-assembly
    /// http://msdn.microsoft.com/en-us/library/system.reflection.assemblyname(v=vs.110).aspx
    /// http://msdn.microsoft.com/en-us/library/1009fa28(v=vs.110).aspx
    /// http://stackoverflow.com/questions/3723934/using-propertyinfo-to-find-out-the-property-type
    /// </summary>
    /// 
    /// This program generates unit test stubs for all of the string properties of all of the types in an assembly.  It will need to 
    /// be modified to specifically generate the test stubs desired.  
    /// Argument 0 = Path to the assembly
    /// Argument 1 = Path and file name for output file
    class Program
    {
        static void Main(string[] args)
        {
            if (!ValidateArguments(args)){return;}

            using (var sw = File.CreateText(args[1]))
            {
                WriteUsingBlock(sw);
                WriteClassHeader(sw);
              
                var a = Assembly.LoadFrom(args[0]);
                foreach (var type in a.GetTypes())
                {
                    // get all public static properties of MyClass type
                    var propertyInfos = type.GetProperties();

                    // sort properties by name
                    Array.Sort(propertyInfos,
                        delegate(PropertyInfo propertyInfo1, PropertyInfo propertyInfo2)
                        {
                            return propertyInfo1.Name.CompareTo(propertyInfo2.Name);
                        });

                    // write property names
                    foreach (var propertyInfo in propertyInfos)
                    {
                        if (propertyInfo.PropertyType == typeof(string))
                            WriteTestForProperty(sw, type.Name.Replace("`", ""), propertyInfo.Name);
                    }
                }

                WriteClassFooter(sw);
            }
        }

        private static void WriteUsingBlock(TextWriter sw)
        {
            sw.WriteLine("using System;");
            sw.WriteLine("using System.Linq;");
            sw.WriteLine("using Microsoft.VisualStudio.TestTools.UnitTesting;");
            sw.WriteLine("");
        }

        private static void WriteClassHeader(TextWriter sw)
        {
            sw.WriteLine("namespace MyProject.Tests");
            sw.WriteLine("{");
            sw.WriteLine("    [TestClass]");
            sw.WriteLine("    public class MyTests");
            sw.WriteLine("    {");    
        }

        private static void WriteClassFooter(TextWriter sw)
        {
            sw.WriteLine("    }");
            sw.WriteLine("}");
        }

        private static void WriteTestForProperty(TextWriter sw, string typeName, string propertyName)
        {
            sw.WriteLine("      [TestMethod]");
            sw.WriteLine("      public void MyTests_{0}_{1}()", typeName, propertyName);
            sw.WriteLine("      {");
            sw.WriteLine("          // Put in code here for your test");
            sw.WriteLine("      }");
            sw.WriteLine("");
        }

        private static bool ValidateArguments(string[] args)
        {
            if (!args.Any() || args[0] == "/?" || args[0] == "/h" || args[0] == "/help" || args.Count() != 2)
            {
                Console.WriteLine("GenerateUnitTests takes 2 arguments.  The first is the dll for which tests will be created and the second is the output file.");
                Console.WriteLine("Usage: GenerateUnitTests <dll file path> <output file>");
                return false;
            }

            return true;
        }

    }
}

After running the generator code, you will get stub code that looks like this:

using System;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace MyProject.Tests
{
    [TestClass]
    public class MyTests
    {
      [TestMethod]
      public void MyTests_Class1_String1()
      {
          // Put in code here for your test
      }

      [TestMethod]
      public void MyTests_Class1_String2()
      {
          // Put in code here for your test
      }

      [TestMethod]
      public void MyTests_Class1_String3()
      {
          // Put in code here for your test
      }

      [TestMethod]
      public void MyTests_Class1_String4()
      {
          // Put in code here for your test
      }

      // The generator created many more tests, but I have 
      // omitted them for the sake of brevity.

This is just stub code from the example, but you could expand the generator to fit your testing needs.

TDD is definitely the desired way to generate greenfield code.  The benefits of focus alone prove that out.  However, when you have to retrofit tests for when refactoring or generating tests on existing code, using .NET’s reflection capability will save an enormous amount of “pattern pounding” and it will make sure you are thorough!

Jun 162014
 

If you work with 3rd party .NET libraries, you may find yourself in a situation where you would really, really like to see what is going on “beneath the hood” of that black box, 3rd party assembly you are using.  I have encountered cases where the API documentation wasn’t really clear as to what a method would do with a particular parameter.  I have also had cases where the 3rd party library failed on a call and the cause wasn’t readily discoverable.  For these cases, I have called on a very cool tool, Lutz Roeder’s .NET Reflector.  Unfortunately, that tool has now become a commercial, pay-to-use product of Red Gate Software.  There are several nice additions Red Gate has made to the tool, but for simple decompilation, I recommend the use of the open source, ILSpy tool.

ILSpy is a free, no-frills, .NET decompiler that uses reflection to IL to rebuild code back into C# syntax.  It is a very useful tool and can help with the problems I mentioned before where you really need to see inside assemblies where you don’t have access to the source code.  You can see from this example that I used ILSpy to look into the TryOpen method of the vdDocument class from VectorDraw, a 3rd party control for CAD rendering.  I wondered what was going on with file formats that are not native to VectorDraw (i.e. *.vdml and *.vdcl).

ILSpy Showing the vdDocument.TryOpen Method

ILSpy Showing the vdDocument.Open Method

I drilled into the vdDocument.Open method simply by clicking on the method in the deconstructed code.  That led me to the vdDocument.Open method and the ILSpy seamlessly displayed the code for the method:

ILSpy Showing the vdDocument.TryOpen Method

ILSpy Showing the vdDocument.TryOpen Method

From here, ILSpy shows me the code that it has reconstructed.  I can clearly see the branching around the file types and I can continue to drill down through this code.  I can use this to determine intent for the method or I can use this to see how parameters are used in their code.  This definitely comes in handy when there is some confusion around the use of a particular method.

I highly recommend ILSpy for all your .NET decompilation needs.  It is fast, detailed, and best of all it is free!

Jun 032014
 

One of the problems that we see at my work, often on a newly created development box, is that you can launch ArcMap from the debugger, but can’t break and examine code and objects.  The problem for this often lies in the ArcMap.exe.config file.  You must allow for the proper version of the .NET runtime in the config file.  Without it, the CLR won’t load the right runtime and debug symbols won’t align with the code you are running.

To fix this, edit the ArcMap.exe.config file, which is located at: C:\Program Files (x86)\ArcGIS\Desktop10.2\bin.  This post is for ESRI’s ArcMap, but it applies globally to all Windows exes that utilize .NET framework assemblies.

To run/debug against the 4.0 .NET framwork, make sure that you have this line in the ArcMap.config.exe file and you will be good to go:
<supportedRuntime version=”v4.0.30319″/>

You can read more about this from Microsoft in these two articles:

Mar 312014
 

Build

The Microsoft Build Conference last year was fairly enlightening for me in that it gave a peak into the direction Microsoft was intended to take their OS, cloud (Azure), and related products (Office, XBox). To me, it seemed that they were being quite reactionary in most all of their markets.

At the time, the Windows 8 OS was being revamped into Windows 8.1 in response to poor user perception. To their credit, Microsoft did their best to address user concerns, but it still seemed that they were trying to shoulder their way into the mobile space that, so far, has been dominated by Android and iOS. With tepid response and (still) unhappy desktop users, Microsoft seems poised to release Windows 8.1.1 with nods to the non-touchscreen crowd (which, arguably, would be most Windows users). I’m not sure that is going to generate much enthusiasm for the new OS, so I’m still a little confused as to where they are going to take Windows. Hopefully, they will release some information about Windows 9. Maybe it will herald the turnaround of Microsoft’s OS ship.

Cloud was a big, big deal last year. Microsoft demonstrated some pretty interesting applications of Azure, including a lot of support for mobile devices, authentication, and other support services. They demonstrated edits to a document on multiple platforms, which was so 2010 (can you say Google Docs?), but it showed well. Perhaps the best demo they had was one of Project Spark, where a world created on a Surface tablet was available for play on XBox One. It was really slick, but I think the wow factor was in Spark and XBox One, not in the cloud. Azure is pretty slick and the web UI is great, but there is nothing there that Amazon and Google haven’t been into for a while now. This will be another area where it will interesting to see if they show any innovation versus their competitors.

To Microsoft’s great credit, they did acknowledge the death of Silverlight and they even embraced newer (and older) technologies. Javascript got a lot of session time and the .NET platform updates were nice to see.

I look forward to see what the next few days hold at the Microsoft Build 2014 conference. All of the sessions can be streamed and you can find them all at the Channel 9 site.

Sep 202013
 

The .NET Framework provides a straight-forward and fairly easy syntax to use for callbacks.  These callbacks can be used for all sorts of messaging within your system.  These messages can signal a UI event, like a button press, or they can be used to send a message to many objects serially (multicasting).

The basis for all of this communication comes from ye olden callback.  The callback is simply a method where a pointer to a function is passed and then that pointer is used to (you guessed it) call back to that function.  This works well and has for years.  However, the problem with this methodology is that it is not type-safe.  That is, the function callback is merely a pointer to a location in memory where the function resides.  There is no guarantee that the function will have the expected signature of the code doing the callback.  This is where delegates come into play in the .NET Framework.

System.Delegate is a type in the .NET Framework Class Library that is used as a type-safe wrapper for a callback.  The delegate allows the CLR to ensure that all calls through the delegate will have the proper parameters.  Further, System.Delegate is extended with the System.MulticastDelegate type to allow for callbacks to multiple clients.

Events are a special type of delegate that provide protection for event calling and for the underlying delegates invocation list.  That is, only the class that defined the class my invoke the event and subscribers are allowed to add/remove only themselves from the invocation list.  Events are commonly used with UI objects, such as buttons, grids, trees, and other controls to callback to the underlying code when the user performs an action.

Defining and using events in the .NET framework is really straight-forward.  This sample shows the 3 steps to create and use a simple event:


using System;
using System.Threading;

namespace SimpleEventsExample
{
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // This is a simple example to demonstrate events. Remember these 3 things when setting up an event:
    // 1. Create a Type derived from EventArgs to pass back information pertaining to the event.
    // 2. Create an event that passes back the EventArgs instance in the object that is to publish the event
    // 3. Subscribe to the event in the objects that are to listen to the event.
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////

    /// 1. Create a Type derived from EventArgs to pass back information pertaining to the event.
    ///
    /// This is a Type derived from EventArgs whose payload is the current time at the time of the
    /// event and the seconds that have transpired since the beginning of the run.
    internal class SecondsCountdownClockExpiredArgs : EventArgs
    {
        internal SecondsCountdownClockExpiredArgs(DateTime currentTime, int secondsEllapsedSinceStart)
        {
            CurrentTime = currentTime;
            SecondsEllapsedSinceStart = secondsEllapsedSinceStart;
        }
        internal DateTime CurrentTime { get; set; }
        internal int SecondsEllapsedSinceStart { set; get; }
    }

    /// 2. Create an event that passes back the EventArgs instance in the object that is to publish the event
    ///
    /// This is the object that will be firing the event. It will allow subscription to the event via
    /// a public event.
    internal class SecondsCountdownClock
    {
        private const int MillisecondsInASecond = 1000;
        private readonly int _timerInterval;
        private int _secondsEllapsedSinceStart;
        private readonly int _seconds;

        // Define a public event to which listeners can sign up for notification
        public event EventHandler&lt;SecondsCountdownClockExpiredArgs&gt; SecondsCountdownClockExpired;

        internal SecondsCountdownClock(int seconds)
        {
            _seconds = seconds;
            _timerInterval = seconds * MillisecondsInASecond;
        }

        // Cheesy countdown timer that wakes up and fires based on the interval entered.
        internal void StartTheCountdown()
        {
            Console.WriteLine("Seconds Countdown Clock set to expire every {0} seconds", _seconds);
            for (; ; )
            {
                Thread.Sleep(_timerInterval);
                IncrementTimer();
            }
        }

        // When the interval has been reached, this function is called. If there are subscribers to the event,
        // create a new event args class, put information in the class, and fire the event.
        private void IncrementTimer()
        {
            _secondsEllapsedSinceStart += _seconds;
            if (SecondsCountdownClockExpired != null) SecondsCountdownClockExpired(this, new SecondsCountdownClockExpiredArgs(DateTime.Now, _secondsEllapsedSinceStart));
        }
    }

    /// 3. Subscribe to the event in the objects that are to listen to the event.
    ///
    /// This observer object will subscribe to the clock event and will output information to the console
    /// about the event.
    internal class ClockObserver
    {
        internal ClockObserver(SecondsCountdownClock secondsCountdownClock)
        {
            // Subscribe to the SecondsCountdownClockExpired event
            secondsCountdownClock.SecondsCountdownClockExpired += secondsCountdownClock_SecondsCountdownClockExpired;
        }

        static void secondsCountdownClock_SecondsCountdownClockExpired(object sender, SecondsCountdownClockExpiredArgs e)
        {
            Console.WriteLine("Current Time: {0:h:mm:ss}        Seconds Ellapsed Since Start: {1}", e.CurrentTime, e.SecondsEllapsedSinceStart);
        }
    }

    /// This program is a test harness that creates the countdown clock and creates and observer to listen to clock events.
    /// After it generates the clock and observer, it kicks things off by starting the clock.
    class Program
    {
        static void Main(string[] args)
        {
            // Create the clock that will publish clock events
            var seconds = Convert.ToInt16(args[0]);
            var theSecondsCountdownClock = new SecondsCountdownClock(seconds);

            // Create the observer that will listen to clock events and pass the clock pointer to its constructor
            new ClockObserver(theSecondsCountdownClock);

            // Kick off the clock
            theSecondsCountdownClock.StartTheCountdown();
        }
    }
}

Here is the output:

Output from the Seconds Countdown Clock - Demonstrating Events

Output from the Seconds Countdown Clock – Demonstrating Events

Although this sample isn’t very complicated, it is interesting to see what is going on under the covers with the Event type.  The Event type is really a special type of Delegate, which can be seen when examining the intermediate language using the ILDASM.exe tool.  A cursory look at the SimpleEventsExample.SecondsCountdownClock type shows the add and remove methods for the event:

ILdasm With Event Add and Remove

ILdasm With Event Add and Remove

Now look at the deconstruction of the add_SecondsCountdownClockExpired into IL:

Intermediate Language Showing Delete Combine

Intermediate Language Showing Delete Combine

You can see from the ILDASM output on line IL_000b that System.Delegate::Combine is the underlying mechanism used for adding to the event listener.  Further, looking at the IL for remove shows the underlying delegate remove.

Could you use a Delegate type for this?  Yes, you could, but the Event type is particularly designed for this sort of work.  It can only be raised in the class in which it was defined and it protects the invocation list (the list in the underlying delegate class) from being modified arbitrarily, which protects your code and makes for more robust software.

Jul 182013
 

I attended the Microsoft Build Conference a couple weeks ago in San Francisco.  I was very impressed with the keynote presentations, the depth of knowledge of the presenters at the technical sessions, and the manner in which the conference was run in general.  A few themes kept emerging throughout the conference.

1. The Computing World is Changing

The first of these was that the computing world is changing.  This is pretty obvious, but the clip at which things are changing is staggering.  Check out these stats from Gartner:

WorldwideDeviceShipmentsBySegment

Microsoft finds themselves in a world where PC sales are declining, while portable device sales (phones and tablets, most notably) are on the rise.  If Gartner’s predictions hold true, it shows that consumers are going to be interacting less and less with traditional Windows PCs.

Another set of numbers from Gartner that plays into the reactionary mood at Microsoft is that Windows is no longer the dominant OS for computing devices:

WorldwideDeviceShipmentsByOS

To quote Ms. Milanesi, from Gartner,

“The trend towards smartphones and tablets will have much wider implications than hardware displacement,” said Ms. Milanesi. “Software and chipset architecture are also impacted by this shift as consumers embrace apps and personal cloud.”

2.  Microsoft is Playing Catch Up

It was clear to all attendees that Microsoft is well aware of these trends and is doing its all to catch up with the wave that has, in some cases, passed them by.   Steve Ballmer described the new “One Microsoft” initiative, where he said that function will take precedent over organization.  To quote from Ballmer’s “One Microsoft:  Company realigns to enable innovation at greater speed, efficiency” memo:

“We are rallying behind a single strategy as one company — not a collection of divisional strategies. Although we will deliver multiple devices and services to execute and monetize the strategy, the single core strategy will drive us to set shared goals for everything we do. We will see our product line holistically, not as a set of islands.”

They are playing this strategy out in spades in their mobile division.  They are cutting prices on their Surface tablets and working across divisions to bring function to users by providing apps on the tablet that play through the Azure service with other devices, like phones, PCs and the XBox.  They are courting developers who work in Java and Javascript by creating way for them to enter the ecosystem.  As Ballmer stated, Microsoft is developing with a “rapid release cadence” to try to more quickly bring content to the market.  I think this is great and can only help us as developers and help spur competition and innovation in the market in general.

One interesting thing of note is that they seem to be trying to buy market share.  I spoke with developers from Hulu, Jeppessen, and NBA online and they were all there on Microsoft’s dime.  In fact, they all discussed that Microsoft has been funding their development efforts, to one extent or another, to bring their apps to the Windows 8/Windows RT platform.

3.  Microsoft Has A Lot Riding on Azure

The second keynote was spent going into detail about the Azure platform and the benefits of implementing solutions in IaaS, PaaS, and SaaS using Azure.  Discussion was made about how Azure is used by Microsoft for XBox gaming, SkyDrive, Skype, Outlook.com, and Office 365.  They stated that Azure storage and compute size doubles every 6 months and that there has been a 3x growth in the use of Hyper V virtualization.  Demos were given of the Azure Portal interface and I have to say that it is very slick.  I have since set up a website, a Windows Server VM, and an Ubuntu VM through the Azure Portal and can attest that it is very well done.  It is apparent that Azure is a big part of Microsoft’s future strategy and that as developers, we are long overdue to be embracing the cloud.

Microsoft seems to be turning the ship and is doing what it can to lure us as developers into its mobile ecosystem.  Given the large embedded user base, the number of line-of-business apps that run on Windows, and given the company’s obvious commitment to change with the industry, I think they will be a safe bet for a long time to come.