October 28, 2016 7:13 GMT

The Xamarin Show: Grab a Snack Pack!

Xamarin Show LogoWe launched The Xamarin Show on Channel 9 this past September to provide content for both novice and advanced Xamarin users. Today, we’re excited to showcase the latest that The Xamarin Show has to offer in the form of Snack Packs! A Snack Pack is a bite-sized episode that’s covers a specific topic in just a few minutes. We couldn’t be more excited with the response to The Xamarin Show thus far and are very pleased to feature our collection of Snack Packs!


Snack Pack 1: Android Emulators 

Join James as he explores the various options available to the cross-platform developer for running Android apps within an Emulator, explaining the differences between Hyper-V and HAXM.


Snack Pack 2: iOS Simulators 

Did you know that you can display the iOS Simulator on Windows? James is here to tell us how and to explain the options available on macOS, as well!


Snack Pack 3: Xamarin Test Recorder for macOS 

Testing is a critical stage in the mobile development lifecycle and, with so much variance in device types, size and platforms, a centralized testing strategy is required. In this Snack Pack, join James and Charles Wang as they discuss Xamarin Test Cloud and the Xamarin Test Recorder for macOS.


Subscribe Today

With new episodes posted every week, you don’t want to miss out on any of the great content to come. Be sure to subscribe to The Xamarin Show on Channel 9. We’re always interested in hearing your ideas, so if you have a topic that you think would make an excellent Snack Pack, let James know on Twitter!

The post The Xamarin Show: Grab a Snack Pack! appeared first on Xamarin Blog.

October 28, 2016 1:11 GMT

New SWIFTFramework version 2017.1

New SWIFTFramework version 2017.1 with the latest SWIFT “November” changes is available to download and upgrade. Please check our dedicated site at SWIFTComponents web.

What’s new

  • Latest 2017 specification messages
  • Highly improved performance with up to 3x speed improvement with validation
  • Option to switch off the schema validation making the parsing and basic message creation up to 100x faster
  • Improved licensing mechanism with added RunTime key code setting

  • Happy Coding.

    The post New SWIFTFramework version 2017.1 appeared first on IOS BITS LTD | Mobile application development.

    October 27, 2016 6:34 GMT

    Live Webinar | Scale Your Mobile Quality: Industry Benchmarks and Testing Best Practices

    Join Justin Raczak, Senior Program Manager at Microsoft, for a live webinar on November 10, 2016 at 9 am PST / 12 pm EST / 4 pm GST to learn how organizations everywhere are staying competitive by changing the way they think about mobile development. We’ll provide practical steps on how to evaluate your organization’s mobile practices so you can chart a course to become an industry leader.

    Whether you’re a small startup whose entire business lies within your mobile apps or a large enterprise arming your workforce with productivity tools, the principles of a healthy mobile development culture are the same. Your people, processes, and tools must focus on facilitating continuous learning and rapid iteration as the means to consistently deliver first-class mobile experiences.

    Justin RaczakWe’ve leveraged our experience in the field observing demonstrated best practices to develop a model for thinking about your own mobile practices. Justin will introduce the basics of the index and define characteristics of organizations at various stages of mobile maturity, so you can identify what your organization needs to do to achieve excellence in your mobile efforts. From teams just beginning to explore mobile app testing to those with established test automation practices, all attendees will leave with steps they can take today to begin their journey to mobile excellence.

    Register now to join Justin on November 10, 2016 at 9 am PST / 12 pm EST / 4 pm GST and:

    • Explore why Mobile DevOps is critical to mobile success and how test automation unlocks even more value
    • Benchmark your organization’s quality culture, release cadence, test automation, and device support strategy using the Mobile Maturity Index
    • Learn how Xamarin Test Cloud supports Mobile DevOps and makes it possible to ship high quality mobile experiences faster



    All registrants will receive the recording of the webinar, so we encourage you to sign up even if you can’t join us on the day of the event.

    The post Live Webinar | Scale Your Mobile Quality: Industry Benchmarks and Testing Best Practices appeared first on Xamarin Blog.

    October 26, 2016 6:00 GMT

    Adding the Microsoft Graph to Your Xamarin.Forms Mobile Apps

    The Microsoft Graph provides a unified API endpoint for access to various services like mail, contacts, calendar, files, and more. To help make it as easy as possible to interact with the Microsoft Graph in your mobile apps, Microsoft released the Graph SDK, which wraps these APIs into an easy-to-use SDK.

    In a previous blog post, we walked through building a mobile app that consumed the Microsoft Graph using HttpClient. Today, you’ll learn how to build a mobile app that interacts with the Microsoft Graph using the brand new Microsoft Graph SDK.

    Step 1: Register App

    Previously, developers would need to register their mobile app on the Azure Portal. With the latest update, it’s now possible to register the app at https://apps.dev.microsoft.com. Click on Add an app on the page, give the app a name, and click Create application.


    Once the app has been created, make a note of the App ID. It’s now time to request permissions for both our app and the user. In this sample, we’ll focus on the process of providing permissions to the user.


    Once the application is created, it’s time to give it permissions. There can be permissions for the user as well as for the application. In this sample, we’ll be giving permissions to the user.


    Step 2: Authenticate

    To authenticate the user against Active Directory, we’ll be using the Microsoft Authentication Library (MSAL). Let’s start by declaring the required variables and scopes in our app’s App.cs file.

    public static PublicClientApplication IdentityClientApp = null;
    public static string ClientID = "3b1def2e-5b4e-413d-9a96-b8d8e9776029";
    public static string[] Scopes = {
    public App()
       IdentityClientApp = new PublicClientApplication(ClientID);
       MainPage = new HomePage();

    AuthenticationHelper.cs is a helper class which fetches the AccessToken behind the scene and authorizes the requests.

    graphClient = new GraphServiceClient(
             new DelegateAuthenticationProvider(
             async (requestMessage) =>
                var token = await GetTokenForUserAsync();
                requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", token);
    return graphClient;

    Step 3: Using the Graph API

    Using the Graph SDK is pretty straight forward. The snippet of code below will fetch information about the user, which includes their calendar and contacts.

    var graphClient = AuthenticationHelper.GetAuthenticatedClient();
    var me = await graphClient.Me.Request().GetAsync();
    UserName.Text = me.DisplayName;
    UserRole.Text = me.JobTitle;
    UserOffice.Text = me.OfficeLocation;
    var calendar = await graphClient.Me.Calendar.Events.Request().GetAsync();
    var evnt = calendar.FirstOrDefault();
    EventsTitle.Text = evnt.Subject;
    EventDate.Text = evnt.Start.DateTime.ToString();
    var contacts = await graphClient.Me.Contacts.Request().GetAsync();
    var contact = contacts.FirstOrDefault();
    ContactName.Text = contact.DisplayName;
    ContactEmail.Text = contact.EmailAddresses.FirstOrDefault().Address;

    Remember, as each platform implements the authentication experience differently, using CustomRenderer IPlatformParameters can be passed separately.

    The app will now display the details outlined above when it’s run.

    Wrapping Up

    The Microsoft Graph SDK makes it simple to consume Graph APIs in any .NET application, allowing us to add user data like mail, contacts, calendar, and files to our apps with a single unified API. You can find the fully functional sample used in this blog here and the SDK used is available here

    The post Adding the Microsoft Graph to Your Xamarin.Forms Mobile Apps appeared first on Xamarin Blog.

    October 25, 2016 6:23 GMT

    Kickstart Your Project with Our New Bootstrapped Mobile Apps

    Xamarin makes it fast, easy, and fun to build great mobile apps. Building a mobile app starts in the same place any other project does, with File -> New Project. With that in mind, we’re excited to share new cross-platform mobile apps for iOS, Android, and Windows 10 that will eventually become a part of the File -> New Project experience for Xamarin developers, but that you can use today to bootstrap your own cross-platform mobile app development.

    Your feedback matters

    We’re sharing these projects early so that we can incorporate your feedback into our upcoming templates. If you have ideas for how we can improve the apps, please let us know on the Xamarin Forums.

    We’ll select one random Xamarin community member who leaves feedback to receive a free code for Continuous, a C# and F# IDE for the iPad.

    Connected App Template

    Try Out Bootstrapped Apps Today

    You can try out the apps in just two simple steps:

    1. Download the bootstrapped apps.
    2. Open one of the four bootstrapped apps in Visual Studio.

    Connected Mobile Apps

    Many mobile applications also require cloud backends. The bootstrapped apps launched today also include “connected” versions of the apps that include a preconfigured cloud data storage layer with Azure Mobile Apps, complete with online/offline synchronization and automatic conflict resolution, as well as built-in support for five identity providers: Facebook, Twitter, Google, Microsoft accounts, and Azure Active Directory.

    To try out the connected apps, you’ll need to have the Azure .NET SDK for Visual Studio installed. After that, you can configure cloud data storage and authentication and connect them to your app in just a few lines of code.

    Don’t forget to leave your feedback on the Xamarin Forums fora chance to win a free copy of Continuous! We look forward to hearing your feedback.

    The post Kickstart Your Project with Our New Bootstrapped Mobile Apps appeared first on Xamarin Blog.

    October 21, 2016 7:00 GMT

    Last Xamarin Dev Days of 2016

    Xamarin Dev Days provides an easy way for you to learn mobile development for iOS, Android, and Windows in a free, full-day event complete with introductory sessions, live demos, and a hands-on workshop. We’ve seen a remarkable response from developers looking to dive into mobile development, with over 125 events in more than 40 countries, and sessions in 15+ languages!

    As the year nears it’s end, we’re announcing the last round of events for 2016 and we’ve partnered with our experienced Xamarin MVPs, Microsoft MVPs, and community leaders to help bring Xamarin Dev Days to a town near you. Come learn about the power of building mobile apps with Xamarin and Microsoft Azure with your local developer community, and leave after building your first cloud-connected, cross-platform app to kickstart your next mobile project.


    Last Xamarin Dev Days of 2016!

    The following cities are now officially open for registration:

    Xamarin Dev Days for 2016 are all announced, but don’t worry—there are still over 70 events happening around the world through December! Visit the Xamarin Dev Days website for a full list of cities, or use this interactive map to find an upcoming Xamarin Dev Days near you:

    Want To Support Xamarin Dev Days?

    Xamarin Partners and community members from all over the world are helping to support the Xamarin Dev Days series. If your company is interested in potentially participating in Xamarin Dev Days in the future, you can apply here to be a sponsor.

    The post Last Xamarin Dev Days of 2016 appeared first on Xamarin Blog.

    October 21, 2016 3:27 GMT

    App Shortcuts in Xamarin on Android 7.1

    With the Pixel release, Android 7.1 is upon us and it’s never too early to start playing with some new features!

    Xamarin.Android App Shortcuts in Android 7.1
    Xamarin.Android App Shortcuts in Android 7.1

    One of the features I’ve been looking most forward to is App Shortcuts (previously known as Quickcuts).  This is basically Android’s equivalent to 3D Touch Quick Actions on iOS.

    While technically, the Google Now and Pixel Launcher will only support this feature as of 7.1 and higher, a number of other launchers have already added support for App Shortcuts without the requirement of the latest version of Android.

    According to Google’s official App Shortcut documentation we can create static and dynamic shortcuts.  This post is going to focus on static shortcuts since at the time of writing, we are waiting on a Xamarin update to provide us with the new API’s for creating dynamic shortcuts.

    Static Shortcuts

    Static shortcuts are declared in a resource file and can’t change.  They will always show up the same in your app’s list of shortcuts.  For many apps, this is incredibly useful and will probably be what you primarily use.

    1. Trick the Manifest

    To get started, until Xamarin.Android is updated to support API Level 25, we’re going to have play a small trick on our manifest.

    In the application element of your AndroidManifest.xml change, or add a android:targetSdkVersionattribute to have a value of 25.

    2. Declare your shortcuts

    Static shortcuts are created in an xml resource file.  Typically you’ll create a file: Resources\xml\shortcuts.xml.  The format is pretty simple:

    <?xml version="1.0" encoding="utf-8"?>  
    <shortcuts xmlns:android="http://schemas.android.com/apk/res/android?utm_source=rss&utm_medium=rss">  
          android:targetPackage="com.mypackage" />

    You can declare multiple shortcuts in the same file.

    Your shortcuts can also each include multiple <intent .. /> elements which will be used as the back stack for when your user launches the shortcut.  The last <intent .. /> in the list will be the one the user sees when they launch the shortcut.

    3. Make sure your targetClass is correct

    In case you didn’t already know, by default in Xamarin.Android your activities will have their java generated counterpart code named with a hash prefix (for reasons we are not going to dive into in this post).  This means that figuring out the correct targetClass to use in your shortcut intent declarations may not be as simple or obvious as you would expect.

    Luckily, there’s an easy work around.  In your [Activity] attribute, you can specify the java generated class name explicitly by specifying a Name property.  You’ll need to give it a full package name and class name, for example:

    [Activity (Name="com.mypackage.ShortcutActivity")]
    public class ShortcutActivity : Activity
        // ...

    4. Map the shortcuts.xml to your Main Activity

    Now that you’ve created a shortcuts xml resource file, you need to relate it to your app’s activity which is marked as the Main Launcher.  We can do this by adding a simple MetaData attribute to the activity:

    [MetaData("android.app.shortcuts", Resource = "@xml/shortcuts")]
    [Activity(MainLauncher = true)]
    public class MainActivity : Activity
        // ...

    Now you’re ready to install your app and test out your App Shortcuts!  That’s all there is to it!

    October 20, 2016 7:39 GMT

    Mobile Leaders Podcast | Understanding the Uniqueness of Mobile DevOps with Roy Cornelissen, Xpirit

    roy-cornelissenThis is the second episode in our Mobile Leaders podcast series, focused on helping you achieve success with your mobile initiatives faster through different perspectives and experiences from industry analysts, veterans, and mobile leaders from large and small organizations.

    In today’s episode, join Steve Hall and I as we discuss the hot topic of Mobile DevOps along with special guest Roy Cornelissen. Roy leads the mobile competence at Xpirit, a consulting company focused on Cloud, Mobile, and Application Lifecycle Management based in Netherlands.

    DevOps for mobile apps is unique and more challenging than for web. Device fragmentation, with hundreds of combinations of devices, operating systems, and screen sizes in play, makes it hard to ensure that your apps look, behave, and perform well for all users. Most teams think about getting apps to market and fail to consider the time and costs of maintaining apps and users.

    Subscribe or Download Today

    You can find the Mobile Leaders Podcast on SoundCloud and iTunes to download today’s episode,
    Understanding the Uniqueness of Mobile DevOps with Roy Cornelissen, Xpirit. Don’t forget to subscribe to the podcast for new episodes over the next few weeks!

    You can also listen to our first episode, Enterprise Mobility Trends – Where are things headed? With Maribel Lopez, Founder, Lopez Research here.

    The post Mobile Leaders Podcast | Understanding the Uniqueness of Mobile DevOps with Roy Cornelissen, Xpirit appeared first on Xamarin Blog.

    October 19, 2016 7:58 GMT

    Create a Game with iOS 10 and Message App Extensions

    iMessage App
    With the release of iOS 10, Apple introduced an exciting new feature called Message App Extensions. This new extension type can send text, stickers, media files, as well as interactive messages and integrates with the Messages app, presenting new functionality for users.

    Message App Extensions support different types of content that can be shared. One of the most exciting of these is “Interactive Messages,” which allows you to launch an app from Messages, create custom content, and then use the new Messages Framework APIs to send it in Messages. In this blog post, we’ll explore iMessage App Extensions by creating an interactive game named Monkey Tap.

    Building Your First iMessage App Extension

    Creating an iMessage App Extension is easy! Use the New Project wizard via “File -> New Solution” to start a Single View iOS App. Then, add another New Project to the solution by right clicking it in your Solution Pad. Under the iOS templates, select the Extension menu item and select iMessage Extension. The main difference between this and other extension types is that there is not a “container” app project; instead, the Message app we are creating itself acts as the container.



    Message App Extensions introduce a new type: MSMessagesAppViewController. This acts a lot like what we’re used to, but introduces some message-specific items we need. For example, an MSConversation object is available that represents the conversation we’re in. This is useful so we know where to send a message. We can now create a new controller to handle displaying the score for the game, thereby allowing us to send the score to our recipient as a message.

    public partial class ScoreViewController : MSMessagesAppViewController
    	public override void ViewDidLoad()
    		FinalScoreLabel.Text = string.Format("You scored {0}!", finalScore);
    		// Set up the message layout
    		MSMessageTemplateLayout layout = new MSMessageTemplateLayout()
    			Image = UIImage.FromBundle("Monkey"),
    			Caption = "Try and beat my score!",
    			TrailingCaption = "" + finalScore,
    			Subcaption = "MonkeyTap"
    		// Create a new message with the above layout
    		MSMessage message = new MSMessage()
    			Layout = layout
    		// Send the message when the button is tapped
    		PostScore.TouchUpInside += (sender, e) =>
    			conversation.InsertMessage(message, (Foundation.NSError error) =>
    				if (error == null)
    					// Handle successful send
    				else {
    					// Report Error
    					Console.WriteLine("Error: {0}", error);
    		PlayAgain.TouchUpInside += (sender, e) =>
    			DismissViewController(true, null);

    The interesting parts are still in ViewDidLoad. Here, MSMessage is created and being used to send the score. The Layout property accepts a MSMessageTemplateLayout. The properties handle what’s displayed:

    MSMessageTemplateLayout layout = new MSMessageTemplateLayout()
    	Image = UIImage.FromBundle("Monkey"),
    	Caption = "Try and beat my score!",
    	TrailingCaption = "" + finalScore,
    	Subcaption = "MonkeyTap"

    Here is what our iMessage App Extension looks like:

    We’ll use another controller to handle the the game logic. This will capture any taps from the user and add them as a score.

    public partial class GameViewController : MSMessagesAppViewController
    	public override void ViewDidLoad()
    		// As we are using a UIImageView, we need to detect taps with a UITapGestureRecognizer
    		UITapGestureRecognizer tapGesture = new UITapGestureRecognizer((obj) =>
    			// Game logic
    		gameTimer.Elapsed += (sender, e) =>
    			if (time.Equals(0))
    				// Once we run out of time, stop the timer
    				gameInProgress = false;
    				InvokeOnMainThread(() =>
    					ScoreViewController scoreVC = Storyboard.InstantiateViewController("ScoreVC") as ScoreViewController;
    					// Pass the score and ActiveConversation to the next ViewController
    					scoreVC.finalScore = score;
    					scoreVC.conversation = ActiveConversation;
    					ShowViewController(scoreVC, this);
    					// Reset the labels
    					ScoreLabel.Text = "Tap monkey to begin!";
    					TimerLabel.Text = "Time: 0.0s";


    That’s it! We’ve made a little game where the user can tap on the view and increase their score during the countdown. When it’s over, we compose a message to send to our recipient. This is where the MSConversation comes in handy.

    conversation.InsertMessage(message, (Foundation.NSError error) =>
    	if (error == null)
    		// Handle successful send
    	else {
    		// Report Error
    		Console.WriteLine("Error: {0}", error);

    We’ve Only Scratched the Surface

    We’ve just touched on some of what’s possible with these new extensions. If you’d like to learn more about this topic, check out the documentation. You’ll find more information about other available APIs, learn about Sticker Packs, group conversations, and more. You can browse the entire source code for the Monkey Tap project in this post.

    The post Create a Game with iOS 10 and Message App Extensions appeared first on Xamarin Blog.

    October 18, 2016 6:37 GMT

    Xamarin.Forms Book Now Available in Easy to Digest Chapter Summaries

    Creating Mobile Apps with Xamarin.FormsPeople learn in different ways. Some people like to learn a new API framework by reading a big book; for those people I’ve written Creating Mobile Apps with Xamarin.Forms with 28 chapters available as a free download to help you to get started building mobile apps for iOS, Android, and Windows today.

    Other programmers—particularly those who have experience with similar frameworks—might prefer to accelerate the learning process. Generally, these folks can get much of what they need from API documentation and sample code; they don’t need massive books.

    For this group of future Xamarin.Forms developers, I’ve written a summary (or abstract) of sorts for each chapter of the book. Each summary describes what’s in the corresponding chapter and contains links to the documentation for each of the APIs described in the chapter, links to the sample code from that chapter, links to related Xamarin.Forms guides, and a link to the full chapter itself.

    These summaries allow you to learn Xamarin.Forms in a structured, brick-by-brick manner and a minimal amount of reading. You can also use the summaries to check if a particular chapter has information that you might need before consulting the full chapter for a more detailed exposition.

    You’ll find the links to these summaries on the web page for the book. Each listed chapter (such as Navigation and MVVM) has links to both the full text in a PDF file and to the summary page. The summaries are also listed on their own page.

    Consuming a 1,200-page Petzold book has never been easier and neither has learning Xamarin.Forms!

    The post Xamarin.Forms Book Now Available in Easy to Digest Chapter Summaries appeared first on Xamarin Blog.

    October 18, 2016 2:32 GMT

    Getting Started With Serverless and TypeScript

    If you're doing any "serverless" development on AWS Lambda, you should definitely check out the similarly named Serverless framework. Serverless makes it much easier to build manageable applications with this sort of architecture, taking away a lot of the painful things you would otherwise need to manage and automate yourself.

    As you write these event-driven systems, a lot of your functions end up looking like data pipelines - your function receives some input, processes or transforms it as appropriate, and outputs something that might be consumed by a user or even another function. These functional, stateless systems really benefit from having some static type checking, which is where TypeScript can really shine. In this post I'll show how to get started writing a basic Serverless application using TypeScript, and even layer in things like linting and testing that you'd ultimately want in any real application.

    Initial Project Setup

    If you don't already have Serverless installed, go ahead and do so via NPM:

    npm install serverless -g  

    Once that is installed you will be able to use the serverless command (or optionally sls or slss as shorthand) to invoke different commands for the framework. To start, let's create a new Node app:

    sls create -t aws-nodejs  

    This will create a few files for you:

    • handler.js: the function's implementation
    • serverless.yml: the function's configuration
    • event.json: sample function input for local testing

    This is obviously a JavaScript implementation, so now we can start replacing it with TypeScript. First, go ahead and install a few NPM packages:

    npm i --save-dev typescript webpack ts-loader serverless-webpack  

    If you're familiar with using Webpack on other platforms, such as the web where it's most common, then this should feel pretty familiar. Serverless provides a nice extensibility model, which helps enable us to leverage the same Webpack model we use elsewhere. Next, create a webpack.config.js file to configure Webpack:

    var path = require('path');
    module.exports = {  
      entry: './handler.ts',
      target: 'node',
      module: {
        loaders: [
          { test: /\.ts(x?)$/, loader: 'ts-loader' }
      resolve: {
        extensions: ['.ts', '.js', '.tsx', '.jsx', '']
      output: {
        libraryTarget: 'commonjs',
        path: path.join(__dirname, '.webpack'),
        filename: 'handler.js'

    This is boilerplate Webpack, passing TypeScript files through the TypeScript compiler and outputting a JavaScript file. We can also add a tsconfig.json file to configure TypeScript:

      "compilerOptions": {
        "target": "es5",
        "module": "commonjs"
      "exclude": [

    With that ready to go, let's update serverless.yml:

    service: serverless-typescript-demo
      name: aws
      runtime: nodejs4.3
      - serverless-webpack
        handler: handler.hello
         - http:
             path: hello
             method: get

    There are a few things going on in here:

    • service defines the name for this service
    • plugins defines the plugins we want to use, which in our case is the Webpack plugin
    • functions lists out all functions for this service
    • hello is defined as a function, specifies its handler method, and also connects a GET /hello HTTP endpoint to the function

    With the plugin added, running the serverless command will now show you a few new commands added by the Webpack plugin. Before we do that, the last thing we need to do is create the TypeScript version of the handler. Rename handler.js to handler.ts, and replace the contents with:

    export function hello(event, context, callback) {  
      callback(null, { 
        message: 'Hello from TypeScript!', 

    The function's handler receives three parameters here:

    • event: the payload for the event that triggered the function
    • context: information about the context in which the function is running
    • callback: a callback that must be invoked by the function to say that the function has completed, and also specify success or failure

    In this case we simply return a successful invocation, where the response payload contains a message string and also relays the event that it received.

    You can go ahead and run this locally by running:

    sls webpack invoke -f hello -p event.json  

    Go ahead and replace the default contents of event.json with something that matches the API Gateway event format:

      "method": "GET",
      "headers": {
        "host": "localhost:8000",
        "user-agent": "curl/7.49.1",
        "accept": "*/*"
      "body": {},
      "path": {},
      "query": {
        "foo": "bar"

    You can also simulate API Gateway locally by running:

    sls webpack serve  

    This will allow you to hit http://localhost:8000/hello to trigger your function. If you run sls deploy Serverless will deploy your function out to AWS and provide you with the endpoint that you can hit there as well.

    Add Some Types

    That's all well and good, but technically everything there was untyped. Let's go ahead and add some basic types here in a new file named models.ts:

    export interface IResponsePayload {  
      message: string;
      event: any;
    export interface IQueryParameters {  
      foo: string;
    export interface IEventPayload {  
      method: string;
      query: IQueryParameters;
    export interface ICallback {  
      (error: any, result: IResponsePayload): void;

    Now we have some really basic types around the function's input and output, so let's update the handler to take advantage of that:

    import { ICallback, IEventPayload } from './models';
    export function hello(event: IEventPayload, context, callback: ICallback) {  
      callback(undefined, {
        message: `Method: ${event.method}, Param: ${event.query.foo}`,
        event: event

    If you go ahead and invoke the function again you should see basically the same output as before, except that the message will reflect what you provide via the query string ?foo=. If you tweak the format string for message to try and use event.query.bar, you'll see the TypeScript compile step fail, just the way we want. These are obviously trivial types, but as you start to build out larger systems that deal with real events and data, these types can save you from a lot of mistakes that are otherwise easy to make.

    Add Linting

    If you're like me, you like to make sure you have some linting rules set up for all your JavaScript and TypeScript projects. In the spirit of setting this up like a real world project, let's layer that in. For this example I'll use the TSLint config we use at Olo:

    npm i --save-dev tslint tslint-config-olo  

    We can add a tslint.json file to specify we'd like to use this config:

      "extends": "tslint-config-olo"

    Finally, we'll add an NPM command named lint in package.json to run TSLint:

    "scripts": {
      "lint": "tslint *.ts"

    Now you can run npm run lint to lint all the TypeScript files in the current folder.

    Add Tests

    Finally, no application is complete without some tests, so let's set some up. You're welcome to use your favorite testing frameworks, of course, but for this example I'm going to use Karma, Mocha, and Chai:

    npm i --save-dev mocha chai karma karma-typescript-preprocessor2 karma-webpack karma-chai karma-mocha phantomjs-prebuilt karma-phantomjs-launcher  

    Next, go ahead and create karma.conf.js which will configure the test runner and Webpack:

    var webpackConfig = require('./webpack.config');
    module.exports = function(config) {  
        basePath: '',
        frameworks: ['mocha', 'chai'],
        files: ['tests.ts'],
        preprocessors: {
          'tests.ts': ['webpack']
        webpack: {
          module: webpackConfig.module,
          resolve: webpackConfig.resolve
        reporters: ['progress'],
        colors: true,
        logLevel: config.LOG_INFO,
        browsers: ['PhantomJS'],
        singleRun: true

    We can also install some typings for Mocha and Chai:

    typings i --save dt~mocha --global  
    typings i --save chai  

    Next, let's add another NPM command to run the tests:

    "scripts": {
      "test": "karma start"

    Finally, we can add a basic test file named tests.ts:

    import { hello } from './handler';  
    import * as chai from 'chai';  
    const expect = chai.expect;
    describe('hello function', () => {  
      it('processes the query string', done => {
        const requestEvent = {
          method: 'GET',
          query: {
              foo: 'bar'
        hello(requestEvent, {}, (err, result) => {
          expect(result.message).to.equal('Method: GET, Param: bar');

    Now if you run npm run test you should see one successful test.


    This only scratches the surface of what you can do with Serverless, especially when paired with TypeScript, but hopefully you can start to see the potential here. Admittedly the linting and testing pieces are somewhat tangential here, but I really wanted to show how easy it is to get started building out a real-world application on top of Serverless while being able to leverage modern technologies like TypeScript and Webpack. The full source for this example is available on GitHub.

    October 13, 2016 5:53 GMT

    Live Webinar | Xamarin University Presents: Introduction to Xamarin with Visual Studio

    It’s an exciting time to be a mobile developer—there are many new technologies to learn and take advantage of, and the types of applications we can build today are incredible. From immersive augmented reality experiences such as Pokémon GO to always-connected social media and news, our mobile devices have truly become the central hub of our lives.

    Kym PhillpottsIf you’ve been wondering how to get that great idea out of your head and onto your phone, we’ve got the starting place for you. Join us October 27 at 11:00 am PT / 2 pm ET / 6 pm GMT when Kym Phillpotts from Xamarin University will take you on a tour of how to build and test your first application with Xamarin for Visual Studio.

    Xamarin for Visual Studio lets you leverage Visual Studio, the power of C#, and the .NET framework to create, debug, test, and deploy native applications for mobile devices including your phone or tablet, the watch on your wrist, and even the big screen TV in your living room.

    Learn how to structure your code so you can maximize code sharing between platforms and use Xamarin.Android, Xamarin.iOS, and Xamarin.Froms to create fully native mobile apps. Along the way, you’ll see some of Xamarin for Visual Studio’s amazing tools, including GUI designers and the new XAML Previewer for Xamarin.Forms. You’ll also learn how to easily connect to Microsoft Azure’s powerful backend services to give your apps critical mobile capabilities, like push notifications, user authentication, storage, and more.

    With these skills in hand, you’ll be able to translate your great idea into an extraordinary mobile app. Whether it’s a simple tool to make your own life easier, or the next big thing in the App Store, sign up below to join Kym on October 27 at 11 am PT / 2 pm ET / 6 pm GMT to start building amazing mobile apps today!


    All registrants will receive the recording of the webinar, so we encourage you to sign up even if you can’t join us on the day of the event.

    The post Live Webinar | Xamarin University Presents: Introduction to Xamarin with Visual Studio appeared first on Xamarin Blog.

    October 12, 2016 8:11 GMT

    Understanding Android’s Doze Functionality

    The Android operating system enables developers to create complex applications that take advantage of background services, alarm scheduling, and data synchronization. With users downloading more apps than ever, it’s important that these mass amounts of apps don’t slow down and drain the users batteries, which is why Google introduced Doze in Android Marshmallow and expanded it’s reach in Android Nougat.

    When Devices Doze

    BatteryJust like the name implies, Doze kicks in when a user’s device is unplugged from a power supply and the handset isn’t being used. Previously, Doze would only occur when the device was stationary for a set amount of time with the screen off, but with the release of Android 7.0, Doze has several states that can occur even if the device is not stationary.

    Doze Level 1

    In Android 7.0, Doze can occur any time the device is on battery and the screen is off. After a certain amount of time, applications will cease to have network access and all syncs and background jobs will be deferred to a maintenance window that Android determines. Normal operation resumes as soon as the user plugs in their phone to charge or turns on the screen. Here’s an illustration of Android 7.0’s Doze Level 1:


    Doze Level 2

    If the device remains stationary or is already in Level 1 Doze and becomes stationary, Level 2 will begin and start additional restrictions. Level 2 is the standard Doze from Android Marshmallow, which ignores all wakelocks, defers all alarms, syncs, and jobs, and restricts network access, GPS, and Wi-Fi scans.

    The system will wake and allow applications to perform normal operations at specific intervals in all levels of Doze. If your application is using any of these restricted APIs, it’s important to realize that your app may not perform actions when you thought it would and that Doze should be tested for. The one important thing to remember with Doze is that there is one loophole when it comes to push notifications and Google Cloud Messaging—any push notifications marked “High Priority” will still come through when Doze is occurring.

    Testing for Doze

    You can easily test for Doze mode to make sure you app is acting correctly when testing on a device or emulator running Android 6.0 (API Level 23) or higher. Simply run your application, leave it active, and shut off the device screen (ensuring the app remains active). You don’t need to wait for Doze to kick in; you can force Doze via the ADB command prompt with two simple commands:

    $ adb shell dumpsys battery unplug
    $ adb shell dumpsys deviceidle step

    You can run the second command multiple times to continue cycling through Doze modes to fully ensure your app is responding correctly when in and out of Doze mode.

    Critical Alarms

    Manyn apps may be using the AlarmManager to schedule events such as calendar notifications. To help manage this, there have been two new methods added to the AlarmManager in API 23: SetAndAllowWhileIdle and SetExactAndAllowWhileIdle. They are very similar, but the SetExact will ensure the alarm goes off at the exact time requested instead of a window. These alarms should be used sparingly and are still restricted to firing just once every 9 minutes per app.

    Take Advantage of Job Scheduler

    The new Job Scheduler API introduced in Android 5.0, now part of Google Play services as GcmNetworkManager, enables developers to schedule background tasks and allow Android to correctly run them when it can batch multiple tasks together for efficiency and battery savings, making it great for one-off or periodic tasks. You can learn more about the Job Scheduler in our samples and in the GcmNetworkManager blog on data refresh.

    Learn more

    Google has provided great documentation on how to fully optimize apps for Doze, including many of the tips I’ve provided here plus several more. Additionally, be sure to read about all of the API changes in Android N, including the updates to Doze and how it can effect apps.

    The post Understanding Android’s Doze Functionality appeared first on Xamarin Blog.

    October 12, 2016 3:34 GMT

    Smoky Mountain Boys and Girls Club Charity Golf Event

    On October 5th, we ran the Smoky Mountain Boys and Girls Club Charity Golf Event.  This was using our golf scoring application.  The application is built on Microsoft Azure and uses Xamarin for some of the club management pieces, such as picture taking (Note the picture shown in the scoreboard below)., C#, ASP .NET Web Pages, Entity Framework, jQuery, and other various software tools  The event had 65 teams spread across two courses (River Course and Highlands Course at the Sevierville Golf Club).  Originally, there were 67 teams, however 2 did not show.  The system will allow teams to be entered, grouped together, flighted, etc.  There are two key items for the event:
    • Additional sources of revenue.  The scoreboard & scorecard provides for sponsorship placement.  Notice in the picture the three sponsors in the header.
    • The amount of time saved in team scoring, totaling, breaking ties, flighting, and etc. that occur after the event.  On an event this size, these typically take 1-1.5 hours and are prone to human error.

    Does your charity have a golf event that it wants to take to the next level?

    October 11, 2016 10:39 GMT


    Short story
    When using MVVM as the pattern of choice for your app, make sure to use PropertyChanged.Fody to make your life a little easier. 
    1. Install the nuget-package PropertyChanged.Fody
    2. If using Xamarin studio, edit the Weavers.xml file in the root and add <PropertyChanged>. This is done automatically in Visual Studio.
    3. Create a base class for ViewModels and decorate it with the [ImplementPropertyChanged]attribute
    4. All your properties will be raising the PropertyChanged event on INotifyPropertyChanged.
    Long story
    MVVM heavily relies on ViewModels that implement INotifyPropertyChanged. This is the way that the View will be aware of changes in the ViewModel and what triggers UI-updates when you change a ViewModel property.

    Before PropertyChanged.Fody

    The usual way to tackle this is to implement the INotifyPropertyChanged your self. INotifyPropertyChanged only defines one event called PropertyChanged. This event is what the view hooks up to in order to listen to the ViewModel. No magic at all going on here.
    So what we do is that we implement that interface and add a method to raise it in a simple way.
    using System.ComponentModel; // The definition lives here

    public class MyViewModel : INotifyPropertyChanged
    // The only thing INotifyPropertyChanged defines
    public event PropertyChangedEventHandler PropertyChanged;

    // Helper method to raise the event
    protected void RaisePropertyChanged(string propertyName)
    if (PropertyChanged != null)
    PropertyChanged(this, new PropertyChangedEventArgs(propertyName));

    // And a property with a backing field
    private string _name;
    public string Name
    return _name;
    _name = value;
    That is alot of code for a single property. What if we could get rid of most of that? 

    After PropertyChanged.Fody

    Enter PropertyChanged.Fody!
    To install, do this:
    1. Install the nuget-package PropertyChanged.Fody
    2. If using Xamarin studio, edit the Weavers.xml file in the root and add <PropertyChanged>. This is done automatically in Visual Studio.
    After installing the nuget package, rewrite the code above to look like this.
    public class MyViewModel
    public string Name {get; set; }

    Can we make it better

    Yes, create a base class for your ViewModels and decorate that one with the ImplementPropertyChanged attribute. Then you can forget about it.

    How does it work

    Fody is an IL-weaver. It modifies the IL code generated by the compiler and implements the interface for you.


    Make sure to check out the official documentation at https://github.com/Fody/PropertyChanged
    October 11, 2016 10:27 GMT

    3D Touch your Xamarin(.Forms) app: apply pressure to icon area

    Now that I have got a new iPhone 7 that supports 3D Touch it’s about time to have a play with that!

    In case you have missed it, 3D Touch (or Force Touch) is a concept that Apple introduced with the iPhone 6s (Plus) and iOS 9. It lets you press the screen a bit harder which enables you, as a developer, to act on it.

    Already incorporated in iOS you can now use it to show the user some previews of content without navigating to it, but mostly it is used in some shortcut menu on the iOS main screen. When you 3D Touch an app icon you’ll probably see some menu options to navigate to somewhere in the app directly. With the introduction of iOS 10 it also shows you the widget associated with your app, we will look at that as well in a following post.

    This menu is really easy to implement in your own Xamarin (and Xamarin.Forms!) app, that is what we will be looking at in this post!

    The possibilities

    You can use the 3D Touch for you app icon in a few ways. The first and foremost is just to show a static menu which acts as a shortcut menu. When the user clicks one it automatically focusses the search field or goes to the right tab or screen. It can also be used more dynamically, for instance to show some recent played songs on your favourite music app. You can either use the default icons that Apple supplies for you, but you can also use your own icons. This is known as the Quick Actions and is what we will be looking at in this post.

    Other features that can be done now are Peek and Pop and Pressure Sensitivity. The first allows you to show some kind of preview of content. Think of a Facebook post which you give a little pressure and you get a preview of the linked content behind it. If you press further you will navigate to the full content.

    The Pressure Sensitivity provides you with information about how hard the user is pressing the screen. With this information you could draw a thicker line while drawing for instance.

    In-depth documentation of all you can do with this can be found in the Xamarin documentation

    Configuring your Quick Actions

    The first thing you need to do to implement this is think about what menu options you would like to show. You can do anything you want! But it’s probably best if it does something meaningful.

    For an app I’ve been building at our company to file expense claims I wanted to implement this. The interface is a list of previous claims and a button to add a new one. So I thought to myself: “why not add a new claim right from the app icon?”. So I wanted to create a Quick Action to go to the new screen immediately.

    The first thing you need to do is specify your actions in the info.plist file like this:

            <string>Declaratie toevoegen</string>

    There are a few things going on here, I will go over them by the key names:

    • With the UIApplicationShortcutItemIconType you can set the icon for your action. There is a whole list of built-in options you can use, as found here. These will cover the most scenarios. However if you want to use a custom icon, replace this with the UIApplicationShortcutItemIconFile key and set the string value to the filename in your resources without the extension. So if you have a ‘myawesomeicon.png’ in your resources, set the string value to ‘myawesomeicon’. Also keep in mind that the file needs to be a PNG, square 35×35 pixels, single color.
      Note that you still need to add the UIApplicationShortcutItemIconType key as it is required. However when you add the UIApplicationShortcutItemIconFile the IconType key will be ignored.
    • UIApplicationShortcutItemSubtitle is an optional key. If you put something here it will be shown in a smaller font below the UIApplicationShortcutItemTitle key value. The subtitle key isn’t used a lot by popular apps.
    • With the UIApplicationShortcutItemTitle key you specify the caption of your action. Keep this short and meaningful, i.e. ‘Add this’, ‘Search’, etc. FYI for the non Dutch speakers, this one says: “Add expense claim”
    • Last but not least there is the UIApplicationShortcutItemType key. This one is also required and identifies the option that the user has chosen. It can be anything as long as it is unique. A common pattern is the app ID with a suffix, incrementing number

    With adding this in our info.plist and deploying it we can already see our action popping up. It just doesn’t do anything yet.

    Our Quick Actions menu
    Our Quick Actions menu

    If you want to test this kind of behaviour you’re going to either need a MacBook pro with 3D touch on the touch pad or a iPhone that supports it. Although the Simulator does have menu options to simulate a deep press they don’t seem to be implemented.

    Implementing the Quick Action in code

    So now our menu is ready, let’s implement some logic in it. If you are using Xamarin.Forms you have to go in you iOS project since this is very specific iOS stuff.

    Although not strictly necessary, you probably want to put your shortcut identifiers in some static class for easier use. So create a ‘ShortcutIdentifier’ static class in you iOS project and implement it something like this:

    public static class ShortcutIdentifier
        public const string First = "com.company.appname.000";
        public const string Second = "com.company.appname.001";
        public const string Third = "com.company.appname.002";
        public const string Fourth = "com.company.appname.003";

    Of course the names could be more meaningful.. In my case it would look like this:

    public static class ShortcutIdentifier
        public const string AddExpenseClaim = "nl.kembit.expenseclaim.ios.000";

    Just make sure the string values correspond with the ones in your info.plist file.

    From here there are a few ways to go about this, which is mainly dependent on how your architecture looks like and what action you are after to implement. I have implemented my functionality with the MessagingCenter. Although I’m not a big fan of using it a lot, it did the trick for what I was trying to do without having to overhaul a lot of things. For more info on how to (not) use is, check out this article by Adam Pedley.

    But first things first, I opened up my AppDelegate.cs because that is the main entry point for our app so there we have to determine if our user has tapped a shortcut.

    First we’ll add a couple of things that aren’t there yet.

    public partial class AppDelegate : FormsApplicationDelegate
        public bool HandleShortcutItem(UIApplicationShortcutItem shortcutItem)
            var handled = false;
            // Anything to process?
            if (shortcutItem == null) return false;
            // Take action based on the shortcut type
            switch (shortcutItem.Type)
                case ShortcutIdentifier.AddExpenseClaim:
                    MessagingCenter.Send(App.Instance, "GoToNewExpenseClaim");
                    handled = true;
            // Return results
            return handled;
        public override void PerformActionForShortcutItem(UIApplication application, UIApplicationShortcutItem shortcutItem, UIOperationHandler completionHandler)
            // Perform action
        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
            // ... There probably is some stuff in here already

    With the comments in place it should be pretty straight forward.

    Basically we override the PerformActionForShortcutItem to get notified when a Quick Action needs to be handled and we can supply a method to handle it.
    Within that method we check which shortcut it was with the static class we made earlier and handle it accordingly. In my case I will send out a message.

    Now in the PageModel of my main screen I subscribe to the message…

    MessagingCenter.Subscribe<App>(this, "GoToNewExpenseClaim", NavigateToNewItemFromShortcut);

    And handle what it should do

    private async void NavigateToNewItemFromShortcut(App app)
        // Pop everything first so we don't get the same page multiple times on the stack
        await CoreMethods.PopToRoot(false);
        // Execute the new command

    There is some FreshMvvm stuff in here because that is the framework I used for this app. Basically it pops any other pages so we don’t get any weird navigationstack behaviour and then we execute the command for adding a new claim which was already there.

    And that is it! When I now launch from the Quick Action menu I get the add new item screen immediately like I wanted to and gained a few precious milliseconds today!

    Let me know what you think or what you like to see. I plan to add a widget after this next.

    Also I’d love to see some good original uses for the Quick Actions and deep press functionality. So hit me up on Twitter!

    October 01, 2016 12:00 GMT

    Leveraging Azure Functions for MIT AppInventor Web Interactions

    I’m contributing a few hours a week on Fridays to tutor kids on programming and a bit of electronics, in what we call a “Geeks’ School” (or Escuela de Geeks). I’m always exploring ways to make it more interesting for kids (12-16yo) to learn programming. I found out that given that the cellphone (mostly Androids here in Argentina) is their primary computing device, they were instantly hooked to the MIT AppInventor 2 platform.

    We’re actually using Thunkable, a fork of the original MIT AI2 that provides a nicer Material Design UI and sleeker looking client/companion app for the device. Kids have even interacted via chat directly with the site owners, which was a blast!

    One of the kids wanted to build a translating app that would:

    1. Accept spoken spanish input
    2. Recognize the text and send it to a web api for translation
    3. Get the translated text and have the app speak it out loud

    The speech recognition and text-to-speech parts were very straightforward involving just a couple built-in blocks with simple input-output connectors:

    speech recognition block and text-to-speech

    Plugging a Web component in-between the recognized (Spanish in this case) text in when speech.After Getting Text and the call to call tts.Speak proved quite challenging. To be clear, invoking web services by issuing POSTs and GETs is as easy as anything else: just drop the non-visual Web component on the designer and just call it from the blocks view. That’s the easy part. But the key thing in invoking web services is processing its output, of course ;)

    Most web APIs nowadays return plain JSON, and a quick search around the web for how to parse and consume JSON from an app yielded some very scary looking massive amount of blocks for something that is just a couple lines of code in any modern programming language.

    Azure Functions to the rescue

    So I remembered the Build Conference introduction of Azure Functions and chatting with the team at their booth, as well as Scott’s great introduction to Serverless Computing and this seemed like the perfect opportunity to give it a shot.

    In short, what I wanted was a way to get a single JSON property value from the response of Google’s translate API. The request looks like the following:


    And the response:

        "data": {
            "translations": [
                    "translatedText": "Hello"

    It takes literally ONE line of code to retrieve the translatedText using Json.NET:

    var result = JObject.Parse(json).SelectToken("data.translations[0].translatedText")

    So I went to http://functions.azure.com (love the customized subdomain, as opposed to navigating the seemingly endless features of Azure in the portal) and created a new “Function app”.

    NOTE: the “function app” is the actual Web API ‘site lite’ that will host the actual function (or functions). So if you name it like your function, i.e. parsejson then define the parsejson function, the resulting URL will look slightly awkward: https://parsejson.azurewebsites.net/api/parsejson

    In my case I went for stringify for the function app name, and json for the function name, which results in a nice looking url https://stringify.azurewebsites.net/api/json

    I started directly with from the Or create your own custom function link at the bottom of the wizard, and chose the HttpTrigger - C# template. Then I wrote the code in a window without any intellisense (I hope that changes soon ;)) but it was dead-simple. The whole function that takes POSTed JSON bodies and a “q=[JSON PATH]” argument for stringifying it is:

    #r "Newtonsoft.Json"
    using System.Net;
    using Newtonsoft.Json.Linq;
    public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
        var query = req.GetQueryNameValuePairs()
            .FirstOrDefault(q => string.Compare(q.Key, "q", true) == 0)
        var json = await req.Content.ReadAsStringAsync();
        return string.IsNullOrEmpty(json) || string.IsNullOrEmpty(query) ?
            req.CreateResponse(HttpStatusCode.OK, "") :
            req.CreateResponse(HttpStatusCode.OK, JObject.Parse(json).SelectToken(query).ToString());

    And of course you can try it out simply from curl:

    curl -k -X POST -d "{\"data\":{\"translations\":[{\"translatedText\":\"Hello\"}]}}" https://stringify.azurewebsites.net/api/json?q=data.translations\[0\].translatedText

    A whole speech to text translation app in less than 20 blocks

    And with that, suddenly, interacting with the Web from MIT AppInventor2 or Thunkable is super straight-forward. The whole program is easy to grasp by any 12yo+ kid:

    1. When the button is clicked, start listening for speech: Listen for speech
    2. When speech is recognized, ship it off for translation: Translate recognized speech
    3. When translation JSON comes back, ship it off for “stringifying”: Parse JSON
    4. When the simple string comes back from “stringify”, speak it out loud: Parse JSON

    It would have taken that many blocks or more just to parse the JSON response from the translation Web API. A massive improvement by just using a little bit of serverless computing to aid in teaching :)

    For other teachers leveraging MIT AppInventor for the Web, here’s the “documentation”:

    1. Set the stringify Web component’s URL to https://stringify.azurewebsites.net/api/json
    2. Append the path of the JSON value to retrieve as the query string parameter, like ?q=data.translations[0].translatedText
    3. Use a POST Text call passing in the JSON to parse.

    NOTE: if you are dealing with a single JSON web response format, the URL of the stringify Web component can be set statically in the Designer pane and never changed from blocks, as shown in the above translation example.

    I look forward to using Azure Functions a whole lot more. For one, I think I’ll expand the stringify Azure Fuction app to include an xml and possibly html functions receiving an XPath expression as the ?q= query string parameter.

    September 30, 2016 12:00 GMT

    How to nuke the Visual Studio MEF component model cache from an MSI

    A quick search on the web for InvalidMEFCacheException will yield quite a few results. If you have faced it, you know it’s annoying like hell.

    I wonder, if VS already detected its cache is invalid, why doesn’t it auto-nuke it and offer a quick Restart action?

    Two very common ways you can corrupt the MEF cache are:

    1. Improperly include VS assemblies that provide MEF components in your extension
    2. Providing different versions of your own assemblies that provide MEF components in different extensions

    The first issue can be solved easily by installing the Microsoft.VisualStudio.SDK.VsixSuppression nuget package into your project. Sometimes some assemblies are missing from the suppression, but the team is super responsive and will ship an updated nuget package the moment you report the missing suppression in their gitter chat. That’s one of the many benefits of shipping granular nuget packages out of band :).

    If you want to be 100% future-proof, you can add this target to your VSIX project and be sure that no missing assemblies ever go into your VSIX:

    <Target Name="ExcludeVisualStudioAssemblies"
            Condition="'$(IncludeCopyLocalReferencesInVSIXContainer)' == 'true'">
        <SuppressPackaging Include="@(VSIXSourceItem)"
                           Condition="$([System.String]::new('%(Filename)').StartsWith('Microsoft.VisualStudio'))" />

    The second case will require you to carefully factor your assemblies so that the actual MEF implementations live in a single place and are distributed by a single extension, possibly declaring a dependeny on that one in the other extensions’ manifests.

    If users continue to see random (and usually hard to repro) MEF exceptions, it might be that it’s not you who is distributing those duplicate assemblies, and with VS vibrant ecosystem of extensions, it’s hard to make sure in advance that doesn’t ever happen. In that case, you might still want to ensure a clean MEF cache on the next VS start after you install your product.

    If you’re installing via the VS gallery as a VSIX, then you’re out of luck ;). But if you have an MSI that installs your extension, then it’s fairly straightforward.

    Partially based on the (fairly old) blog post tactical directory nukes, I came up with the following, which works great:

    • Add the WixUtilExtension to your WiX project. I usually add it like this directly to the .wixproj:
       <WixExtension Include="WixUtilExtension">
    • Add the XML namespace to your WiX file: xmlns:util="http://schemas.microsoft.com/wix/UtilExtension"

    • Declare and initialize a property for each of the VS MEF caches you support and are going to potentially clean:

       <SetProperty Id="MEF14" Value="[%LOCALAPPDATA]\Microsoft\VisualStudio\14.0\ComponentModelCache" Before="CostInitialize" /> 
    • Finally, add the following element to a component installed by each VS version you support:
       <util:RemoveFolderEx On="both" Property="MEF14" Id="CleanMEF14" />

    Of course, have as many MEF[n] properties as you need, like MEF11, MEF12, etc., and initialize the property to point to the right ComponentModelCache folder appropriately.

    The On="both" ensures you clean the cache after an install or uninstall, so you always leave VS in a pristine MEF state. The slight performance hit on the first run after an install is not terrible and certainly a rare event unless you’re testing VS extensions for a living ;)