About the Author

Travis Schilling is focused on the Rich Client Stack of .NET that manifests his programming expertise in software technologies like C#, WPF, Silverlight, ADO.Net, WCF, and HTML5. His software expertise crosses the latest genre of cutting edge computing devices like the Microsoft Surface and the XBOX Kinect. After graduating from Neumont University in Salt Lake City, Utah with a Bachelor’s degree in Computer Science, Travis became a Software Engineer at InterKnowlogy in Carlsbad, CA. Travis has an expertise in NUI (The Natural User Interface) having built numerous multi-touch and gesture based interfaces for software applications. Travis is a Windows Developer 4 Microsoft Certified Professional Developer. When not architecting, designing and building software, Travis is often found in the gym, conquering the galaxy in StarCraft 2 or playing his bass guitar. Travis’ loves are his Nissan 370z and hanging with friends and family.

Uploading a file with an MVC 5 Controller with views, using Entity Framework

I’ve been working on a simple CRUD website using MVC 5 (w/ Razor) and EF 6, and when creating or editing a specific item I needed to upload a picture along with the EF object. I looked around and found a few options, but most were more complicated than I needed or they uploaded the picture/file separately from the create/edit views. So I wanted to document the simple hybrid I was able to use.

You start off with a database, EF model of that DB and an MVC 5 Controller with views, using Entity Framework (template from Visual Studio). The concept is virtually the same for Edit or Create, so I’ll only show the code related to Create.

In the .cshtml file I did 2 things.

  1. I updated the Html.BeginForm call to include the Action, Controller, method AND the enctype = “multipart/form-data”
  2. I added an input element that specified its type as a file, and it provided a button to choose a file, and showed the filename after the file was chosen.
<input type="file" name="file" id="file" style="width: 100%;" />

With that finished, I went to the backing controller, to the Create method, and added an additional parameter of HttpPostedFileBase. Now when the user clicks the save/create button the file parameter will be non-null if a file is chosen, and you can handle it however you like. Below is an example:

public async Task<ActionResult> Create( [Bind( Include = "Properties" )] EntityFrameWorkModel model, HttpPostedFileBase file )
{
	if ( file == null )
	{
		ModelState.AddModelError( string.Empty, "An image file must be chosen." );
	}
	else if ( ModelState.IsValid )
	{
		string fileName = Path.GetFileName( file.FileName );
		// Upload the file to Azure Blob Storage
		string savedFilePath =
			await Task.Run(
				() =>
				{
					var storageCredsAndAccountKey = new StorageCredentialsAccountAndKey( "{Storage Account Here}", "{Credentials Here}" );
					var storageAccount = new CloudStorageAccount( storageCredsAndAccountKey, true ); // true says to use HTTPS
					var blobClient = storageAccount.CreateCloudBlobClient();
					var container = blobClient.GetContainerReference( "{Container Name Here}" );

					var blockBlob = container.GetBlockBlobReference( fileName );
					blockBlob.UploadFromStream( file.InputStream );

					return blockBlob.Uri.ToString();
				} );
		model.FilePath = savedFilePath;
		
		db.EntityFrameworkObjects.Add( model );
		await db.SaveChangesAsync();
		return RedirectToAction( "Index" );
	}
	
	return View( model);
}

As I said, it’s a simple solution, but it’s quick to implement.

Supporting iOS 6.1 and iOS 7 (Xamarin.iOS)

As a developer it’s always way more fun to play with the new “toys” a new framework or OS provides. The issue we usually run into is at what point are we able to start using the new functionality in applications we develop. With Apple and iOS, the adoption rate of new versions is so high and so quick that you only really need to worry about supporting the 2 latest versions. With that said, if you’re starting something brand new you’ll probably just want to build against the newest version, but if you’ve got an existing application that you want to function in both versions you’ll need to do some work.

1st: If you don’t have Xcode 5, copy the iPhoneOS6.1.sdk and the iPhoneSimulator6.1.sdk folders from your existing Xcode 4.6.3 installation somewhere else so you can still dev for iOS 6. The simulator SDK can also be downloaded after the upgrade, but this is faster since you already have it on your machine. The SDKs are located under /Applications/Xcode.app/Contents/Developer/Platforms. In Finder choose Go => Go to Folder to get to the desired directories. Copy both of these folders somewhere else for use later.

  • iPhoneOS6.1.sdk is located here /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/
  • iPhoneSimulator6.1.sdk is located here /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/

NOTE: If you’ve already upgraded to Xcode 5 you’ll need to download the Xcode 4.6.3 installer from the Apple Developer site located here. Once downloaded, open the .dmg file and right-click on the Xcode icon, choose “Show Package Contents” and then follow the same directory structure to get to the SDK folders.

2nd: In order to support iOS 7 make sure you are upgraded to OS X 10.8.5 and Xcode 5.

3rd: With Xcode 5 installed copy the iPhoneOS6.1.sdk and iPhoneSimulator6.1.sdk folders back to the directories you copied them out of. You should notice 7.0 versions of each SDK now in those directories as well.

4th: In Xamarin Studio under the iOS Build view in your project options, you’ll now notice that you have the ability to specifiy 6.1 as the SDK version as well as 7.0. Under the iOS Application view is the more important Deployment Target property. Set this to 6.1 in order for the application to still be deployable. Otherwise only iOS 7 devices will be able to get it from the app store. Making this change will allow it to be deployable for both versions, but you still have one more thing.

5th & Last: Apple made some drastic changes with how certain properties work, how the NavigationController’s title bar and the iOS status bar look and work, and a bunch of other things. You’ll need to add version specific code to handle/fix these changes. I created a VersionHelper static class to do the comparison logic for me. There are definitely other ways to accomplish this but here it is:

public static class VersionHelper
{
	private static Version _systemVersion;
	public static bool CurrentVersionIsGreaterThanOrEqualTo( Version versionToCompareAgainst )
	{
		if ( _systemVersion == null )
		{
			_systemVersion = new Version( UIDevice.CurrentDevice.SystemVersion );
		}

		return _systemVersion >= versionToCompareAgainst;
	}
}

With that you should be good to go.

Creating an iOS Settings Bundle (Xamarin.iOS)

With the investigation I’ve been doing in building an iOS application using Xamarin, I’ve now gotten to the point where I wanted to put some settings into the iOS Setting app for my application. I found this nice thread that gave the 3 easy steps to set up a settings bundle.

It literally is as simple as written, but there were a couple gotchas that I ran into that I wanted to forward along.

  1. The Settings.bundle folder needs to be in the project root, NOT under the Resources folder (where some examples showed it). I’m not sure if this is a new change or not, but I spent some time banging my head against the wall over this one.
  2. If you do not register default values for your settings they’ll return the default for the data type. (ie. null for String, false for bool, etc….). The DefaultValue you specify in the Root.plist file for a setting is the default value the control will show, NOT the value of the setting. Below is an example of registering default values for settings.
  3. NSUserDefaults userDefaults = NSUserDefaults.StandardUserDefaults;
    NSMutableDictionary appDefaults = new NSMutableDictionary(); 
    appDefaults.SetValueForKey( NSObject.FromObject( true ), new NSString( "BooleanSettingKey" ) );
    userDefaults.RegisterDefaults( appDefaults );
    userDefaults.Synchronize();
    

Accessing the value for a setting is a simple as the following:

bool settingValue = NSUserDefaults.StandardUserDefaults.BoolForKey( "BooleanSettingKey");

One last thing that I found in an example solution here was how to listen in your app for when settings have been changed and wanted to pass it along:

NSObject observer = NSNotificationCenter.DefaultCenter.AddObserver( (NSString)"NSUserDefaultsDidChangeNotification", DefaultsChanged ); 
private void DefaultsChanged( NSNotification obj )
{ 	
// Handle the settings changed 
}

The biggest bummer I found in the iOS Settings Bundle is that everything is statically defined. So if you happen to have a collection of items that you want updated from a server, you’ll have to do this on your own inside your application.

Working with UITableView (Xamarin.iOS)

After setting up my solution, my next step was to figure out how to display a list in iOS with the ability to select an item. In WPF, my first thought would be to utilize the ListBox control, bind its ItemsSource to the underlying data, and define an ItemTemplate for how I want each item to look. Not so simple in iOS. There’s a nice list control called the UITableView that provides support for a number of neat things (indexed list, splitting the items into sections/grouping them, selection, etc…). However, to accomplish the most important part, hooking it up to data, you have to define a data source object that you assign to the .Source property of the UITableView. There are a number of ways to accomplish this, but I went with creating a source that inherits from UITableViewSource. Xamarin has a nice guide that I used for guidance (Working with Tables and Cells).

Coming from WPF and MVVM I wanted to make this source reusable rather than following all the examples that were hardcoded to a specific object type. So I decided to create an ObjectTableSource, and since I’m still in the early stages of development I decided to make use of the built-in styles for the cell appearance rather than making a custom cell. With this in mind I needed to make sure that the objects provided to my table source had specific properties for me to utilize so I created an interface called ISupportTableSourceand used that as the .

public interface ISupportTableSource
{
	string Text { get; }
	string DetailText { get; }
	string ImageUri { get; }
}
public class ObjectTableSource : UITableViewSource

When inheriting from UITableViewSource you must override RowsInSection and GetCell. RowsInSection is exactly what it sounds like, you return how many items are in that section. My current version only supports 1 section so it returns the total number of items. GetCell returns the prepared UITableViewCell. The UITableView supports virtualization of its cell controls so in order to get the cell you need to call the DequeueReusableCellmethod on the table view. In versions earlier than iOS 6 this will return null if the cell hasn’t been created yet. In iOS 6 and later you can choose to register a cell type with the UITableView and that will make it so a cell is always returned. However, going this path means that you can’t specify which of the 4 build in styles to use (since it is specified in the constructor only), so I refrained from registering the cell type and handle null. When preparing the cell I also loaded any images on a background thread so the UI is still responsive, but I’ll cover that in another post.

public override int RowsInSection( UITableView tableview, int section )
{
	return _items.Count;
}

public override UITableViewCell GetCell( UITableView tableView, NSIndexPath indexPath )
{
	// if there are no cells to reuse, create a new one
	UITableViewCell cell = tableView.DequeueReusableCell( CellId )
			       ?? new UITableViewCell( _desiredCellStyle, CellId );

	ISupportTableSource item = _items[indexPath.Row];
	if ( !String.IsNullOrEmpty( item.Text ) )
	{
		cell.TextLabel.Text = item.Text;
	}
	if ( !String.IsNullOrEmpty( item.DetailText ) )
	{
		cell.DetailTextLabel.Text = item.DetailText;
	}
	if ( !String.IsNullOrEmpty( item.ImageUri ) )
	{
		cell.ImageView.ShowLoadingAnimation();
		LoadImageAsync( cell, item.ImageUri );
	}
	return cell;
}

The remaining thing for making this usable was to provide a way to notify when an item has been selected. There isn’t any event on the UITableViewSource like I expected, instead I needed to override the RowSelectedmethod and fire my own event providing the object found at the selected row.

public override void RowSelected( UITableView tableView, NSIndexPath indexPath )
{
	ISupportTableSource selectedItem = _items[indexPath.Row];

	// normal iOS behaviour is to remove the blue highlight
	tableView.DeselectRow( indexPath, true );

	OnItemSelected( selectedItem );
}

Beginning Xamarin and Xamarin.iOS

I’ve recently started delving into using Xamarin and Xamarin.iOS to get an understanding of its capabilities and see what I could do with it. After my first little app, I have to say it is really impressive what the people at Xamarin have done!

I’m coming at this from years of experience in C# and WPF/Silverlight/XAML and I wanted to describe my initial findings. For this post I plan to cover the general setup.

Installation

My goal was to have an iPad application that does something similar to a Master-Detail set of views where I could display a collection of images. Because of this I wanted to get a grasp on both Xamarin Studio and the Visual Studio integration so I installed Xamarin for Windows (on my primary dev machine) and Xamarin for OS X (on a Mac Mini we have at our office) from here. NOTE: On Windows 8 run the Xamarin installer as Administrator otherwise it will error out near the end. The installation took a while because it downloaded everything that I needed to develop for iOS (and for Android since I wanted to look into that in the future too.), but once everything was installed I was able to start developing instantly.

The installation guides for Xamarin.iOS, located here, provided excellent instruction for hooking up Visual Studio 2012 to remote debug on the Mac Mini (Section: 6.2. Connecting to the Mac Build Host), and the Xamarin services that were installed made it so that I found and connected to the Mac immediately. On another note, Synergy is an amazing tool to use to share your keyboard and mouse between the 2 devices. You need to make sure both machines are on the same network though in order for it to work (quickly at least).

Solution Setup

With Xamarin installed, I decided to get my feet wet by following Xamarin’s Hello, iPhone guide. (They’ve done a very nice job with their guides covering a nice range of topics.) For someone who has never developed in Xcode (and is pretty much a Mac beginner) this provided a nice tutorial of the tool.

With a general idea of how to get started, I created my solution in VS 2012 and on the Mac I used “Finder” to connect to my machine and open up the solution in Xamarin Studio. I’ve found that if I want to use Xcode’s Interface Builder to design my UI I need to add the iPad View Controller via Xamarin Studio, since adding it in Visual Studio didn’t create the .xib file.

My next step was to set up a core library, since I desire to try Xamarin’s Android functionality in the future, to enable code reuse. Xamarin is currently developing support for referencing Portable Class Libraries (PCLs), but until they’ve got that functioning we have to go more manual routes. I created the PCL to hold my core files (model objects primarily), but went the route of linking to all those files in the iOS project. Once I work on the Android counterpart I’ll be able to update with whether I think it’s the right way to go.

EDIT: With the release of Xamarin.iOS 7.0.1, they’ve apparently fixed the PCL build issue I was running into. So I was able to remove the links to all the files and reference the PCL library instead!

Debugging

It is extremely nice to be able to dev and debug in VS 2012 while connected to the iOS simulator on the Mac. When running into exceptions being thrown, I found that, if it wasn’t immediately apparent as to what the exception was caused by, debugging from Xamarin Studio on the Mac provides better exception information.

I’ll go into more detail on discoveries I ran into in other posts, but overall the development process using Xamarin and Xamarin.iOS has been very interesting and enjoyable. I would definitely recommend it.

Accessing Dependency Property (DP) Changed in WinRT

With the release of Windows 8 and WinRT, I began the process, during RECESS, of porting an existing app we’d created for the Microsoft Surface (the team that is now called “Pixel Sense”) to be a Windows Store application. The application followed more of an MVC (Model View Controller) approach, rather than MVVM (Model View ViewModel), so there we a number of controls that subscribed to the DataContext and Visibility changed events in their code behind, which don’t exist in WinRT.

WinRT (Windows Store) applications seem to have many of the same limitations that Silverlight had, compared to WPF, and rather than rewrite the parts of the application to try and avoid needing to know when these DPs changed, I came up with a simple framework to register for a callback when a specified DP changed.

First Solution

The way to get around this issue was actually really straight forward. In each control, I created and registered a DP for each DP I wanted a change notification from (ie. DataContextEx, VisibilityEx, etc…).

public static readonly DependencyProperty DataContextExProperty =
		  DependencyProperty.Register( "DataContextEx", typeof( object ), typeof(DemoControl ),
			new PropertyMetadata( null, OnDataContextExChanged ) );

public object DataContextEx
{
	get { return (object)GetValue( DataContextExProperty ); }
	set { SetValue( DataContextExProperty, value ); }
}

private static void OnDataContextExChanged( DependencyObject d, DependencyPropertyChangedEventArgs e )
{
	( (DemoControl)d ).OnDataContextExChanged( e );
}

private void OnDataContextExChanged( DependencyPropertyChangedEventArgs e )
{
	//Handle the change
}

Then, in the control’s constructor, I bound the created DP(s) to the related DP I wanted to know had changed. With this binding, whenever the source DP (ie. DataContext, Visibility, etc…) changed it would cause the “extension” DP to change and that would call the changed handler I registered when creating the DP.

var binding = new Binding
			{
				Path = new PropertyPath("DataContext"),
				RelativeSource = new RelativeSource
								{
									 Mode = RelativeSourceMode.Self
								}
			};
SetBinding(DataContextExProperty, binding);

With this I had all that I needed. However, I hated the idea of having to rewrite this code on every control that I needed the notification on. So I decided to create a framework to allow me to register for a changed callback on any FrameworkElement.

Framework

I decided to go the route of creating a FrameworkElement extension method called RegisterDependencyPropertyChanged that takes a lambda expression for the property to bind to and a callback for when that property changes.

this.RegisterDependencyPropertyChanged( () => DataContext, DataContextChangedHandler );

The extension then calls RegisterDependencyPropertyBinding on FrameworkElementAttachedProperties. FrameworkElementAttachedProperties is an internal class that holds the functionality to create and register an Attached DP for each type of DP (ie. DataContext, IsHitTestVisible, Visibility, etc..) the user desires a callback for and bind that Attached DP to the DP (using the same process defined under First Solution. Then whenever that value changes it attempts to find a callback registered for it, and if one is found, calls the registered callback with the DependencyPropertyChangedEventArgs provided.

Attached DPs are only able to be bound to one property of an object at a time (but can be bound to the same property of multiple objects). This is why an Attached DP is created and registered for each DP of a control as there may be a case where a change callback is registered for more than one property of that control. Therefore whenever FrameworkElementAttachedProperties.RegisterDependencyPropertyBinding is called it calls GetNextUnusedAttachedPropertyForFrameworkElement. This either grabs an existing Attached DP registered for that property, or it will create and register a new one and return it.

private static DependencyProperty GetNextUnusedAttachedPropertyForFrameworkElement( string propertyName )
{
	if ( !_staticExtensionDPs.ContainsKey( propertyName ) )
	{
		var unusedDependencyProperty = DependencyProperty.RegisterAttached( _extensionDPsNamePrefix + "_" + propertyName,
													   typeof( object ),
													   typeof( FrameworkElementAttachedProperties ),
													   new PropertyMetadata( null, DependencyPropertyExPropertyChanged ) );
		_staticExtensionDPs.Add( propertyName, unusedDependencyProperty );
	}
	
	return _staticExtensionDPs[propertyName];
}

The registered callbacks are stored in the DependencyPropertyCallbacks Attached DP on FrameworkElementAttachedProperties. By storing the callbacks in the Attached DP, when the control that has registered is unloaded, it can be collected by the Garbage Collector and there aren’t memory leaks.

Conclusion

I tend to prefer the MVVM approach, but there are cases when constraints dictate that a different approach is used. This is a nice little addition for when that occurs. Here is a demo solution containing the framework (FrameworkElementExtension.cs) and an example of how to use it.

Copying Files After a Successful Build With Robocopy on VS2010

The Problem
In one of the latest projects I’ve been working on, I needed to be able to interchange data providers. We decided to use Prism and MEF to load up the concrete instance of our IDataProvider at runtime, and created a separate project to contain the XML based implementation of that provider. Since we need a concrete instance to debug I wanted the latest .dll and .pdb of the XML data provider project to be copied into a Modules folder in the app’s output directory after it has successfully built. At first I thought I would use xcopy to copy the files, but after seeing that it has been deprecated, I switched to using Robocopy (which turned out to be just as easy). Once I figured what tool I would use to copy the files, I needed to figure out where to run the command from and I found 2 options.

Option 1: Project Post-build event
The quickest option I found was to enter the Robocopy command into the Post-build Event Command Line box in the project properties. Since Robocopy comes with Windows Vista and on you can open the Command Prompt and type robocopy /? to see everything that it is capable of. The command I used to copy the .dll and .pdb files was the following:
robocopy “$(TargetDir)\” “$(SolutionDir)\Application\$(OutDir)\Modules” $(TargetName).dll $(TargetName).pdb

With that command entered, I saved and then built the project, but the build was not successful and displayed an error staying robocopy exited with a code of 1. Wondering why I received this error, I went to the application’s output directory to find, to my surprise, that the Modules folder had been created and both the .dll and .pdb files had been copied successfully to that folder. Searching around for an answer I found this stackoverflow post explaining that unlike every other command line tool that returns a 0 when successful (which is what Visual Studio expects), robocopy returns a 1 when successful. So after adding a check to exit with a code of 0 if the error level was 1, it then built successfully.

Option 2: MSBuild Extension AfterBuild
On the stackoverflow post, mentioned above, there was an answer that recommended using the Robocopy task in the MSBuild Extension Pack as an AfterBuild target. I found this idea very intriguing (especially since it appeared to handle the return code of 1 issue) and attempted to use it to accomplish the same copying task. After a few hours of working with it I found that I could only get it functioning installing the MSBuild Extension Pack3.5 (even though I am on an x64 machine and building a .Net 4.0 project). I then edited my .csproj file and added the following code, which does the exact same thing as the post-build command, at the bottom of the file. After reloading and building the project, the files were copied to the Modules folder.

<Import Project="$(MSBuildExtensionsPath)\ExtensionPack\MSBuild.ExtensionPack.tasks"/>
<Target Name="AfterBuild">
	<ItemGroup>
		<OutputFiles Include="$(TargetName).dll"/>
		<OutputFiles Include="$(TargetName).pdb"/>
	</ItemGroup>
	<MSBuild.ExtensionPack.FileSystem.RoboCopy Source="$(TargetDir)\" Destination="$(SolutionDir)\Application\$(OutDir)\Modules" Files="@(OutputFiles)">
		<Output TaskParameter="ExitCode" PropertyName="Exit" />
		<Output TaskParameter="ReturnCode" PropertyName="Return" />
	</MSBuild.ExtensionPack.FileSystem.RoboCopy>
	<Message Text="ExitCode = $(Exit)"/>
	<Message Text="ReturnCode = $(Return)"/>
</Target>

The Decision
While Option 2 is very cool and clean looking, I decided to stick with Option 1 for the following reasons:

  1. Option 2 would require all the developers on the project to install the MSBuild Extension pack (not difficult at all but time consuming and annoying if your builds are failing and you didn’t know you needed the 3rd party pack)
  2. Writing the Post-build (Option 1) command was much quicker
  3. If any other developer is wondering how the files are being copied into the Modules folder (or needs to change it), with Option 1 they can quickly and easily look at (and change) the Post-build event in the properties window, but with Option 2 they have to know to go edit the .csproj file and then search it to find the AfterBuild target code

SpeechRecognitionEngine Grammar Choices and Updating them Dynamically

The Microsoft Speech Platform provides a great speech recognition engine. I’ve been using it with the Microsoft Kinect to add voice command functionality to existing Kinect enabled WPF applications. The SDK is located here, and once installed you just need to add a reference to Microsoft.Speech.dll, which is located at C:\Program Files\Microsoft Speech Platform SDK\Assembly.

Static Choices
Once you have the SDK and assembly referenced, the process of specifying what words or phrases you want the SpeechRecognitionEngine to look for is extremely straight forward and easy. Just specify your collection of Choices, create a new GrammarBuilder and append the Choices to it, create a Grammar and provide it with the GrammarBuilder, and finally load that Grammar into the SpeechRecognitionEngine. You can then point the SpeechRecognitionEngine to your audio source and tell it to RecognizeAsync.

var sre = new SpeechRecognitionEngine(ri);
var currentChoices = new Choices();
currentChoices.Add("red");
currentChoices.Add("show blue square");

var gb = new GrammarBuilder
{
     Culture = _ri.Culture
};
gb.Append(currentChoices);

sre.LoadGrammar(new Grammar(gb));

Dynamic Choices
If you know all of the possible command choices from the beginning and never need them to change, then this is as far as you need to go. I, however, wanted to be able to change what choices were valid based on what area of the application I was in. I had hoped it would be as simple as adding and removing choices for the collection, but there isn’t any remove functionality in Choices, GrammarBuilder, or Grammar. On the SpeechRecognitionEngine I did find an UnloadGrammar method so I figured I could just keep a collection of my currently valid choices, create a new Grammar from those, unload the old Grammar, and then load the new one. When I ran the application I ran into some very weird results. Calling UnloadGrammar would take a very long time to execute (it took 3 minutes for one try). Once it got past that point loading the new grammar worked, but the amount of time it was taking was unbearable and I would not be able to use it if there was always the possibility of the application freezing up for that long just to change the available audio choices. So after a long time searching I finally decided to see what MSDN had to say about the UnloadGrammar and LoadGrammar methods and found this page. It is for Office 2007 R2 but the example it provided put me on the right track.

It turns out that when the SpeechRecognitionEngine is running, any changes to the grammar need to occur when the engine is ready for the changes. To get the engine ready you need to call RequestRecognizerUpdate and pass a custom object (that contains what action you want to do and the related data) into the method as a UserToken.

sre.RequestRecognizerUpdate(new UpdateGrammarRequest
								{
									RequestType = GrammarRequestType.UnloadGrammar,
									Grammar = _currentGrammar
								});
sre.RequestRecognizerUpdate(new UpdateGrammarRequest
								{
									RequestType = GrammarRequestType.LoadGrammar,
									Grammar = _currentGrammar
								});

You also need to subscribe to the RecognizerUpdateReached event on the engine, and in that event handler you can call the UnloadGrammar and LoadGrammar methods which will then execute immediately.

private void RecognizerUpdateReached(object sender, RecognizerUpdateReachedEventArgs e)
{
	var request = e.UserToken as UpdateGrammarRequest;
	if (request == null)
		return;
		
	switch (request.RequestType)
	{
		case GrammarRequestType.LoadGrammar:
			sre.LoadGrammar(request.Grammar);
			break;
		case GrammarRequestType.UnloadGrammar:
			sre.UnloadGrammar(request.Grammar);
			break;
		default:
			throw new ArgumentOutOfRangeException();
	}
}

By doing this, you still end up with a tiny bit of lag between calling RequestRecognizerUpdate and having the RecognizerUpdateReached event fire, but it is only ever a couple seconds instead of minutes.

Remote Debugging from Visual Studio 2010

In my latest project I was running into an issue where running my installed application on a test machine was crashing before it could even startup, but it ran perfectly when installed on my machine. I was almost to the point of taking the time to install Visual Studio 2010 on the test machine, when my coworker, Bryan Coon, reminded me of the Remote Debugging capabilities of VS and recommended trying that first.

I started off using Danny Warren’s Remote Debugging post to get both my machine(on domain) and the test machine(off domain) enabled so that I could Attach to Process (Ctrl+Alt+P) from VS 2010 on my machine. Here are the main points that I gathered from it:

  • 3 instances of the same username needed to exist as administrators (and have been logged into at least once)
    1. The domain username on my machine (domain\travis). This is the username that Visual Studio is run under.
    2. The machine username on my machine (MyMachine\travis)
    3. The machine username on the test machine (TestMachine\travis). This is the username that the remote application is run under.
  • The Visual Studio 2010 Remote Debugging Monitor needed to be installed on the test machine
    • Use the setup program that matches the OS (x86, x64, ia64)
    • I ran the application instead of setting it up as a service, so I needed to make sure it ran as an administrator
  • Everything from the bin\Debug folder of the application must be copied to the test machine.

Once the Remote Debugging Monitor was started, I was able to view all the running processes in VS by entering the name of the server that the Remote Debugging Monitor started (travis@TestMachine) into the Qualifier box.

In most cases this would have allowed me to then attach to my running application and hit debug points. My application, however, crashed before the application even became available in the list of available processes.

So the next step was to get Visual Studio 2010 configured on my machine to start the application on the remote (test) machine when I started the application with debugging (F5). I found what was needed here. All that was required was to modify the following properties in the Debug section of the application properties screen:

  • Select Start external program and specify the path to the application on the remote computer
  • Check Use remote machine and specify the remote machine

The gotcha I ran into was that again the remote machine name is the server name that the Remote Debugging Monitor started not the actual machine name.

With these final steps completed I was able to start the application with debugging and immediately found my issue. While this process took a little bit of time to setup, it saved a bunch of time that would have been spent installing Visual Studio 2010 and allowed me to keep the test machine clean of all developer tools. So if I run into an issue like this again I will definitely think to try Remote Debugging right away.

Delivering the Art of Lunch

Here at InterKnowlogy we have this great program called RECESS where we get to take a few hours each week to try our hand at new technologies. One of our leads, Dan Hanan, posted a great little read on what RECESS actually is so I won’t go into any more detail about it.

Background
One of the best ways, we’ve found, to learn a new technology is to utilize it in an application in order to find its strengths, weaknesses, etc. Being a bunch of Software Engineers we have a tendency to be obsessive and compulsive in almost everything we do, and when that is paired with pickiness over certain types of food, deciding upon where to go to lunch as a group becomes very time consuming (almost longer than actually eating the food). So back in the spring of this year a couple of other devs and myself decided we wanted to learn more about ASP.Net MVC, Silverlight 4 (with RIA), and Entity Framework 4, and decided on creating a lunch decision service using these technologies (kill 2 birds with 1 stone and have fun doing it). We also decided that we needed a good name for this application before we could start, and since InterKnowlogy’s slogan had recently changed to Delivering the Art of Software, we decided to play with it and call our application the DAL (Delivering the Art of Lunch).

Scenario
The most important thing we’ve learned from other RECESS projects is to keep the finished project as simple as possible otherwise it won’t ever be finished. So we decided to create a service that would send out an email to all the registered users, at a specified time in the morning, to see if they will be joining the group for lunch. In the email is a link to an MVC page where they say yes or no. A little later on everyone who says that they are in for lunch then receive another email with a link to another MVC page where they can choose their top 3 restaurant choices(the restaurants are an intersection of all the preferred restaurants of the users joining in for lunch), and a little later an email stating the restaurant choice is sent out to everyone participating in lunch. It is then up to the people involved on whether they are going to abide by the choice or not.

We decided to use the Silverlight client to be where we register users, create/update/delete restaurants, and choose which restaurants the user is ok with going to for lunch, and the ASP.Net MVC site is where the users specify if they are available for lunch and their top 3 restaurant choices. It also shows who has said they are joining in and what the final restaurant choice is.

After a few weeks of work we had an Alpha version that we wanted to try out with our coworkers. So we deployed it to a server, and sent out an email letting everyone know about it. With it being Alpha we expected to run into a few issues, but within the 1st day we hit one issue that brought the whole thing down. Our owner, Tim Huckaby, loves to hear about new things we’re working on and try them out. So he joined in, added 5 top restaurants in the world (that none of us can afford let alone get to over lunch time), and made only those 5 his preferred restaurants. The next day when the process started and he said he was in for lunch (even though he doesn’t eat lunch with us), the resulting intersection of preferred restaurants was empty, and we weren’t able to use the application when it never provided restaurants to choose from.

Fixing the bug
While we have given Tim some much deserved crap over the restaurants he chose, he did find a very damaging bug that needed to be fixed. Our end result was if the restaurant intersection didn’t return any results then choose up to 5 of the most popular preferred restaurants, and if there still weren’t any the service randomly chooses 5 restaurants for everyone to vote on.

After a long hiatus, I finally got the bug fix along with a number of other refactorings up again and we’ll see how long it can stand. 🙂

Finally
The overall learning experience was pretty positive. Entity Framework makes development against a simple database extremely easy, and in the Silverlight world, pairing that with RIA services gives you the same functionality on the client side. One issue with RIA that I ran into is the fact that any extra methods you create to extend the DomainService is very limited to the parameter types that can be used. It is extremely powerful for basic CRUD functionality, but it takes work to get more complex things functioning. ASP.Net MVC is really powerful and something that I will need to delve into more in the future.

More RECESS rambles to come.