How to reference C++ WRL Components from a .NET project

Whenever your Windows Runtime (WinRT) component has to implement COM interfaces as well as WinRT interfaces, Microsoft advises you to use the Windows Runtime Template Library (WRL), because the C++/CX – which otherwise is recommended to develop WinRT components – does not allow to implement COM interfaces.

However, if you are trying to use some of Microsoft’s publicly available samples from a .NET component, you might run into trouble. The problem is, that the winmd file that gets generated when you compile a WRL C++ Component – by default – does NOT reference the “Windows.winmd”-file, which provides the meta data for the WinRT API as a whole. Instead, it references only the particular winmd-files that describe partial areas of the WinRT API. These partial WinRT descriptions can all be found at a location similar to “C:\Windows\System32\WinMetadata”, whereas the complete WinRT API can be found at “C:\Program Files (x86)\Windows Kits\8.0\Windows Metadata\Windows.winmd”.

To demonstrate this problem I am referring to Microsoft’s “Real-time communication sample” that can be found at http://code.msdn.microsoft.com/windowsapps/Simple-Communication-Sample-eac73290. If you try to consume the “Microsoft.Samples.SimpleCommunication” component, which is part of the solution, from a Metro-style based C# application, you will have to add a reference to the components winmd-file (“Microsoft.Samples.SimpleCommunication.winmd”). Your C# application will still work fine. However, try to instantiate a class such as StspMediaSink next:

Microsoft.Samples.SimpleCommunication.StspMediaSink k = new Microsoft.Samples.SimpleCommunication.StspMediaSink();

This should produce the following error at compile time:
The type 'Windows.Media.IMediaExtension' is defined in an assembly that is not referenced. You must add a reference to assembly 'Windows.Media, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime'.

Metro-style based C# applications by default reference the WinRT API as a whole. This means that your project references the “Windows.winmd”-file. The problem now is, that the compiler is not smart enough to recognize, that the Windows.Media.IMediaExtension-interface, which is implemented by the StspMediaSink-class, is already defined in the referenced “Windows.winmd”-file. Instead it wants you to add a reference to the same “Assembly”.

You cannot simply go ahead and add a reference to the “Windows.Media.winmd”-file as requested. If you added a reference to Windows.Media.winmd the compiler would complain about ambiguous references to Windows.Media.IMediaExtension. Instead we have to modify the C++ Microsoft.Samples.SimpleCommunication-project in a way that it does not reference the “Windows.Media.winmd”-file anymore, but instead the “Windows.winmd”-file.

This can be achieved by adding the following custom build step to the C++ project:

Command Line: mdmerge -partial -i “$(OutDir).” -o “$(OutDir)Output” -metadata_dir “$(WindowsSDK_MetadataPath)” && copy /y $(OutDir)Output\* $(OutDir)
Outputs: $(OutDir)%(TargetName).winmd
Execute After: Midl

If you recompile the component now, you should be able to reference and consume it from your C# component. If you disassemble the component’s winmd-file, you will notice that it now references “Windows.winmd” and not the “Windows.Media.winmd”-file anymore.

In a future blog post I am going to describe how you can create your own WRL C++ project from scratch as Visual Studio 2011 currently does not ship a project template, unfortunately.

Responding to Incoming Phone Calls on WP7

While working on a Windows Phone 7 application recently, I discovered some limitations of the platform that were rather frustrating.  The application allowed audio to be recorded and played back, and it was expected that recording would pause if an incoming phone call was received on the phone.  The app was already designed to pause recording when the app was deactivated, and initially I thought an incoming phone call would cause deactivation.  I was surprised to discover that it did not.  Instead, the app continued to run uninterrupted while a phone call was taken.  If the app was recording at the time, recording would continue throughout the phone call.  Interestingly, the XNA Microphone class appeared to be muted during the phone call, with that portion of the recording being blank, neither side of the conversation captured.

A little searching confirmed that an incoming phone call does not deactivate a WP7 app.  Instead, the app is “obscured”, and the only way to detect the phone call is by subscribing to the Obscured event of the PhoneApplicationFrame class.  Unfortunately, the Obscured event simply indicates that something from the OS is obscuring the visual of your app (“the shell chrome is covering the frame”, in the words of the MSDN docs), without providing any detail about the source cause.  As a result, many things can cause Obscured to fire, including an incoming phone call, locking of the screen, an incoming text message, a calendar event notification, and a MessageBox.  There are no events fired specific to the different types of OS interruptions that can occur, nor any properties in the ObscuredEventArgs to indicate the source cause.  There is an IsLocked property within ObscuredEventArgs that can be used to detect if locking of the screen caused Obscured to fire, but otherwise no other useful information is given.

This presented a problem for our application, and I could imagine it being a problem for others as well.  In our app we wanted to handle incoming phone calls differently than other types of OS interruptions, such as incoming text messages or calendar event notifications.  The former should pause recording, while the latter should not.  (Pausing recording in response to something as innocuous as a calendar notification would be an awful experience within our app, as the user could easily be unaware recording had stopped, causing potentially important audio to be missed.)

Even the ability to discriminate a screen lock as the source of the Obscured event is of limited value.  We’ve set up our app to continue running (and recording) under lock screen, and at first glance it seems like it would be helpful to ignore the Obscured event if a screen lock was the cause.  Unfortunately, once the screen is obscured, no other OS interruptions fire the Obscured event until the screen is once again unobscured.  Although we did not want to pause recording in response to the lock screen, we did want to pause recording in response to an incoming phone call, including when the screen was locked.  The Obscured event is not fired in response to the incoming phone call if the screen is locked, however.  It would be impossible for us to have consistent behavior both while the screen is locked and unlocked.

As a result of these limitations, we decided to ignore the Obscured event altogether, and simply allow recording to continue while a phone call was taken.  Most users will likely dismiss incoming phone calls while recording, but if they take the call, at least their conversations will not be recorded.  (Instead a blank gap appears in the recorded audio.)  Hopefully future versions of WP7 offer more information about OS interruptions, so apps can respond in an intelligent manner dependent upon the source of the interruption.

Validation and Updating UI Values Based on User Input in MVC 3 Razor

I’m currently working on a project leveraging ASP.NET MVC 3 and the Razor View Engine. Wow, that’s a mouth full! This is some pretty awesome stuff. I’ve been extremely impressed with the capabilities of the framework, and I continue to be impressed the more I use it and learn it.

Remote Validation

One of the coolest features I’ve found in MVC 3 has been remote validation. What is remote validation? It is a way to leverage actions on a controller to validate user input on a model object. To use it you simply apply the RemoteAttribute to the property on your model that will be an input field in a form and specify the action and controller to use. A great example of how this is done can be found here on the msdn. What I like about this is the flexibility to have a validation controller per model on very small projects, or have a dedicated validation controller that calls model validator classes. The controller will only receive the value it should validate so each property should specify a different action on the validation controller regardless of which approach you take. I prefer the model validator approach because it allows me to reuse the validation logic when a form is submitted and I need to do one last validation before the model is persisted.

Updating UI Values Based on User Input

OK, so this sounds very confusing. So let me try to explain what I wanted to do. I have a list of Entry objects and each entry has a property of type EntryDefinition. Some entries are auto generated based on the value chosen for another entry, but all entries are always displayed to the user. If an entry is auto generated it is read only, otherwise it can be modified by the user. I needed a way send values entered by the user to the server, process them and generate the auto generated values, and then display the updated values the user. This was a pain to get working! I discussed the matter with my coworker Kevin Stumpf who has much more experience working in the web world. He helped me get on the right path to solve the matter.

First, was the challenge of getting the values written to the HTML file using Razor. A helpful Stack Overflow post showed me how to render a list of complex objects. Making sure I used Html.HiddenFor for all of the properties that were not displayed to the user took some getting used to. I kept receiving null values on the server side post in my model object and didn’t understand why at first.

Next, I need to get multiple submit buttons on my form. One button for for submitting the form and a new button for sending the model to the server for updating and updating the user’s display. There were a couple of options that I found after reading this post on Stack Overflow. That post linked to this post by Andrey Shchekin, which then led me to the post by David Findley that finally solved the problem best for me. The solution was to set the name property to button for each of the submit buttons. Then set each button’s value property to whatever made sense to the user, in my case “Update” and “Submit.” Then in the action handling the post I add a new parameter of type string named button. This maps to the name of the two buttons. The value the the button parameter will be the value of the button clicked by the user. Now in the action I could check if button equaled “Update” then don’t persist any data, generate any new values and update the model with those values then return View(model) and the user will see the new values and the other values they had input earlier.

After talking more with Kevin he added that I should just hook up to the text changed of the text boxes of the source entries using JQuery then update the auto generated values automatically as the user types. This would be awesome! If there is enough time on the project I will try this.

Conclusion

As I found from my searches there are a ton of articles out there on all this stuff. I just get so excited when I find cool stuff that I like to share. Hopefully something here is useful in your quest!

Declaring Capabilities in WP7 Apps

If you’ve ever created a Windows Phone 7 application, you’re probably aware that before submitting for Marketplace approval you must enable only those “capabilities” that are actually being used.  Capabilities required by your app must be listed in the WMAppManifest.xml file, found in the Projects folder of your UI project.  For new solutions, all capabilities are by default included, as shown below:

	<Capabilities>
	  <Capability Name="ID_CAP_GAMERSERVICES"/>
	  <Capability Name="ID_CAP_IDENTITY_DEVICE"/>
	  <Capability Name="ID_CAP_IDENTITY_USER"/>
	  <Capability Name="ID_CAP_LOCATION"/>
	  <Capability Name="ID_CAP_MEDIALIB"/>
	  <Capability Name="ID_CAP_MICROPHONE"/>
	  <Capability Name="ID_CAP_NETWORKING"/>
	  <Capability Name="ID_CAP_PHONEDIALER"/>
	  <Capability Name="ID_CAP_PUSH_NOTIFICATION"/>
	  <Capability Name="ID_CAP_SENSORS"/>
	  <Capability Name="ID_CAP_WEBBROWSERCOMPONENT"/>
	  <Capability Name="ID_CAP_ISV_CAMERA"/>
	  <Capability Name="ID_CAP_CONTACTS"/>
	  <Capability Name="ID_CAP_APPOINTMENTS"/>
	</Capabilities>

If you include capabilities that are not actually used in your app, your submission to the marketplace will fail.  Fortunately, the Marketplace Test Kit (found via the context menu of the UI project in Visual Studio) can be used to verify what capabilities are required.  The “Capability Validation” result of the “Automated Tests” lists all capabilities used within you app.  The result below shows two capabilities used by an app.

Capabilities

Unfortunately, if you do not declare a capability that your app does actually use, you can easily run into trouble.  The automated tests of the Marketplace Test Kit will list all the capabilities that you make use of, but they will not indicate that you have missed a required capability.  The test will also still indicate a “passed” status, even though you have not declared a required capability.  Instead, functionality within your app can simply break, with no clear indication of the cause.

It’s usually best to leave all of the capabilities listed in the manifest file until you’re near the completion of your development, and then use the Marketplace Test Kit to determine which ones you can remove.  Since this is the typical development process, it’s unusual to encounter a problem.  If you’re starting with existing code, however, this can be the cause of a real headache.  Perhaps you’re returning to a solution you worked on earlier, in order to add new functionality.  Or perhaps you’ve started with a sample solution you came across online, expanding it with additional functionality.  In either case, if you add code that requires a capability no longer included in the manifest, you may end up chasing down bugs that don’t make much sense.

Recently I was exploring the possibilities of recording and playing back audio on WP7.  A quick search led me to a great starting point, in the form of a demo app for a WP7 voice recorder (http://www.codeproject.com/Articles/175122/Making-a-Voice-Recorder-on-Windows-Phone).  That solution uses the Microphone class of the XNA Framework for recording, and the XNA SoundEffect class for playback.  Although the SoundEffect class offers the interesting ability to adjust the pitch of the sound, it does not provide a way to specify the temporal position within the audio file.  I wanted a scrub bar to allow the user to move the playback position arbitrarily.  Switching to a MediaElement for playback would allow me to do this.

After making the appropriate changes, I was disappointed to find playback wasn’t working.  Subscribing to the MediaFailed event of the MediaElement revealed that a failure was occurring as soon as its source was set.  (The error message was the fairly useless “3100 An error has occurred”.)  After much digging around, I finally realized that MediaElement requires another WP7 capability (“ID_CAP_MEDIALIB”), and by introducing it into my project I needed to add the capability to my manifest file as well.

The lesson I learned is that if I’m starting with an existing WP7 solution and plan on making extensive changes, I should first visit the manifest file and make sure all capabilities are included.  This could prevent some serious debugging headaches.  Also, if I encounter bugs that don’t make much sense, it’s a good idea to run the automated tests of the Marketplace Test Kit, and ensure all capabilities listed in the results are included in the manifest file.  Only when I’m close to submitting for approval do I remove unnecessary capabilities from the manifest (and I comment them out, rather than remove them, making it easier to add them all back in if I revisit the code at a later time).

My favorite new features in VS11 Beta

After having a week to work with the new Visual Studio Beta, I’m already missing some of the new features when I need to jump back over to 2010. Here are some of my favorites, in no particular order.

Quick Find

image
This is a frequently highlighted new feature, and I’ve definitely found it useful already as a quick shortcut for getting to almost any function in the IDE. My favorite part of it is that it’s so keyboard focused and allows me to skip reaching for the mouse to do things that I would normally just dig into a menu for. As a longtime SlickRun user, the keyboard shortcut to activate it also feels really natural (SlickRun uses Win+Q, Quick Find is Ctrl+Q) and the fast auto-complete search feels similar too.

Incremental Search feels right again

image
Although much of the new functionality was available previously through the Power Tools, a few of the things that got pulled in finally got that extra polish that makes them just feel right. One of the first Power Tools that I had turned off was the new unified Find box that took over a bunch of different functions and keyboard shortcuts. The big problem I had was the way it handled Ctrl+I incremental search. I use this so frequently that it’s a reflex and there were a few hiccups in keyboard focus that caused me to have to stop and figure out how to get back to the state I wanted to be in in the editor. Now, in the beta, this experience has been smoothed out, and the only noticeable difference from the old Ctrl-I functionality are the new visual cues: the box up top showing what I’ve typed, the extra highlighting of all matches in the current window, but the keyboard experience feels the same, and responds just like I expect.

Navigate To (Ctrl+,)

image
One of the things I miss most when working in a bare instance of Visual Studio that doesn’t have my two favorite extensions installed (CodeRush and ReSharper) is quick keyboard navigation to any type in my solution. The new Navigate To window provides a similar (though not identical) experience, with a search while typing listing of types and members, including camel casing caps shorthand, and instant navigation to the selected item.

Out of process solution load and build

This one is pretty obvious, but I know a lot of work went into this and it’s going to be such a dramatic time and frustration saver. Finally those extra cores are getting used on the big workloads.

TFS Local Workspaces

So many cool things about this, and I’ve only scratched the surface so far, but just the way this has been worked into the UI is really impressive. Like if you need to switch back and forth between Local and Server workspaces, there’s one button to click. Doing a Compare to the workspace version of the file just works the same, but doesn’t need to talk to the server at all, so is much faster. No more worrying about accidentally changing a file from outside VS and getting out of sync – now VS is watching and will pick up the change for you. Just all around a well thought out experience and hits a lot of the big annoyances people have with using TFS source control.

New Diff tool

Finally, the Visual Source Safe compare window is gone. A lot here is similar to other diff tools that you could previously point TFS to for your comparisons, but being built in not only skips that extra configuration, but also gives you the full VS editor. Editing a file right in the compare window with full syntax highlighting, Intellisense, and even instant updates of the compare state feels like magic after so much time spent with the old one. The UI isn’t the only part that’s changed either. TFS auto-merging is much improved too and should cut down dramatically on the number of times you even see the merge window.

Using Fakes for easy unit test stubs and shims in VS11

There are a lot of different ways to do mocking in .NET unit tests, from writing your own mock interface implementations to fully built out commercial frameworks like TypeMock. The Moles Isolation framework from Microsoft Research offered some intriguing possibilities but as a research project has never had the same level of support as a full product. Now the Moles concepts and much of the usage syntax have shown up in the Visual Studio 11 beta renamed as Fakes.

The first step in using Fakes is to add a reference to the new Microsoft.QualityTools.Testing.Fakes assembly in your unit test project. Continue reading

Installing Win8 Consumer Preview on the Samsung 700T

Since September, I’ve been using the Developer Preview version of Windows 8 that came with the Samsung 700T tablets that we got at //BUILD/, but today Microsoft released the next update to Win8 – the Consumer Preview.  Obviously, it came out today, so it’s time to update the device!

I couldn’t find any documentation showing how to upgrade / install the new OS, and heard that upgrades are not supported in these pre-release bits, so I was ready to wipe the device and install clean.  Through trial and error, here’s how I installed the Consumer Preview version.

The plan was to boot from a USB thumb drive that has the contents of the installation media on it.   You’ll see below that it wasn’t the normal “boot from ISO” experience that I’m used to on a desktop PC.

Create Bootable USB Thumb Drive

Most importantly, you can only use a thumb drive that is 4 GB in size. The hardware does not recognize larger drives than that.

Use the Windows 7 USB/DVD download tool to create a bootable USB drive from the .ISO file.  I think this is similar to expanding the contents of the .ISO onto the USB drive, but then it also makes it bootable as well.  As you’ll see below, I didn’t end up actually BOOTING from the USB drive, so making it bootable is probably an extraneous step.

Insert the USB thumb drive into the device.

Enter “BIOS” at Startup

This was new to me.  When the device is powering up, hold down the START button until you see the “Preparing Options” message at the bottom.  IMG_20120229_141943This brings you to what seems to be the equivalent of BIOS options, but with a Win8 layer on top of it running the show (touch works in this UI).

(Excuse the nasty camera pics here – couldn’t take actual screenshots when down in the low level BIOS options.)

Choose TROUBLESHOOT.

Choose ADVANCED OPTIONS.

Choose COMMAND PROMPT.

At this point you will be prompted for account credentials.  This is another area new to me – requiring account credentials on the device at this “low level” before you can go hacking on the system.

IMG_20120229_142049

Command Prompt – Run SETUP

Now you will be at a familiar command prompt, at the X drive (not sure what drive this is).

CD to the D drive, which on my device is the USB thumb drive.  Notice the directory listing is the Win8 Consumer Preview installation software from the ISO.

IMG_20120229_142149

Now from the root of the D drive, run SETUP.  Up comes the first step of the installation…

IMG_20120229_142206

From here, after a couple intro steps, I chose “Custom” installation since I want to wipe my device, not an upgrade, and had to choose a partition…

Crazy List of Partitions

It turns out there are 5 partitions on my device.  The main one where Win8 Developer Preview is installed is Partition 5.  IMG_20120229_142506I deleted that one (drive options, advanced) and installed to that partition.

Finally … we’re on to the “normal” installation of Windows 8…

IMG_20120229_143027

Windows 8 Consumer Preview

Ahh, the start screen…

Tablet Win8 CP - Start Screen

How to use PhoneGap API + iOS, Android

Last blog post I showed how to use PhoneGap’s API with Windows Phone 7. For this blog post, I will use the same web files (HTML and Javascript files) and create an iOS and Android application.

How to setup dev environment?
First thing to get started is visit PhoneGap’s website where they have instructions on how to setup your environment to create an iOS and Android app with PhoneGap. Just select your platform and the instructions will update update on the page for that environment.

After you have your iOS and Android environment setup using Xcode and Eclipse, copy the web files into the “www” folder for each project. Below is a screen shot of the project navigator or package explorer inside Xcode and Eclipse.

Package Explorer in Eclipse for Android Project Navigator in Xcode for iOS

Since I’m reusing the web files, all the code is exactly the same across the Android, iOS and Windows Phone 7 app. So, I’ll just show a few of the pages/screens in the iPhone simulator and Android simulator.

Device Screen (Android) Device Screen (iPhone)
Notification Screen (Android) Notification Screen (iPhone)

Click here to download the iOS example project.
Click here to download the Android example project.

How to use PhoneGap API + WP7

How to get started?

In my previous blog posts I’ve shown how to use PhoneGap with Xcode and Eclipse in targeting iOS and Android platforms. For this blog post, I will show how to use the PhoneGap API with Visual Studio and the Windows Phone 7 emulator as your development environment.

For this sample project, we will also be using JQuery and JQuery Mobile UI.

Now to get started, PhoneGap has documentation on what tools to download and what steps to follow. After you have your development environment setup, you can look over PhoneGap’s API documentation. The API is not to cumbersome and is straight-forward in following for each of the different device hardware. Most of the API involvrs javascript callbacks as I will show below in example code.

For this blog post, I will discuss how to use the following:
1. Device
2. Accelerometer
3. Camera
4. Geolocation
5. Notification

Most of the API methods and objects will exist on most of the major platforms (iOS, Android, WP7). However, some things will be specific on some platforms. Android and WP7 has a search and back button but iOS doesn’t. The menu button only exists on Android. In general, you should be able to use the PhoneGap universally on all platforms. But its good practice to test and run on each device to make sure it works they way you expect.

The sample project was developed fully in Visual Studio and tested with the Windows Phone 7 emulator. The 5 device hardware features that I will interact with using the PhoneGap API is shown on their own phone screen. The examples are very simple to explain how to use the PhoneGap API.

Below is a screen shot of the sample project’s Solution Explorer in Visual Studio. Notice the “www” folder. This folder is created with the PhoneGap project template and where all your web files (HTML, CSS, JavaScript, etc) exist.

Solution Explorer

Before we dive into the API code for each phone screen, I want to mention when using the PhoneGap API you should place your javascript code inside the javascript event OnDeviceReady. If you place your javascript code that calls the PhoneGap API in here, you can guarantee the device is loaded and ready to interact with. Below is the code included in the index.html file.

        <script type="text/javascript">

        document.addEventListener("deviceready", onDeviceReady, false);

        // once the device ready event fires, you can safely do your thing!
        function onDeviceReady()
        {

        }
        </script>

Now lets dive into example code.

Device – Gather device specific information

The HTML and jQuery Mobile UI for the Device screen.

<body>
    <div id="home" data-role="page">
        <div data-role="header">
            <h1>Device</h1>
            <a href="#accelerometerpage" data-icon="add">Next</a>
        </div>
        <div data-role="content">
            PhoneGap Device API
            <!--<a href="#newpage" data-role="button">Second Page</a>
            <br/>-->
            <p id="devicename"></p>
            <p id="devicephonegap"></p>
            <p id="deviceplatform"></p>
            <p id="deviceuuid"></p>
            <p id="deviceversion"></p>
        </div>
    </div>
</body>

The jquery code inside onDeviceReady. The device object is from PhoneGap’s API and its value is added to the innerthtml for each #device element.

        <script type="text/javascript">

        document.addEventListener("deviceready", onDeviceReady, false);

        // once the device ready event fires, you can safely do your thing!
        function onDeviceReady()
        {
            console.log("onDeviceReady. You should see this message in Visual Studio's output window.");

            $('#devicename').html(device.name);
            $('#devicephonegap').html(device.phonegap);
            $('#deviceplatform').html(device.platform);
            $('#deviceuuid').html(device.uuid);
            $('#deviceversion').html(device.version);
        }
    </script>

The HTML and jQuery Mobile UI for the Accelerometer screen.


      <div id="accelerometerpage" data-role="page">
        <div data-role="header">
            <a href="#home" data-icon="back">Back</a>
            <h1>Accelerometer</h1>
            <a id="camerabutton" href="#camerapage" data-icon="add">Next</a>
        </div>
        <div data-role="content">
            PhoneGap Accelerometer API
            <p id="aX"></p>
            <p id="aY"></p>
            <p id="aZ"></p>
            <p id="aTime"></p>
        </div>
    </div>

The jquery code inside onDeviceReady. The navigator object is from PhoneGap’s API. Here the navigator object calls the watchAcceleration method where the first input is the success callback method, the second parameter is the error callback method and the third parameter is the frequency in millisections the success callback method will fire.

var watchId = navigator.accelerometer.watchAcceleration(onAccelSuccess, onError, { frequency: 1000 });

        function onAccelSuccess(a) {
            $('#aX').html(a.x);
            $('#aY').html(a.y);
            $('#aZ').html(a.z);
            $('#aTime').html(a.timestamp);
        }

        function onError() {
            // TODO: write error logic
        }

The HTML and jQuery Mobile UI for the Camera screen. Here we will write to the imageuri the fileURI of the image we capture. It will write out the location and filename of the image.

      <div id="camerapage" data-role="page">
        <div data-role="header">
            <a href="#accelerometerpage" data-icon="back">Back</a>
            <h1>Camera</h1>
            <a href="#geolocationpage" data-icon="add">Next</a>
        </div>
        <div data-role="content">
            PhoneGap Camera API
            <p id="imageuri"></p>
        </div>
    </div>

The jquery code inside onDeviceReady. The navigator object calls camera then the getPicture method. The input parameters are similar to the Accelerometer except the third parameter where we define inline the quality, destinationType and Camera.DestinationType.FILE_URI. The file_uri that is returned in the success callback method will be added to the innerhtml at imageuri.

navigator.camera.getPicture(onCameraSuccess, onError, { quality: 50, destinationType: Camera.DestinationType.FILE_URI });

        function onCameraSuccess(fileUri) {
            $('#imageuri').html(fileUri);
        }

The HTML and jQuery Mobile UI for the Geolocation screen. Similar to the Accelerometer screen, we will write the lat/lon values to the innerhtml.

      <div id="geolocationpage" data-role="page">
        <div data-role="header">
            <a href="#camerapage" data-icon="back">Back</a>
            <h1>Geolocation</h1>
            <a href="#notificationpage" data-icon="add">Next</a>
        </div>
        <div data-role="content">
            PhoneGap Geolocation API
            <p id="lat"></p>
            <p id="lon"></p>
        </div>
    </div>

The jquery code inside onDeviceReady. Here we’re calling the watchPosition of geolocation object and on the success callback method retrieving the lat and lon values.

navigator.geolocation.watchPosition(onGeolocationSuccess, onError, { frequency: 1000 });

        function onGeolocationSuccess(p) {
            $('#lat').html(p.coords.latitude);
            $('#lon').html(p.coords.longitude);
        }

The HTML and jQuery Mobile UI for the Geolocation screen. Here we created an anchor tag that will look like a mobile button that will display a PhoneGap notification alert.


      <div id="notificationpage" data-role="page">
        <div data-role="header">
            <a href="#geolocationpage" data-icon="back">Back</a>
            <h1>Notification</h1>
            <a href="#storagepage" data-icon="add">Next</a>
        </div>
        <div data-role="content">
            PhoneGap Notification API
            <br/>
            <a id="notificationbutton" href="" data-role="button">Click Me!</a>
        </div>
    </div>

The jquery code inside onDeviceReady. Here we use jquery to create a handler for notificationbutton that will call PhoneGap’s API object navigator.notification.alert. When the success callback method is reached it will update the innerhtml text of the button to Clicked.

            $('#notificationbutton').click( function() {
                navigator.notification.alert("You clicked me!", onNotificationSuccess, "Click", "Ok");
            });

        function onNotificationSuccess()
        {
            $('#notificationbutton').html('Clicked');
        }

I hope this helps in getting started with PhoneGap’s API. There is a lot more that can be discussed.

Here is the code for the sample project.

Introduction to Moq Framework

I have been using Moq for a few weeks now for a current project at work. I have looked at other mock frameworks for unit testing and have pleasantly been enjoying Moq. Let me first describe what Moq is.

What is Moq?
Moq is promoted by its creators as easier to learn and use than other Mock Object Frameworks such as Rhino Mocks and TypeMock Isolator. Moq is the only mocking library for .NET developed to take advantage of Linq expression trees and lambda expressions. Thus making it the most productive, type-safe and refactoring-friendly mocking library available.

Moq supports mocking interfaces as well as classes. There are some requirements and limitations on classes. The class can’t be sealed. Also, the method being mocked must be marked as virtual. You cannot mock static methods.

The emphasis on lambdas enables Moq to provide a very clean syntax for representing expectations, parameter constraints, and return values. The name “Moq” comes from a combination of Mock and Linq, even though it truly uses lambdra expressions instead of Linq as you will see below in examples.

Moq uses Castle DynamicProxy internally as the interception mechanism to enable mocking. It’s merged into Moq binaries, so you don’t need to do anything other than referencing Moq.dll.

Moq Features
Moq offers the following features according to Moq’s Google code web site

1. Strong-typed: no strings for expectations, no object-typed return values or constraints
2. Unsurpassed Visual Studio intellisense integration: everything supports full Visual Studio intellisense, from setting expectations, to specifying method call arguments, return values, etc.
3. No Record/Replay idioms to learn. Just construct your mock, set it up, use it and optionally verify calls to it. You may not verify mocks when they act as stubs only, or when you are doing more classic state-based testing by checking returned values from the object under test.
4. Granular control over mock behavior with a simple MockBehavior enumeration. No need to learn what’s the theoretical difference between a mock, a stub, a fake, a dynamic mock, etc.
5. Mock boths interfaces and classes
6. Override expectations: can set default expectations in a fixture setup, and override as need on tests
7. Pass constructor arguments for mocked classes
8. Intercept and raise events on mocks
9. Intuitive support for out/ref arguments

Most of the above features I will demonstrate with example code below.

Now to some code. Assume you have a Product that you want to test against. That Product has an Id and Name and is stored somewhere in a repository. To keep things simple, we will be using Moq and testing against IProduct and IProductRepository.

    public interface IProductRepository
    {
        List<IProduct> Products();
        IProduct GetProduct(int id);
    }

    public interface IProduct
    {
        int Id { get; set; }
        string Name { get; set; }
    }

So, let’s simply mock our Product using Moq. Then assign values to Id and Name properties.

            // Mock a product
            var newProduct = new Mock<IProduct>();

            // stub all properties on a mock
            newProduct.SetupAllProperties();

            // Calls Id property and returns 1
            newProduct.SetupGet(p => p.Id).Returns(1);
            // Calls Name property and returns "Bushmills"
            newProduct.SetupGet(p => p.Name).Returns("Bushmills");

Now lets test the values we expect are actually stored in each of the properties.

            // Tests Id property returns 1
            Assert.AreEqual(newProduct.Object.Id, 1);
            // Tests Name property returns "Bushmills"
            Assert.AreEqual(newProduct.Object.Name, "Bushmills");

            newProduct.Object.Name = "Bushmills";
            // Verify that "Name" property is set with any value
            newProduct.VerifySet(x => x.Name);
            // Verify that "Name" property is set to "Bushmills"
            newProduct.VerifySet(x => x.Name = "Bushmills");
            // Verify that "Name" property starts with "Bush" value
            newProduct.VerifySet(x => x.Name = It.Is<string>(s => s.StartsWith("Bush")));

The above example just touches the surface what Moq can help you in unit testing your code. Next example shows how to verify a method is called in your class and how many times it was called.

Below is what we are using. It’s simply a Order class that you can define with an Id and Total. It has a method WriteMethod that string formats your Id and Total together.

    public class Order
    {
        public int OrderId { get; set; }
        public decimal OrderTotal { get; set; }
        public void WriteOrder(IFileWriter fileWriter)
        {
            fileWriter.WriteLine(String.Format("{0}, {1}", OrderId, OrderTotal)); // formats to "1001, 10.53"
        }
    }

Notice in WriteOrder it has a type IFileWriter as an input parameter. Let’s define that below.

    public interface IFileWriter
    {
        void WriteLine(string line);
    }

Now, let’s start using Moq to test and verify that WriteLine was called in IFileWriter through calling WriteOrder in Order. Confused? Hopefully the code below will make things start clicking. First let’s initialize Order and create a mock for IFileWriter

            // Initialize Order
            Order order = new Order() {OrderId = 1001, OrderTotal = 10.53M};

            // Create a mock with Moq
            Mock<IFileWriter>  mockFileWriter = new Mock<IFileWriter>();

            // Call "WriteOrder" method to format the string
            order.WriteOrder(mockFileWriter.Object);

Now lets use Moq to verify if WriteLine was ever called.

            // verify that the "WriteLine" method was called from the interface with the exact input "1001, 10.53"
            // the lambda expression is not really executing
            // it is being turned into an expression tree and then analyzed by Moq, not actually being executed
            mockFileWriter.Verify(fw => fw.WriteLine("1001, 10.53"), Times.Exactly(1));

            // verify that the "WriteLine" method was called from the interface with any input string
            mockFileWriter.Verify(fw => fw.WriteLine(It.IsAny<string>()), Times.Exactly(1));

            // verify that the "WriteLine" method was called from the interface with  input string that starts with "1"
            mockFileWriter.Verify(fw => fw.WriteLine(It.IsRegex("^1001")), Times.Exactly(1));

            // verify with predicates
            // veirfy that the "WriteLine" method was called from the interface with input string  that is longer than 3 characters
            mockFileWriter.Verify(fw => fw.WriteLine(It.Is<string>(s => s.Length > 3)), Times.Exactly(1));

So far in the above two examples I’ve shown how to verify properties and methods in concrete classes. Now let me show you an example in using Moq to mock a return value for a method signature in an interface. Then using that expected return value in a method to verify a sum. The example below is a TaxProduct that has its price calculated with a Tax Calculator.

    public class TaxProduct
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public decimal RawPrice { get; set; }
        public decimal GetPriceWithTax(ITaxCalculator calculator)
        {
            return calculator.GetTax(RawPrice) + RawPrice;
        }
    }

    public interface ITaxCalculator
    {
        decimal GetTax(decimal rawPrice);
    }

First, lets mock our tax calculator:

            // Initialize our tax product
            TaxProduct tp = new TaxProduct() {ID = 1, Name = "Tax Product 1", RawPrice = 25.0M};

            // Create a mock with Moq
            Mock<ITaxCalculator> fakeTaxCalc = new Mock<ITaxCalculator>();

Now when we call GetTax from our mock object, let’s expect a return value of 5M. Then let’s call GetPricedWithTax and verify that GetTax method was called exactly once.

            // make sure to return 5$ of tax for a 25$ tax product
            fakeTaxCalc.Setup(tax => tax.GetTax(25.0M)).Returns(5.0M);

            // state or behavior verification?
            // retrieve the calculated tax
            decimal calculatedTax = tp.GetPriceWithTax(fakeTaxCalc.Object);

            // verify that the "GetTax" method was called from the interface
            fakeTaxCalc.Verify(tax => tax.GetTax(25.0M), Times.Exactly(1));

Now lets make sure the calculated price equals your product price (25.0M) with tax added (5.0M) which should sum to 30.0M.

            // retrieve the calculated tax
            calculatedTax = tp.GetPriceWithTax(fakeTaxCalc.Object);

            // Make sure that the taxes were calculated
            Assert.AreEqual(calculatedTax, 30.0M);

I hope this helps others with an introduction of using Moq to add code coverage in your projects using unit tests.

Here is a link to all the example code