The out of the box console environment in Windows can leave a lot to be desired. It’s hard to resize, copy/paste doesn’t work out of the box, etc. ConEmu and Cmder wrap the existing cmd console (really it works with any console app) and fixes a lot of these issues. Some features (mostly stolen from the website)

  • Smooth window resizing
  • Tabs and splits (panes)
  • Easy run old DOS applications (games) in Windows 7 or 64bit OS (DosBox required)
  • Quake-style, normal, maximized and full screen window graphic modes
  • Better fonts
  • Using normal/bold/italic fonts for different parts of console simultaneously
  • Cursor: standard console (horizontal) or GUI (vertical)
  • Easily select various environments (PowerShell, cmd, admin consoles, etc)
  • Hot keys
  • Better mouse integration in the console

ConEmu and Cmder work in conjunction. ConEmu is the base application and Cmder adds additional configuration and settings. I’ve used them together for so long that I don’t really know which settings are from which program.

The rest of this post will assume you’re already using ConEmu and focus on how to set it up in a way that allows you to customize your console environment and keep it in sync across multiple computers. An added bonus of these requirements is that it makes it trivial to restore your environment when reinstalling Windows or getting a new computer.

Install Cmder and ConEmu

First up, installation. This is easy, just use chocolatey

choco install -y cmder.portable

Export Settings

Well that was easy. Next we’ll start up Cmder and export the existing settings configuration. If you haven’t used the app yet, the defaults are still worth exporting since you need a starting point.

  1. Open up Cmder from the Windows Start Menu (this will start ConEmu)
  2. Open ConEmu’s settings window by using the hotkey Win-Alt-P or by clicking the hamburger menu on the bottom right corner.
  3. Click the Export button that shows up in the bottom right. Export Settings
  4. Save the file to a folder you sync across your computers (OneDrive, Dropbox, etc). I use c:\users\joshq\OneDrive\bin\ConEmu.xml

Use Exported Settings

Now that we have our configuration in a non standard location, we want to tell ConEmu to use it.

  1. Start up ConEmu from the Windows Start Menu
  2. Right click on it in the taskbar and select Pin to taskbar
  3. Close ConEmu to verify that the pin was created
  4. Next update the shortcut
  5. Right click on the pin
  6. Right click on Console Emulator
  7. Click Properties

    Configure Pin Properties

  8. Change the target to include the -LoadCfgFile <Path To Exported Config> (using the config file we exported above)
     Files\ConEmu\ConEmu64.exe" -LoadCfgFile C:\Users\joshq\OneDrive\bin\ConEmu.xml
  9. Click OK
  10. Repeat this on every computer you want to use ConEmu

Now no matter what type of configuration change you make to ConEmu, your settings will follow you across all computers and to any new ones.

Configuring ConEmu

Speaking of configurations, what’s worth tweaking from the default install?

Tweak tab settings under Main/Tab Bar. If you’d prefer that ctrl-tabbing cycles between all tabs instead of just the most recent two, deselect Recent mode on the top right hand corner of the page. You can also change the what the tabs say by default by changing the Console: setting. I use ` %m->m %n %f. It indicates the current tab with an arrow (->`), and shows the currently running command and folder.

Under Startup, you can tell ConEmu remember your open tabs between sessions by selecting Auto save/restore opened tabs.

With Freatures\Transparency, you can configure different transparencies for your console when it is active and inactive. This can get pretty annoying if you make it to transparent, but it is a nice feature if used sparingly.

And most importantly, under Startup\Tasks you can configure which consoles are available when you press Ctrl-T. For me the minimum are cmd, an admin cmd, and a PowerShell prompt, but you can configure PuTTY, Ubuntu prompt using WSL, Visual Studio’s developer command prompt, or really any program that runs under a command prompt.


Configuring cmd

The standard cmd.exe can be started with the /k argument to specify a .bat script to run at startup. This script can let you further customize your console environment. You can use it to set environment variables or aliases. It’s similar to a .bashrc in the Linux world.

To take advantage of this, edit the cmd task and set the command to run to be something like:

cmd /k %HOMEPATH%\OneDrive\bin\cmdinit.bat -new_console

We’re saving the script in the same OneDrive directory as our ConEmu configuration file. This way both will be sunk and the console environment will follow us from computer to computer.

This sample script does a few things:

  1. Adds a couple of additional folders to either the beginning or end of the current PATH
  2. Uses DOSKEY to configure some quick shortcuts to go from the command line to the File Explorer
  3. Uses DOSKEY to configure some aliases for frequent git commands. For instance, all we have to do now is type s to show the git status of the current directory, or co master to switch to the master branch.
  4. Uses DOSKEY to add a quick way to edit the configuration script (aliases) and another to reload the script if any changes have been made (refresh)
  5. Print out the current directory
REM Console Startup Configuration
REM ******************************************

REM ******************************************
SET PATH=%HomeDrive%%HomePath%\OneDrive\bin;%PATH%
SET PATH=C:\Program Files\Git\cmd\;%PATH%
SET PATH=%PATH%;C:\tools\sysinternals

REM Open the current directory in File Explorer
REM ******************************************
DOSKEY   ex=explorer $*
DOSKEY  ex.=explorer .

REM ******************************************
DOSKEY push=git push
DOSKEY pull=git pull
DOSKEY   co=git checkout $*
DOSKEY    s=git status

REM Make it easy to edit this file
REM ******************************************
DOSKEY aliases=gvim %HomePath%\OneDrive\bin\cmdinit.bat ^& echo Don't forget to open run `refresh` to make sure these take effect
DOSKEY refresh=call %HomePath%\OneDrive\bin\cmdinit.bat

REM Print out current path when opening a new console
REM ******************************************

There’s a lot more that can be done to with scripts like this to configure your environment. You can use the above script as a starting point and add anything you think of as you’re plugging away by running the aliases command. Any changes you make will automatically be saved and synced.

comments edit

layout: post disqus_identifier: #32 comments: true categories:

  • Visual Studio
  • VS
  • Command Line

Despite being a developer that uses Windows, I spend a lot of time managing my code on the command line. As such I want to open up my code in Visual Studio from the command line. Typically I already know the name of the sln file, but if I don’t I can do a quick ls *.sln to find it and then type it in.

I’m lazy and that requires me to not only type more, but to also remember things. I’d much rather be able to cd to my project directory and then just type in the same thing no matter where I am and have it open up what I want. My first pass at automating this assumed that there was a single sln file in my current directory, figured out what it was and then opened it.

For the most part that works, but there are a couple of projects that have multiple sln files and/or sln files that don’t live in the root of the folder structure. In my case, there were few enough of these edge cases so I could just code around them.

Below is the batch file that I use. Each special case gets their own if/set.

REM ***************************************************************************
REM ***************************************************************************
REM Find and open the prefered sln file If a prefered file can't be found, just
REM open the first one you see
REM ***************************************************************************


REM First off see if there is a fallback sln file to open
FOR /F %%i in ('dir /B/s *.sln') do (
  SET SLN=%%i

REM Now look if there is a preferred sln that we want to grab
IF  EXIST SecondSolutionInAFolder.sln (
  SET SLN=SecondSolutionInAFolder.sln

IF  EXIST .\ConsoleApps\FunWithSpikes\FunWithSpikes.sln ( 
  SET SLN=.\ConsoleApps\FunWithSpikes\FunWithSpikes.sln

IF NOT %SLN%=="" (
  ECHO Starting [93m%SLN%[0m 

ECHO [91mCould not find a solution file to open.  [0m
ECHO Are you sure you are in the right directory?  [91m %CD% [0m

Installation and Usage

  1. Copy the script into a file named sln.bat somewhere in your path
  2. From the command line go to the root directory for your project
  3. Run the sln command
  4. If the wrong sln file is opened, edit your sln.bat and add another if/set
> cd c:\code\MySuperAwesomeProject
> sln
Starting .\MySuperAwesomeProject.sln

OSS, Licenses comments edit

What open source projects are OK to use in a comercially distributed product?



Some licenses are explicitly not OK to use. For example, the copyleft licenses cannot be used in a closed source project. The following list is not exhaustive. Just because a license is not on the list does not automatically mean that it safe to use.

Dual Licenses

It is possible for a project to have more than one license specified. Unless specified otherwise in their licensing, all clauses from all licenses apply. This means that, to be safe, each license needs to be on the approved list.

Other Licenses

Any other license must be evaluated on a case by case basis.

More Information

The Open Source Initiative has lots of useful information about OSS licensing. Choose A License does a great job of breaking down the most common licenses comparing the differences between them.

Shakespeare comments edit


Principle players

  • Lear
    • King
  • Kent
    • Lear’s faithful servant
    • Exiled
  • Daughters
    • Goneril & Albany
    • Regan & Cornwall
    • Cordelia - The good one
  • Glouchester, Duke of
  • Edmund
    • Glouchester’s bastard
  • Edgar
    • Glouchester’s legit son
  • Fool
    • A fool

Plot Summary

Act 1

In which Lear fails to plan for his retirement.

Act 1 Scene 1

Lear decides to retire and splits up his kingdom amongst his daughters based on how much they love him. Turns out Goneril and Regan are good at professing their love. Cordelia on the other hand is more plain spoken. She gets the shaft. Kent gets exiled. France marries Cordelia.

Act 1 Scene 2

Edmund starts to make his dad think that Edgar is out to kill him for his inheritance. Bastards gotta bastard.

Act 1 Scene 3

Goneril ain’t enjoying having her dad live with her.

Act 1 Scene 4

Lear starts to chafe at living with his daughter. Kent comes back all disguised and ingratiates himself back in with Lear. Fools gotta fool.

Act 1 Scene 5

Lear heads off to his other daughter’s place with the Fool. Kent goes ahead as a messenger.

Act 2

In which Lear realizes that he should have planned for his retirement

Act 2 Scene 1

Edmund scares Edgar into thinking that Glouchester has it out for him. Fakes a fight with Edgar and Edgar flees. Glouchester sees this as proof that Edgar was plotting against him and disowns his son. Regan and Cornwall arrive and support Glouchester in this decision.

Act 2 Scene 2

Kent arrives at Glouchester’s at the same time as Goneril’s messenger and gets sassy with him. Maybe a little too sassy since Cornwall has him put in the stocks.

Act 2 Scene 3

Edgar is evading pursuit. Decides to dress up as a crazy beggar (Tom o’ Bedlam) and go on the lam.

Act 2 Scene 4

Lear arrives to find his servant in the stocks and gets pissy about it. Regan don’t care. Goneril arrives and double teams Lear with her sister. They say as long as he is living under their roofs he has to give up his retinue of 100 knights. Whittling it down to 50, then 25, then none. Lear says F this and runs out into the storm.

Act 3

In which Lear argues with the wind, which I’m guessing is the medieval equivalent of yelling at the T.V.

Act 3 Scene 1

Kent, looking for Lear, bumps into a “Gentleman” from Lear’s retinue. Tells him that all is not lost and that France is coming with Cordelia. Scene ends with them going in separate directions in search of Lear.

Act 3 Scene 2

Lear wanders around in the storm yelling at it and wallowing in self pity. The Fool tries to cheer him up to no use.

Act 3 Scene 3

Glouchester frets over Lear being out in the storm. Tells Edmund that he’s going to help his erstwhile king. Edgar’s all like “cool. cool cool cool.” and then tells the audience that he’s totally going to rat out his dad so that Cornwall will like him.

Act 3 Scene 4

Kent finds Lear and convinces him to seek shelter. They stumble across a shack with Edmund in it who is pretending to be crazy. Glouchester finds them and invites them all back to his pad for safety.

Act 3 Scene 5

Edgar rats out his dad to Cornwall. Cornwall calls for his head.

Act 3 Scene 6

Lear has a delirious fever dream of a trial for Goneril and Regan. Imaginary Regan is imagined to run away and is then chased by imaginary dogs. Glouchester comes back and tells Kent to take Lear to Dover.

Act 3 Scene 7

Cornwall sends Goneril and Edgar back to Goneril’s castle, plucks out Glouchester’s eyes, and is stabbed. It’s just a flesh wound.

Act 4

In which reunions are made and more are hinted at.

Act 4 Scene 1

Blinded, Glouchester has been kicked out of his own castle and is brought to Edgar. Edgar agrees to take him to Dover.

Act 4 Scene 2

Goneril and Edmund arrive at Goneril’s castle. Albany (her hubby) isn’t happy about all the king-gas-lighting and eye-plucking. Goneril totes has the hots for Edmund. Cornwall dies off stage.

Act 4 Scene 3

Lear has arrived at Dover. Cordy reads a letter about how her sisters treated their dad. It made her sorrowful, but at least she’s pretty when she’s sad. Lear is to ashamed to see his daughter.

Act 4 Scene 4

A doctor tells Cordelia that there is hope for treating her dad. She sends out people in search of him.

Act 4 Scene 5

Regan talks with Goneril’s messenger. She’s concerned that Goneril might be intersted in Edmund and tries to get this information from Oswald (the messenger). She reveals that she thinks she is a better match for the new Duke of Glouchester.

Act 4 Scene 6

The cliff diving scene. Edgar (as Poor Tom) has led his father to “the edge” of the Cliffs of Dover. In fact they are nowhere near the cliffs. Edgar in the hopes of helping his father get over his suicidal depressoin encourages his father to jump. Glouchester jumps and doean’t get hurt since they are pretty much on solid ground. Edgar now pretends to be someone else and talks about how far Glouchester had fallen. Glouchester accepts this as a miracle and resolves to live his life out.

Lear stumbles in around now and starts to pontificate on morality. He’s chased off when Cordelia’s messengers find him and try to bring him back t his daughter.

Oswald next stumbles into the scene and declares his intent to kill Glouchester. Edgar, being the good son, takes issue with this and defends his father, killing Oswald. After searching the body, he finds Goneril’s note to Edgar plotting the death of Albany (Goney’s hubby).

Act 4 Scene 7

Lear has been caught and brought back to Cordy.

Act 5

In which everyone lives happilly ever after, except for the vast majority who die in the last scene.

Act 5 Scene 1

Prelude to war. Albany shows up and joins with Regan. Edmund later contimplates killing Albany.

Edgar gives Albany the letter from Goneril trying to plot his assination with Edmund.

Edmund think about which sister he wants to marry.

Act 5 Scene 2

The war has been lost. Edgar tries to reassure Glouchester who is ready to die. Which is good cuz he dies off stage between scenes.

No further, sir. A man may rot even here.

– Glouchester Line 9

Act 5 Scene 3

Edmund sends Lear and Cordelia to prison followed with orders to have them killed. Lear goes gladly. He looks forward to spending the rest of his days with Cordelia and cares not for prison.

Albany, Goneril, and Regan enter and start arguing over Edmund’s station. Goneril reveals that she’s poisoned Regan. Albany summons Edgar (no longr dressed as a commoner) who accuses Edmund of being a traitor and fights him in single combat. Edmund is mortally wounded but takes his sweet ass time to die.

Albany promises to give everything to Cordelia and Lear. Enter Lear with Cordy’s dead body. Lear dies of grief. Kent arrives to say that he’s not long for this world.

Who Dies:

  1. Glouchester (off stage)
  2. Regan (poisoned, dies off stage)
  3. Edmund (wounded in single combat, dies slowly on stage)
  4. Cordelia (hanged off stage)
  5. Lear
  6. Kent (implied to off stage soon after the completion of the play)


Notes from my March 6 - 11 2017 trip to Barcelona with Ksenia.

General Notes

We didn’t use the transit system. Either stuff was within walking distance or we took cabs. Barcelona has it’s own cab app (works like Uber), so you can hail one that way if you wish. The app is called Helo. I found the app through Google maps. Input the address in Google Maps you want to get to, and then click on “Hail a Cab” and app suggestions will pop up.

We like using our credit cards when we travel abroad (we have one that has no foreign transactions fees), and Barcelona was very credit-card friendly (unlike Germany….ugh that’s a whole other story). Also, I find that more and more places ask (when charging stuff to your CC) if you want to pay in Euros or US dollars. Definitely pay with Euros. The price difference may be small, but it starts to add up if you keep using your CC.


Ham. There are several types but what you want to eat will be the black hoof iberico. Sweat, salty, tender, melt in your mouth. Amazing.

There’s more foie here than I would have expected. We wound up eating foie and ham each and every day. It was delightful.

Tapas tend to be very regional dishes in Spain. Which means that you can only find a handful of different options wherever you go. Except Barcelona. Barcelona never had the tapas tradition, so when they started becoming a thing Barcelona just made everyone else’s and then invented some new ones. This means that if you want to try all the tapas, Barcelona is where you want to be. I enjoyed eating tapas at the bar. It’s nice to have the bartender around so you can easily and quickly order another dish. And you will be ordering another dish.

Pan con tomate or tomato bread is a common dish where they rub a mushy tomato on some crispy (sometimes purposefully stale) bread and drizzle some olive oil over it. It is delicious and you can find it everywhere. If a spot doesn’t have good tomato bread then it’s probably not worth eating anything else there.

Reservations aren’t required but can be helpful.

  • Tapas @ Catalana
    • Good not great.
  • La Pepta
    • We went to eat here twice! Ksenia still talks about the foie gras topped with white chocolate and hazelnut shavings. They do giant gintonics.
    • In can get VERY crowded in there so if you get there RIGHT at 7:30pm (when they re-open for dinner), you should be able to get a seat at the bar.
  • Walking Food Tour of Gracia
    • Gracia is a neighborhood with a unique identity and great food. This tour was one of our highlights of the trip! Highly recommend! It just so happened that on our tour it was me, Ksenia, and one other person, plus the guide. Gracia is delightful! Also, if you like getting one-of-a-kind clothing, this is the place to walk around! K got several shirts for herself and mom here. In one shop, the owner/designer had her studio right behind her, with all the materials she needed to make the shirts.
    • Stops:
      • Con Tosca - a cute cafe where we had sausage on tomato bread and a glass of cava.
      • Local market
        • I Conservas Gloria for olives
        • Fabregas for ham
        • La Trobada del Gourmet for cheese and jams
      • Oil Sal a salt and oil store where we had olive oil tasting
      • l’Anxoveta a cute bar, we had tomato bread and crouqets
      • Pastisseria Principe a Syrian pastry shop that’s been there for 30 years
      • Bodega Ca’l Pep an ancient very local bar. We had vermouth, pickled anchioves, and sausage.
      • La botigueta del Bon Menjar a small shop that sells premade food. very local
      • Pastissera Ideal another pastry shop. We had cremat - a Spanish version of creme brulee (it actually predates the French version)
  • La Pubilla
    • My favorite restaurant. I’d recommend a reservation, or just getting there when they open.
    • We ate here twice. When we came back the second time we were welcomed like old friends.
    • Between K and I, we ate like 90% of the menu between the two trips there. And we were not disappointed.
    • The waiter was gave us some great wine recommendations, they have some really local stuff there. Like 1km away local.
    • Best croquets we had
    • Homemade pate
    • The capacio was one of the best things I ate on this trip.
  • Alta Taberna Paco Meralgo
  • Tapeo del Born
    • Near the Picasso Museum. We ate here on our last night, at the bar.
    • It feels a bit more touristy but the food was still good. K liked it more than I did.
    • When we ordered our food, one of the guys behind the bar asked if we had come there before because he was impressed with our choices.
    • The Foie Gras burger was good.
  • Mercado de la Boqueria
    • Not a restaurant, but it has plenty of stalls in it where you can get all sorts of food
    • Butchers sell “meat cones” - charcuterie in a paper cone.
    • Fresh juices
    • Hot food
    • Candies
    • etc.


Gintonic has recently become a thing in Spain. According to a bartender I spoke with Hendrix put a lot of ad dollars into the area and it worked. There are dedicated gin bars with dozens if not hundereds of bottles to choose from. Josh loved these places. A lot.

While gin is the new fad, vermouth is the traditional drink. The early afternoon is called “the vermouth hour”. It’s when you’re supposed to get together with some friends and have a glass of vermouth, a few sardines, and chat.

Another classic is cava, a Spanish sparkling white wine.

  • Elephanta
    • A gintonic bar that also has a great tea list.
    • Several dozen options for gin, with useful descriptions.
    • The menus are on the back of LPs.
    • They do flights
  • Bobby’s Gin
    • Hundreds of bottles of gin
    • Very knowledgeable bartenders
    • Lots of obscure and local gins
    • No food


Barcelona is the city of Gaudi.

  • Gaudi
    • Sagrada Familia
      • Definitely worth booking a ticket with a tour, the “guided experience”, as the tour guide will point out elements to you that you will have missed on your own. Tickets
      • Definitely purchase online! You can choose which time you want to go in.
      • Entrance will be on the “old” side, not the Cubist side.
      • We went in the afternoon and the lighting through the orange/red stained glass windows was AMAZING inside because the sun was setting.
      • This was by far my favorite part of Barcelona that I couldn’t eat or drink.
    • Casa Batlló
      • This house is AMAZING! Don’t miss it!
      • The audioguide is worth it. There are so many details.
      • The interior was really cool with all sorts of curved walls and doors. It felt like being in an underwater fairytale.
    • Park Guell (aka Gaudi Park)
      • So the park is free BUT if you want to go visit the section of the park with all the Gaudi stuff you have to buy a ticket and it’s timed entrances. We didn’t realize this when we went (this is a very recent thing, as the entire thing used to be free) We got there at like 3, got our ticket for 4:30, and in between that time we walked around through the rest of the park which has several layers. It is a nice walk and you have some great views. The Gaudi section will be crowded. So if you’d like, plan in advance and get tickets online for a timed entry. FYI: the entire park is up on a hill! We went to the Park after we did the food tour, because it was essentially a straight shot from the endpoint of the tour (and because stuff was closed at 2pm-ish).
    • Palau Guell
      • My least favorite of the Gaudi sites, perhaps because it was the last.
      • The roof has amazing views but is very sloped. It may not bother some people but I was terrorfied up there. Frozen and refused to move without holding on to something.
  • Free Walking Tour
    • We did three of these in Germany and one in Barcelona. Really great way for you to quickly learn the lay of the land, the history, and some great anecdotes.
  • Picasso Museum
    • I’m a huge fan and this museum is in a very nice building too! Also some good shopping in the area too!
  • La Rambla
    • Very touristy so keep an eye out for pick pockets.
    • Crowded
    • Only worth it as a way to get to Mercado de la Boqueria
  • Papirum
    • Paper store that sells hand, bound deckled, leather notebooks.
  • Museu d’Art Contemporani de Barcelona
    • Very modern very out there. We did not enjoy this museum. It’s the type of modern art that people sneer at when they think of modern art. Like a banquet table that is set with plates of rice died to look like the flags of various nations, but then they left all the food to rot. Or a wall made out of loaves of white bread.


Hotel Praktik Bakery is a hotel with a bakery on the first floor. Sounds a bit gimmicky except that they legitimately have the best bread in the city. There are lines out the door of locals and tourists. You can see the bakers making the bread in the front window. The pastries are amazing, and the grab and go sandwich I got for breakfast was legitimately one of the best sandwiches I ever had.

They do a continental style breakfast, but it’s better to just get something from the bakery directly.

If a bakery doesn’t tickle your fancy, Praktik has other themed hotels in Barcelona, including a wine bar slash hotel.

Oh, and the rooms have rain showers.

All of that, plus a great location.

chrome, tips, GitHub, PR comments edit

Sometimes when I’m working on a long pull request in GitHub and switch back to the PR tab after a while of looking at other pages the Pull Request page will automcaticall reload itself. Most of the time this is fine, but sometimes I wind up losing a lot of state (scroll position, which files were loaded manually, which files had been collapsed, etc). It turns out that Chrome will garbage collect tabs that are taking up a lot of memory that you may not be using. Chrome allows you to disable this behavior by going to chrome://flags/#automatic-tab-discarding. Simply set the drop down to ‘Disabled’.

I typically don’t want to keep this setting once I’m done with my PR, so I’ll then jump into slack and ask it to /remind me to fix chrome://flags/#automatic-tab-discarding in the morning

GitHub Pages, SSL comments edit

Adding a certificate to your GitHub Pages site so that all of your traffic can use HTTPS is easy… if you don’t use a custom domain name. If you do have a custom domain, then you need to do a little work and a (free) Cloud Flare account to get it going.

  1. Create your free acount on
  2. Enter your site’s address in the setup bar
  3. Head over to your DNS provider and add the Clod Flare servers as your custom domain servers. e.g. On NameCheap
  4. Optionally, you can head back to Cloud Flare and set up a page rule to redirect all HTTP pages to redirect to HTTPS. Just add a rule to match http://**
  5. Wait. DNS has to happen now.

Thanks to Hacker Noon for pointing this out.

mermaid, tools comments edit

Mermaid is a tool that will generate diagrams from a basic definition language.

The mermaid website has full description of the language and features:

A Simple Example

The following snippet will create a simple sequence diagram.

    Alice->>John: Hello John, how are you?
    John-->>Alice: Great!

The above diagram renders as:

sequenceDiagram Alice->>John: Hello John, how are you? John-->>Alice: Great!


There are various tools that you can use to edit and save diagrams as images

Mermaid CLI

Pros and Cons


  • Export diagram as an image


  • No live updating diagram as you type
  • Syntax requires a non-standard but simple header of ```mermaid

Setup and Use

  1. Install node.js
  2. Install the mermaid npm package
     npm install -g mermaid
  3. Install the phantomjs npm package
     npm install -g phantomjs
  4. Save the following diagram definition to a file sequence.mmd
         Alice->>John: Hello John, how are you?
         John-->>Alice: Great!
  5. Run mermaid command
     mermaid sequence.mmd
  6. Open the image found at sequence.mmd.png


Visual Studio Code

Pros and Cons


  • Live updating diagram as you type


  • No easy way to export diagram as an image
  • Syntax requires a non-standard but simple header of ```mermaid
  • Supports the activate/deactivate keywords that are unsupported by other processors

Setup and Use

  1. Download and install Visual Studio Code (this is entirely different than the “normal” Visual Studio you use to write C# code)
  2. In Visual Studio Code download and install the Mermaid Preview extension
  3. Restart Visual Studio Code when prompted
  4. Create a new markdown file named
  5. Paste in the following diagram definition (including the lines that start with three backticks)
             Alice->>John: Hello John, how are you?
             John-->>Alice: Great!
  6. Press <control-p> to bring up the Visual Studio Code command window
  7. Type in > Preview Mermaid Diagram
    • Include the > character
    • You only need to type enough of the command that it shows up in the menu
    • You can type in various short cuts that will also bring up the command quickly
      • > Mermaid
      • > PMD (just the initials)
  8. Click on any of the text in the left pane that is part of the diagram definition

Sample Diagram in Visual Studio


Pros and Cons


  • Live updating diagram as you type
  • Export diagram to PNG or SVG


  • Exported diagram has a blank background (you need to manually open the file and add a non-transparent background to be able to view the image)

Setup and Use

  1. Install Atom editor
  2. Install Mermaid Preview extension
  3. Create a new markdown file named sequence.mmd
  4. Paste in the following diagram definition
         Alice->>John: Hello John, how are you?
         John-->>Alice: Great!
  5. Press the Packages -> Mermaid Preview -> Toggle Preview button
  6. To export as image right click the diagram and select Save as PNG

Sample Diagram in Atom

docker, jekyll comments edit

GitHub Pages have some great features that I’m excited about. Markdown makes writing code-centric blog posts easy. Storing posts in git is great – history, diffs, and no need to learn a new tool. Not to mention simple hosting by GitHub.

There’s just one minor issue, setting up a decent environment on a Windows machine can be troublesome if you’re not alread a Ruby developer. I’ve tried twice now and run into issues both times. Multiple versions of Ruby, non-Windows friendly libraries, failed SSL certs, and probably a few more things that I’ve forgotten. Next I thought I’d try it on Linux on Windows. For the most part that worked well, except some auto-reload features didn’t work well.

It’s almost as if I would be better off trying to run the environment on a Linux machine. Seeing as I don’t have a spare machine and hate running VMs on my work laptop, I’m probably not running Linux any time soon.

All I really want is a preconfigured environment that I can download quickly and not have to do anything to setup. Is that too much to ask? Apparently not. Heading over to Docker Hub, I found several Docker Images for exactly the environment I wanted. I blindly went with the one with the most downloads. There was one minor hicup. The instuctions use the Linux variable $PWD to mount the volume from the host machine to the Docker image. That just needed to be translated to %CD%. With that down, I was able to point the browser on my Windows machine to localhost:4040/ and my website was up. I could edit any file with whatever Windows tool I was comfortable with (ironically, Vim), save it and my site would be regenerated.

All told, I was up and running in about 15 minutes, including download time and writing two simple batch files to start and stop the containers.


@ECHO off
ECHO Starting gpages container

docker run -t --rm           ^
    --name gpages            ^
    -v "%CD%":/usr/src/app   ^
    -p 4000:4000             ^


@ECHO off
ECHO Stopping gpages container
docker stop gpages

vim comments edit

I’ve been using Vim for close to 15 years now and it always amazes me. I needed a quick and easy way to encrypt some files on a thumb drive when going from one computer to another. After about 5 seconds of googling I see that as always, vim’s got my back.

First off, you can optionally select your encryption scheme by doing :setlocal cm=blowfish2. There are other options, but that’s the strongest encryption available. Next all you need to do is set the password by typing: :X (note that it is a capital X). You’ll be prompted for the password. After that just close vim as normal. You can cat out your file on the terminal to double check that it’s encrypted.

When you repopen the file in vim, you’ll be prompted to enter the password to decrypt the data.

If you want to save the decrypted file, just clear out the key by doing :set key= and then save the file.


Okay, so I don’t really know why I’d use this, but I just came across Ninject.Extensions.Interception. Basically it allows you to intercept an arbitrary method call and run code before and after the call. Even replace the method entirely.

You could use this to achieve many things you would use Aspect Oriented Programming to do. Post Sharp has a great breakdown on what those use cases are and why it’s a valid approach to solving certain problems.

The canonical use case for this is the ability to easily add logging when you enter and exit a method.

For example, the following code would log all calls to the SomeSuperImportantMehod

public class CanonicalLogging
  public virtual int SomeSuperImportantMehod(string input, int maxItems)
    return CalcualteReallyImportantThing(input, maxItems);

And here’s an example of what the output could be

2017-05-05 13:45:54.64723 CanonicalLogging.SomeSuperImportantMehod called with parameters:  {input:  "Hello World", maxItems: 34 }
2017-05-05 13:56:56.94949 CanonicalLogging.SomeSuperImportantMehod returned "42" after running for 11:02:30226


For the example I’m going to build an implementation of the Dispose Pattern with a base class that will handle all of the actual disposing logic. I’ll use a custom interceptor to ensure that once my objec thas been disposed all future calls to it will throw an ObjectDisposedException.

To get started you first need to be using Ninject. I’m going to assume you have a bit of a background with Ninject. Just in case you don’t, the quick version is that it’s a .Net IoC container. Basically that means that after doing a little configuration you can ask it for an instance of any type you want and it will give it to you, creating it and its dependencies if it needs to.

Another thing to be aware of is that there are two options, either use LinFu or CastleCore for the proxy generation. As far as I can tell, this decision doesn’t really impact much. Just pick whichever framework you like, or one at random. I already use CastleCore in other projects (the Ninject factory extension depends on it), so I’m going with that one.

Install-Package Ninject.Extensions.Interception.DynamicProxy


Next I’ll create the base ADisposable that all of my custom disposable objects will inherit from.

    public abstract class ADisposable : IDisposable
        public ADisposable()
            IsDisposed = false;


        internal bool IsDisposed { get; private set; }

        public void Dispose()

        protected abstract void OnDispose();

        private void Dispose(bool disposing)
            if (IsDisposed) return;

            if (disposing)

            IsDisposed = true;

There two things worth pointing out here. First, the internal IsDisposed property. This will be used by our interceptor later to determine if the object has been disposed. The other thing worth noting is the Disposable attribute. That’s a custom attribute I defined. It inherits from Ninject.Extensions.Interception.Attributes.InterceptAttribute. This is the first step into using interceptors, so let’s take a look.


using Ninject;
using Ninject.Extensions.Interception;
using Ninject.Extensions.Interception.Attributes;
using Ninject.Extensions.Interception.Request;
using System;

namespace Interceptors
    public class DisposableAttribute : InterceptAttribute
        public override IInterceptor CreateInterceptor(IProxyRequest request)
            return request.Kernel.Get<DisposableInterceptor>();

There’s only one method that we have to worry about CreateInterceptor. This just lets the system know what interceptor to use when creating the implementation of ADisposable. You can see here that I added the AttributeUsage to specifically target only classes. Be default InterceptAttributes can be put on anything, although they really only make sense on method (including properties) and class definitions. When the attribute is placed on the class, it impacts all of the methods. In fact there is a neat DoNotIntercept attribute that you can use to exclude certain methods from the class wide interceptor.

In my example, I used the request to get an instance of the Kernel so I could resolve the interceptor I wanted. That was mostly just to illustrate that you can get a hold of the kernel. In this instance, I could have just as easily newed up the DisposableInterceptor. Speaking of which, DisposableInterceptor is where the most interesting code is. We’ll look at that next.


using Ninject.Extensions.Interception;
using System;

namespace Interceptors
    public class DisposableInterceptor : SimpleInterceptor
        protected override void BeforeInvoke(IInvocation invocation)

            var disposable = invocation.Request.Target as ADisposable;

            if (disposable != null && invocation.Request.Method.IsPublic)
                if (disposable.IsDisposed)
                    string methodName = invocation.Request.Method.Name;
                    throw new ObjectDisposedException(disposable.GetType().Name, $"{methodName} called after object was disposed");

It inherits from SimpleInterceptor and overrides BeforeInvoke. As you may guess, there’s an AfterInvoke as well. If you wanted to, you could set the return value of the method by setting invocation.ReturnValue in BeforeInvoke. Or in AfterInvoke you could check to see if it’s within certain limits.

Anyway, in this example all I care about is overriding BeforeInvoke to check if

  1. The instance being invoked is an instance of ADisposable
  2. The method being called is public (no need to worry about private methods being called since they’d have to be called from public ones to begin with)
  3. If the instance had already been disposed.

In order to do all of those things, I just need to inspect sub-properties of the passed in instance of IInvocation. If all of those things are true, then we just throw an exception.

Now that we see the interception code is straight forward, let’s put it all together so that we can use it.

Sample Service

public interface ISomeService : IDisposable
    void SomeMethod(string msg);

public class MyService : ADisposable, ISomeService
    public void SomeMethod(string msg)

    protected override void OnDispose()
        Console.WriteLine("Disposing MyService");

The first thing to look at is the sample service interface and implementation. ISomeService is just a simple interface that inherits from IDisposable and has a single method to implement. MyService inherits from ADisposable and ISomeService and pretty much does the minimum it needs to do to implement them.

Notice though that neither of them are aware of either Ninject or any of the interceptors. They are bog standard C# classes.

Resolving an Interface

private static void TestResolvingInterface()
    Console.WriteLine("Testing resolving an Interface from the Ninject Kernel");
    using (var kernel = new StandardKernel())

        ISomeService service = kernel.Get<ISomeService>();


private static void TestService(ISomeService service)
    Console.WriteLine("    " + service.GetType().Name); // Prints out "ISomeServiceProxy"
    service.SomeMethod("    Hello World");

        service.SomeMethod("    This call should fail");
    catch (ObjectDisposedException odex)

In the first method, TestResolvingInterface, we do some very standard Ninject setup. Create a standard kernel, add some bindings, and then resolve our interface. Again, none of this is even aware of the interceptors. Ninject picked up on it from the attribute and that was enough.

The output for this is:

Testing resolving an Interface from the Ninject Kernel
    Hello World
Disposing MyService
SomeMethod called after object was disposed
Object name: 'MyService'.

You’ll notice that service is an instance of ISomeServiceProxy, not MyService. Ninject wrapped our instance of MyService, adding the extra functionality to the proxy without actually impacting our class.

You’ll also see that the second call to SomeMethod does indeed fail with an ObjectDisposedException.

Resolving a Concrete Class

Now that worked all well and good. But what if we resolved just a class instead of an interface? Well that’s where this starts to break down as we’ll see in the code below.

private static void TestResolvingConcreteClass()
    Console.WriteLine("Testing resolving a Concrete Class from the Ninject Kernel");
    using (var kernel = new StandardKernel())

        MyService service = kernel.Get<MyService>();

private static void TestService(ISomeService service)
    Console.WriteLine("    " + service.GetType().Name); // Prints out "MyServiceProxy"
    service.SomeMethod("    Hello World");

        service.SomeMethod("    This call should fail");
    catch (ObjectDisposedException odex)

So now we’re resolving a MyService directly and passing it to the same test function as the previous example. Let’s look at the output.

Testing resolving a Concrete Class from the Ninject Kernel
    Hello World
Disposing MyService
    This call should fail

We’re getting a proxy wrapping our class again (MyServiceProxy), which is a good sign, but then we see that the second call to SomeMethod actually succeeds. Why is this?

This is probably the biggest caveat in the entire thing. The interceptors can only impact virtual methods. Interface methods are by nature virtual so they are no problem. But when it comes to concrete classes, unless the method is explicislty marked as abstract or virtual it can’t touch them. As I mentioned above, Ninject is dynamically creating an implementation of the requested object with custom implementations of all the methods. If MyService had been sealed, Ninject would have thrown a TypeLoadException when it was resolved because it couldn’t subclass the type.


As mentioned above, the major caveat is that it only works with virtual methods. If you always use interfaces, then you will be just fine, but if you don’t the interceptors will silently fail to be called.

Other than that, this is a pretty easy to use tool that can provide a lot of power. Another obvious use case for this is automating INotifyPropertyChanged. It’s so obvious that it comes premade. Just check out the NotifyOfChanges attribute.

jekyll, update comments edit

This is my first post on my new blogging engine. I’m using GitHub Pages now. So far I really like it. It’s nice and easy. I have been a big fan of markdown for some time now. Rich text that I can easily create in vim? Yes please! Creating templates for pages and content that I can easily create by adding structured data files to a folder? Yes please!

comments edit

Following up on CoolWhip, ChocolateyCoolWhip is a nuget package that makes creating, packaging, and deploying your code through simple. Like CoolWhip, all you need to do to publish a new release is create release in GitHub.


In case you aren’t familiar, Chocolatey is a package manager for Windows built on top of NuGet and PowerShell. It allows users to download and install thousands of software programs with a single command. For example, to install nodejs, all you would need to do is open up a command prompt and enter

> choco install nodejs.install

Getting Started with ChocolateyCoolWhip

To get started, install the nuget package into your project. The first thing you’ll notice is that it creates nuspec and AppVeyor configuration files. Chocolatey uses the nuspec as metadata for your package, the same way NuGet does.

Once setup, all you need to do to update your package on is create a release in GitHub. ChocolateyCoolWhip will pull the version information directly from the release name and kick off a build in AppVeryor. You have complete control over versioning your application

Configuration is simple:

  1. Connect AppVeyor to your GitHub repo
  2. Install the NuGet package >Install-Package ChocolateyCoolWhip
  3. Update the generated nuspec file with your project’s information
  4. Add your authorization tokens to the AppVeyor.yml file
  5. Save/commit your changes

Once this is set up, all you’ll need to do in order to release (or update) your package on NuGet is create a GitHub release with the version number.

There is full step by step documentation in the wiki.

Happy Coding.

this post was originally on the MasterDevs Blog

comments edit

CoolWhip is a NuGet package aimed at making and deploying other NuGet packages easier. With CoolWhip, creating a Release in GitHub automatically pushes that release to NuGet.

Once you’ve installed CoolWhip into your project it will create a nuspec file and AppVeyor configuration file. These will work together to package your project and automatically upload it to

Once setup, all you need to do to update your package on is create a release in GitHub. CoolWhip will pull the version information directly from the release name and kick off a build in AppVeryor. You have complete control over versioning your application.

To configure CoolWhip you need to

  1. Connect AppVeyor to your GitHub repo
  2. Install the NuGet package >Install-Package CoolWhip
  3. Update the generated nuspec file with your project’s information
  4. Add your authorization tokens to the AppVeyor.yml file
  5. Save/commit your changes

Once this is set up, all you’ll need to do in order to release (or update) your package on NuGet is create a GitHub release with the version number.

There is full step by step documentation in the wiki.

Happy Coding.

this post was originally on the MasterDevs Blog

comments edit

I’m OCD when it comes to my code. I don’t like to have any warnings. I wanted to configure my TeamCity builds to fail if there were any warnings in the projects. My first option is to tick the “Treat warnings as errors” box in the project settings. This had a few problems

Problem 1.

I’d have to remember to do it for every project in my repo, including all the projects I make in the future. Even worse, everyone on my team would have to remember to do that too. That’s not something I could rely on.

Problem 2.

While warnings are just errors that you’re ignoring, I will admit that it is convenient to be able to ignore some things some times. I’m fine with debugging and running locally with some errors. I really only wanted to stop people from committing code back to master with warnings. I couldn’t care less about bad hygiene the have when working locally.

The Solution

In searching, I found David Gardiner’s blog post in which he creates a power shell script to edit the xml in each csproj file. It looks simple enough so I removed the TFS bit and added it as a build step in my TeamCity flow. It runs right before compiling my code.

Get-ChildItem -Recurse -Filter "*.*csproj" | % {
    Write-Host $_.Name
    $filename = $_.Fullname
    $proj =
( Get-Content $_.Fullname ) $xmlNameSpace = new-object System.Xml.XmlNamespaceManager($proj.NameTable) $xmlNameSpace.AddNamespace("p", "") $nodes = $proj.SelectNodes("/p:Project/p:PropertyGroup[@Condition and not (p:TreatWarningsAsErrors)]", $xmlNameSpace) $touched = $false $nodes | ForEach-Object -Process { $e = $proj.CreateElement("TreatWarningsAsErrors", "") $e.set_InnerText("true") $_.AppendChild($e) | Out-Null $touched = $true } if ($touched) { Write-Host "Checkout $filename" $proj.Save("$($filename)") | Out-Null } }

this post was originally on the MasterDevs Blog

.NET, c# comments edit

Sometimes it is just much easier to deploy a single assembly that includes all dependencies. ILRepack and ILRepack.MSBuild.Task will do just that for you. Since I like to have Visual Studio and my build environment do this for me, I went with ILRepack.MSBuild.Task.

The Sample

In order to showcase packing an assembly into my program, first I need a program that has a dependency. I decided to go with a simple console app that has a dependency on the Humanizer NuGet package to tell you how long you have to wait until your birthday.

Usage:   repack [date]
  Prints how long it is until your birthday.
  If you don't supply your birthday, it uses mine.
23 weeks until your birthday

I created a new console project in Visual Studio and named it Repack. I then included the Humanizer DLL using the NuGet package manager.

You can find the source code on github.

Using ILRepack

All you need to do is add the following snippet at the end of your .csproj file. To do this, you can open up the .csproj file in notepad or your favorite text [editor])(

<Target Name="AfterBuild" Condition="'$(Configuration)' == 'Release'">
  <InputAssemblies Include="$(OutputPath)\$(AssemblyName).exe" />
  <InputAssemblies Include="$(OutputPath)\*.dll" />

Because we name the target AfterBuild, this code will automatically be run after msbuild or Visual Studio builds our project. Setting the condition ensures that this will only run when we are in release mode. You can definitely run this on debug builds, but it’s less likely that you’d want to.

The ItemGroup specifies lets us create a list of assemblies to include in the package. The first assembly should be your assembly. In my example it will be my executable file Repack.exe. Next, I include all the DLLs in the output directory. This way, if I add a new dependency later, it will be included automatically.

Note that the order does matter. You will want to put the .exe first in this list.

Next all we need to do is call ILRepack. You can specify the output file to be anywhere you like, but in this example I overwrite the existing Repack.exe with the packed version.

Once you rebuild your project (in release mode), you can copy the EXE anywhere you want and it will run.


ILRepack.MSBuild.Task let’s you package DLL’s into your EXE file so you can copy just the executable anywhere and not have to worry about deploying the dependencies as well.

Full sample code can be found on github.

Happy coding.

this post was originally on the MasterDevs Blog

c#, Tools comments edit

Occasionally I need to FTP into one of my Azure websites. Sometimes it’s to look at the logs; other times to upload a few files. Just about every time I go to do this, I realize that I don’t know the credentials. So I go and download the publish profile and open it up in my favorite text editor to get the FTP information and manually enter that in FileZilla.

I quickly became tired of doing this, so I wrote a console app that will do it for me. The source code and executable are available on my GitHub.


  1. Download your publish profile
  2. Run the command line tool
  3. Import the config file to FileZilla

Download your publish profile

Log on to the Azure management portal for the website you want to FTP into. On the right side of the dashboard page you will see an option to “Download the publish profile.” Click it and you’re on your way.

When downloaded the file will look something like this:

<?xml version="1.0" encoding="utf-8" ?>
    profileName="TestSite - Web Deploy"
    userPWD="test password"
    profileName="TestSite - FTP"
    userPWD="test password"

Obviously, all the pertinent connection information has been scrubbed clean. But you get the idea.

Run the command line tool

Next thing you need to do is run pubToFz.exe to convert the publish profile into a format that FileZilla understands. Assuming the default download location, the command would look like this:

pubToFz %home%\downloads\testSite.publishProfile

By default, the tool creates an file named FileZilla.xml in the current directory. The file will look something like this.

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
      <Pass encoding="base64">base 64 encoded test password</Pass>
      <Comments />
      <LocalDir />
      <RemoteDir />

Again, this was scrubbed clean.

Import the config file to FileZilla

Now all you have to do is open up FileZilla and import the config file that you just saved.

this post was originally on the MasterDevs Blog

comments edit

— layout: post disqus_identifier: #43 comments: true categories: [ cmd, tips ] — I recently stumbled across DOSKEY while reading StackOverflow. Reading the documentation I stumbled across something old and something new.


F7    Displays command history
F8    Searches command history

I knew about F7 and use it constantly when I’m on the command line. It pops up a scrollable list of your recent commands.

F8 lets you cycle through commands in your history with a search term.

Suppose you had previously typed a complex command. In the example I have below, I used the command echo Foxtrot Golf. To find and execute it again all you need to do is type the beginning of the command and then press the F8 key. In the example, I type echo on the command prompt and cycle through all the commands that start with that by pressing F8. To narrow it down a bit more, I type in echo F and then press F8 to get all the commands that start with that. Note that it is case sensitive.

this post was originally on the MasterDevs Blog

In Android, your options are kind of small for setting a font purely in XML.

In this post, I’ll create a converter so we can specify the font in an MvvmCross binding.

Getting a font

Before going any further, you need to actually get and include a font in your android app. For this example I will be using Fontin. The main reason I’m using it is because it was easy to find and is free. Download the TTF versions and and include them in your project. Add a new subdirectory to the Assets folder in your android project named “font”. Drop the files into that folder and include them in your project. Make sure that the build action is set to AndroidAsset.

If you get the following error, make sure that the font names are spelled exactly the same as the folder and file names, including capitalization.

java.lang.RuntimeException: native typeface cannot be made

In the example from my screenshots, my font name should be: font/Fontin-Italic.ttf.

And again, capitalization matters.

Binding to Typeface

The first step is to use MvvmCross. Next all you really need to do is bind directly to the Typeface property on the TextView. They Typeface property is an instance of of Typeface (nothing surprising there) which meanst that you’ll need a converter.

      local:MvxBind="Text Hello; Typeface StringToFont(FontName)" />

The converter is pretty straight forward:

public class StringToFontConverter : MvxValueConverter<string, Typeface>
    private static Dictionary<string, Typeface> _cache = new Dictionary<string, Typeface>();
    protected override Typeface Convert(string fontName, Type targetType, object parameter, System.Globalization.CultureInfo culture)
            if (!fontName.StartsWith(@"font/")) fontName = @"font/" + fontName;
            if (!fontName.EndsWith(".ttf")) fontName += ".ttf";
            if (!_cache.ContainsKey(fontName))
                _cache[fontName] = Typeface.CreateFromAsset(Application.Context.Assets, fontName);
            return _cache[fontName];
        catch (Exception e)
            Android.Util.Log.Error("AndroidFont", e.ToString());
            return Typeface.Default;

First thing the converter does is to clean the input, ensuring that the font name starts with the directory and ends with the ttf extension. This makes the binding a bit easier in that we don’t have to remember to get the full font path correct.

It then check its static cache to see if it already has an instance of the the font, if not it creates one by calling Typeface.CreateFromAsset. If creation fails it does some logging and return the default typeface. This is important because in my testing VisualStudio hang pretty hard under some circumstances where errors were ignored.

Fire this up, and you’ll see that the font is in fact set.

One problem with this example is that we are forcing the ViewModel to know the correct name for the font. In some cases that’s ok, in others, we won’t want to handle font in the VM layer. Luckily we can use Tibet binding and just bind to a static string in the xml. Just remember to surround it with single quotes.

    local:MvxBind="Text Hello; 
                   Typeface StringToFont('Fontin-Bold')" />


Here’s a sample layout putting everything together.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""
        local:MvxBind="Text Hello; Typeface StringToFont('Fontin-Bold')" />
<!-- Binding to the View Model -->
        android:text="Bind to Typeface:  " />
        local:MvxBind="Text Hello; Typeface StringToFont(SelectedFont)" />
        local:MvxBind="SelectedItem SelectedFont; ItemsSource FontNames;" />
<!-- Binding to a constant -->
        android:text="Constant Typeface:  " />
        local:MvxBind="Text Hello; Typeface StringToFont('Fontin-Bold')" />
<!-- Error -->
        android:text="Error Handling:  " />
        local:MvxBind="Text Hello; Typeface StringToFont('Not a font name')" />

The edit box and first text box are bound to the value in the spinner. The second text box is staticly bound to the bold font. The last text box is bound to a value that is not a valid font and defaults to the default Android font.

Here’s a link to the working project on git.

Happy Coding

this post was originally on the MasterDevs Blog

To recap, I’m writing a shopping cart app for Windows Phone, Android, and iOS. The purpose of the app is primarily to let me use Forms. Each post will build on top of the previous one.

Last time I fiddled with async loading and added an application level menu. This week I’m going to add native views on Windows Phone and Android using PageRenders.

Recap and Code

This is the tenth post in the series, you can find the rest here:

  • Day 0: Getting Started (blog / code)
  • Day 1: Binding and Navigation (blog / code)
  • Day 2: Frames, Event Handlers, and Binding Bugs (blog / code)
  • Day 3: Images in Lists (blog / code)
  • Day 4: Search and Barcode Scanner (blog / code)
  • Day 5: Dependency Injection (blog / code)
  • Day 6: Styling (blog / code)
  • Day 7: Attached Behaviors (blog / code)
  • Day 8: Writing to Disk (blog / code)
  • Day 9: App and Action Bars (blog / code)
  • Day 10: Native Views (blog / code)

For a full index of posts, including future posts, go to the GitHub project page.

About Page

I want to add a quick about page to the app. I’ll be honest here, I couldn’t think of a great example where the views would be drastically different depending on the platform. They will probably look almost exactly the same. Specifically, they will contain two buttons that will take the user to this blog, (specifically this post), or to the GitHub project page. The WinPhone version will contain two extra labels. Not overly fancy, but educational enough.

First things first, I’ll add a simple view model:

public class AboutViewModel : BaseViewModel
    public AboutViewModel()
        OpenUrlCommand = new Command<string>(s => Device.OpenUri(new Uri(s)));
    public string BlogUrl { get { return @""; } }
    public string CodeUrl { get { return @""; } }
    public ICommand OpenUrlCommand { get; private set; }

The only thing remotely interesting here is the Device.OpenUri(…) call. It does pretty much what you expect it to, namely opens the URI in the native browser. This view model is so simple that I don’t even really need to inherit from BaseViewModel. I do anyway just to future proof it and for consistency.

Next thing I need to do is add the AboutPage stub in in the core project (ShoppingCart.csproj). For reasons I’ll go into a bit later, this can’t be defined in Xaml.

namespace ShoppingCart.Views
    public class AboutPage : ContentPage
        public AboutPage()
            Title = "About";
            Content = new Label { Text = "This page is not available for your platform", }; 

Nice and simple. Just set the title and get out of there.

Now all I need to do is wire up a button somewhere to navigate me to this page. I already have an action bar and app bar on the main CategoriesListPage, so I’ll just add another button there.

  <ToolbarItem Name="Log Out" Command="{Binding LogOut}"  Order="Primary" Priority="0">
      <OnPlatform x:TypeArguments="FileImageSource"
                  Android="ic_action_logout.png" />
  <ToolbarItem Name="About"
               Command="{Binding AboutCommand}" 

I don’t bother with an icon, so I put it in the “Secondary” order. On WinPhone and Droid this means it will only show up win you hit the three dots to expand the menu. It’s bound to the “AboutCommand” which just uses the existing navigation system to take you to the AboutPage.


The first step to getting a native page shown is to define a native page. So here’s the Xaml for my WinPhoneAboutPage.

    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    <Grid x:Name="LayoutRoot" Background="White">
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
        <StackPanel Grid.Row="0" Margin="12,17,0,28">
            <TextBlock Text="Shopping Cart"
                       Style="{StaticResource PhoneTextNormalStyle}"
                       Foreground="{StaticResource PhoneAccentBrush}" />
            <TextBlock Text="about" Margin="9,-7,0,0"
                       Style="{StaticResource PhoneTextTitle1Style}"
                       Foreground="{StaticResource PhoneAccentBrush}" />
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
                <RowDefinition Height="*" />
                <RowDefinition Height="auto" />
                <RowDefinition Height="*" />
                <RowDefinition Height="auto" />
                <RowDefinition Height="*" />
            <Button Grid.Row="1" Content="Browse Source Code"
                    Command="{Binding OpenUrlCommand}"
                    CommandParameter="{Binding CodeUrl}" />
            <Button Grid.Row="3" Content="Read Blog"
                    Command="{Binding OpenUrlCommand}"
                    CommandParameter="{Binding BlogUrl}" />

A very standard view. The next thing I need to do is to set the DataContext of the page so my bindings actually work. I’m inclined to follow the MvvmLight model with the ServiceLocator, but in all honesty that seems like a lot of ceremony for what I know will be one instance of a native view in this app. So, I cheat a little a bit and just manually set the context in the code behind:

public partial class WinPhoneAboutPage : PhoneApplicationPage
    public WinPhoneAboutPage()
        this.DataContext = ShoppingCart.App.AboutViewModel;

Now to wire it up I’ll add a PageRenderer:

public class WinPhoneAboutPageRenderer :  Xamarin.Forms.Platform.WinPhone.PageRenderer
    protected override void OnElementChanged(ElementChangedEventArgs<Page> e)
        this.Children.Add(new AboutPage());

And now that we have the PageRenderer defined, we need to tell the system to actually use it:

[assembly: ExportRenderer(typeof(ShoppingCart.Views.AboutPage), 

This line can go anywhere in the assembly (just not within a namespace). A lot of the examples place it in the same file as the renderer. This has the benefit of keeping it close to where we’re using it. I’ve elected to add this line at the beginning of the WinPhoneSetup file. If we wind up with several definitions for renderers, it would be nice to have them all in one place. I could be wrong about this.

Firing up the emulator and this looks… more than a little wrong.

So, on my fist pass of the ShoppingCart.AboutPage, I had added a label and two buttons. When the WinPhoneAboutPageRenderer created the WinPhoneAboutPage, it just overlaid it on top of the existing controls. Ok, so what if we add a call to Children.Clear()? This still doesn’t look right, and to show exactly what’s wrong, I’ve added a splash of color to the page.

I set the background color of the entire page to red, and of the grid with my buttons to a light green. As you can see, it’s not exactly taking up the entire page.

Children.Add doesn’t seem to be working for me at all, so I’ll try calling SetNativeControl. The problem here is that since I’ve inherited from PageRenderer it expects a Xamarin.Forms.Page and I have a Microsoft.Phone.Controls.PhoneApplicationPage. So I need to change what I’m inheriting from.

public class WinPhoneAboutPageRenderer 
  : VisualElementRenderer<Xamarin.Forms.Page, 
    protected override void OnElementChanged(ElementChangedEventArgs<Page> e)
        SetNativeControl(new WinPhoneAboutPage());

Now that I’m inheriting from the VisualElementRenderer (the base class for the PageRenderer), I can specify that the object I’ll specify to replace the Xamarin.Forms.Page will be a WinPhone page. Now it’s a simple matter of passing SetNativeControl a new instance of my WinPhoneAboutPage. This winds up looking like what I want.

Droid About Page

Moving on to Droid, I create an xml file defining my layout.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""
        android:layout_weight="1" />
        android:text="Read Blog" />
        android:layout_weight="1" />
        android:text="Browse Code" />
        android:layout_weight="1" />

Again, simple two buttons. The views are just there as spacers.

And pretty much straight from the samples, here’s my renderer:

public class DroidAboutPageRenderer : PageRenderer
    private Android.Views.View _view;
    protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Page> e)
        AboutViewModel viewModel = App.AboutViewModel;
        var activity = this.Context as Activity;
        _view = activity.LayoutInflater.Inflate(Resource.Layout.AboutLayout, this, false);
        var blogButton = _view.FindViewById<Button>(Resource.Id.button_blog);
        var codeButton = _view.FindViewById<Button>(Resource.Id.button_code);
        blogButton.Click += (sender, ev) => viewModel.OpenUrlCommand.Execute(viewModel.BlogUrl);
        codeButton.Click += (sender, ev) => viewModel.OpenUrlCommand.Execute(viewModel.CodeUrl);
    protected override void OnLayout(bool changed, int l, int t, int r, int b)
        base.OnLayout(changed, l, t, r, b);
        var msw = MeasureSpec.MakeMeasureSpec(r - l, MeasureSpecMode.Exactly);
        var msh = MeasureSpec.MakeMeasureSpec(b - t, MeasureSpecMode.Exactly);
        _view.Measure(msw, msh);
        _view.Layout(0, 0, r - l, b - t);

First things first, I grab the view model from my static cache. Then I just inflate my view, and start grabbing my buttons so I can add click handlers. Android doesn’t have a concept of data binding, so adding click handlers is a tad manual. Once everything is wired up, I add my view to the renderer. And now I have some errors.

I/MonoDroid( 1596): UNHANDLED EXCEPTION: System.InvalidOperationException: SetElement did not create the correct number of children
I/MonoDroid( 1596):   at Xamarin.Forms.Platform.Android.VisualElementPackager.SetElement (Xamarin.Forms.VisualElement oldElement, Xamarin.Forms.VisualElement newElement) [0x00000] in <filename unknown>:0 
I/MonoDroid( 1596):   at Xamarin.Forms.Platform.Android.VisualElementPackager.Load () [0x00000] in <filename unknown>:0 
I/MonoDroid( 1596):   at Xamarin.Forms.Platform.Android.VisualElementRenderer`1[Xamarin.Forms.Page].SetPackager (Xamarin.Forms.Platform.Android.VisualElementPackager packager) [0x00000] in <filename unknown>:0 
I/MonoDroid( 1596):   at Xamarin.Forms.Platform.Android.VisualElementRenderer`1[Xamarin.Forms.Page].SetElement (Xamarin.Forms.Page element) [0x00000] in <filename unknown>:0 
I/MonoDroid( 1596):   at Xamarin.Forms.Platform.Android.VisualElementRenderer`1[Xamarin.Forms.Page].Xamarin.Forms.Platform.Android.IVisualElementRenderer.SetElement (Xamarin.Forms.VisualElement element) [0x00000] in <filename unknown>:0 
I/MonoDroid( 1596):   at Xamarin.Forms.Platform.Android.RendererFactory.GetRenderer (Xamarin.Forms.VisualElement view) [0x00000] in <filename unknown>:0 
I/MonoDroid( 1596):   at Xamarin.Forms.Platform.Android.NavigationRenderer.SwitchContentAsync (Xamarin.Forms.Page view, Boolean animated, Boolean removed) [0x00000] in <filename unknown>:0 
I/MonoDroid( 1596):   at Xamarin.Forms.Platform.Android.NavigationRenderer.OnPushAsync (Xamarin.Forms.Page view, Boolean animated) [0x00000] in <filename unknown>:0 
I/MonoDroid( 1596):   at Xamarin.Forms.Platform.Android.NavigationRenderer.PushViewAsync (Xamarin.Forms.Page page, Boolean animated) [0x00000] in <filename unknown>:0 
I/MonoDroid( 1596):   at Xamarin.Forms.Platform.Android.NavigationRenderer.OnPushed (System.Object sender, Xamarin.Forms.NavigationRequestedEventArgs e) [0x00000] in <filename unknown>:0 
I/MonoDroid( 1596):   at Xamarin.Forms.NavigationPage+<PushAsync>d__c.MoveNext () [0x00000] in <filename unknown>:0 
I/MonoDroid( 1596): --- End of stack trace from previous location where exception was thrown ---
I/MonoDroid( 1596):   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x00000] in <filename unknown>:0 
I/MonoDroid( 1596):   at System.Runtime.CompilerServices.TaskAwaiter.GetResult () [0x00000] in <filename unknown>:0 
I/MonoDroid( 1596):   at ShoppingCart.Services.AppNavigation+<ShowAbout>d__4.MoveNext () [0x0001e] in c:\code\Repos\spikes\XamarinSpikes\ShoppingCart\ShoppingCart\ShoppingCart\Services\AppNavigation.cs:35 
I/MonoDroid( 1596): --- End of stack trace from previous location where exception was thrown ---
I/MonoDroid( 1596):   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x00000] in <filename unknown>:0 
I/MonoDroid( 1596):   at System.Runtime.CompilerServices.TaskAwaiter.GetResult () [0x00000] in <filename unknown>:0 
I/MonoDroid( 1596):   at ShoppingCart.ViewModels.CategoriesListViewModel+ctor>b__2>d__a.MoveNext () [0x0001b] in c:\code\Repos\spikes\XamarinSpikes\ShoppingCart\ShoppingCart\ShoppingCart\ViewModels\CategoriesListViewModel.cs:39 

The stack trace doesn’t say it, but this error is raised when you call AddView if the ShoppingCart.AboutPage has already had the Content property set. So, I go back to the AboutPage, and pull out the Content property:

namespace ShoppingCart.Views
    public class AboutPage : ContentPage
        public AboutPage()
            Title = "About";

Back to the DroidAboutPageRenderer, the OnLayout override is there to make sure that the view is sized to fit the whole screen. From the top left (0, 0) to the very bottom right (r-l, b-t).

Don’t forget to register it. Again, I decided to add this to the top of DroidSetup.cs.

[assembly: ExportRenderer(typeof(ShoppingCart.Views.AboutPage), 

Running this up, we get a wonderful (if not pretty) native layout:

iOS About Page (A Default)

Don’t get too excited. I still don’t have access to an iDevice. But I wanted to at least try and make sure that the app wouldn’t crash on iOS. I’ve updated the core definition of the AboutPage to at least show a label explaining that this page wasn’t available.

public class AboutPage : ContentPage
    public AboutPage()
        Title = "About";
        if (Device.OS != TargetPlatform.Android)
            Content = new Label
                Text = "This page is not available for your platform",

Since we saw that Android get’s really upset if you set the content in the core version of the page and then try to use a PageRenderer in the platform (at least with my implementation of the renderer), I make sure that we aren’t running on an Android device before setting the content. The content could have been set to something much more complicated than just a simple label. It could have even used data bindings like any other page.

Since I don’t have an iPhone, here’s what it looks like on a Droid.

And now we have native views on 2 out of 3 platforms.

Happy Coding

this post was originally on the MasterDevs Blog