I'm Johan Danforth and this is my dev blog - a mix of .NET, ASP.NET, Rest, Windows Phone, Azure and some iPhone as well. I like to dig into brand new stuff and figure out how it works, then share it with fellow devs. Cheers!

  • Formatting File Upload Input with Bootstrap

    If you’re using file upload forms in your Bootstrap themed website and would like to format the button and the field nicely, take a peek at this article by Cory LaViska. He nails it.


    A small example which produces an input-group like this (“Fil” means file in Swedish):


    <div class="editor-label">
        <div class="input-group">
            <span class="input-group-btn">
                <span class=" btn btn-default btn-file">
                    välj fil... <input type="file" name="data" id="data">
            <input type="text" id="valdfil" class="form-control" readonly />
    <script type="text/javascript">
        $(document).ready(function () {
            $(document).on('change', '.btn-file :file', function () {
                var input = $(this),
                    numFiles = input.get(0).files ? input.get(0).files.length : 1,
                    label = input.val().replace(/\\/g, '/').replace(/.*\//, '');
                input.trigger('fileselect', [numFiles, label]);
            $('.btn-file :file').on('fileselect', function (event, numFiles, label) {
  • Using FontAwesome in Universal Apps

    image_thumb2Want to use FontAwesome in Universal Apps (both Windows Phone & Windows 8.1). The procedure is similar to how you do it for WPF:

    1) Install-Package FontAwesome

    2) Mark the file /fonts/fontawesome-webfont.ttf with “Build Action” set to “Content” (not “Resource”)

    3) Try out the font like this in a sample Windows Phone main page:

        <TextBlock Text="&#xf09b;"                 FontFamily="fonts/fontawesome-webfont.ttf#FontAwesome" />

    And you should see:


    Note that the steps and syntax is a bit different from how you do it in WPF.

  • Using FontAwesome in WPF

    imageWant to use FontAwesome (http://fontawesome.io/) in your WPF application? With a few simple steps you can do it.

    1) Use Nuget and Install-Package FontAwesome

    2) Mark the file /fonts/fontawesome-webfont.ttf and set it’s “Build Action” to “Resource”

    3) Test the font in a simple TextBlock like this:

    <Window x:Class="FontAwesomeWPFBlogTest.MainWindow"         
    ="525">     <Grid>         <Viewbox>             <TextBlock Text="&#xf09b;"
                           FontFamily="pack://application:,,,/fonts/#FontAwesome" />         </Viewbox>     </Grid> </Window>

    Run it and you should see this:


    The “hardest” thing is to make sure you enter the right icon-hexcode for the Text property. You can look at the different icons available in the icon-gallery page on http://fontawesome.io/icons/ then check the name of the icon you like. After that, go to the /Contents/font-awesome.css file in your project and look it up there, say for example the paint-brush icon:

    .fa-paint-brush:before {   content: "\f1fc";

    The content-value says “\f1fc” which is the hex value of the paint-brush symbol in the font and that is the value you have to enter in the Text-property in your XAML:


  • Lazy Loading TreeView Sample with ASP.NET MVC and jqTree

    I’ve been looking for a lightweight TreeView library to use with ASP.NET MVC, and I think I’ve found my “weapon of choice” – jqTree.

    The code is available on https://github.com/mbraak/jqTree and the author mbraak (Marco Braak) is very active in the “issues” section answering questions from users.

    The package is not available on Nuget at the moment though, but it’s easy enough to download and set up manually.

    Download and unzip the code from Github, copy the files jqtree.css and jqtree-circle.png to your /Content folder, and copy the tree.jquery.js file to your /Scripts folder. Then open up your /App_Start/BundlesConfig.cs file and add the files to your bundles, something like this:


      bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
      bundles.Add(new StyleBundle("~/Content/css").Include(

    Add this viewmodel to hold the treeview node data:

    public class Node
        public string label { get; set; }
        public string id { get; set; }
        public bool load_on_demand { get; set; }
        public Node(string label, string id, bool loadOnDemand = true)
            this.label = label;
            this.id = id;
            this.load_on_demand = loadOnDemand;


    Then create a controller method in HomeController.cs which will be called on-demand/lazily by the TreeView control in your HTML-view. My action is called /Home/Nodes and takes and optional “node” parameter which holds the id of the treeview-node being “expanded”. This is some simple test-code using the local computer folder structure on the D-drive just to try it out. If it’s a folder I’m passing “true” to the load_on_demand property of the jqTree javascript model:

    public ActionResult Nodes(string node)
        Debug.WriteLine("id=" + node);
        var list = new List<Node>();
        if (node == null)
            var items = Directory.GetFileSystemEntries("D:/");
            foreach (var item in items)
                list.Add(new Node(Path.GetFileName(item), item, Directory.Exists(item)));
            var items = Directory.GetFileSystemEntries(node);
            foreach (var item in items)
                list.Add(new Node(Path.GetFileName(item), item, Directory.Exists(item)));
        return Json(list, JsonRequestBehavior.AllowGet);

    In your Razor HTML-view, the base for the TreeView control is a simple <div> tag, with an data-url attribute pointing at the method it should call to get data:

     <div id="tree1" data-url="/home/nodes"></div>

    and finally some javascript/jquery to initialize the TreeView and add some handling, this code loads the treeview, sets the icons I would like to have (from font-awesome) and adds a click-handler which just writes out the selected node name to the console.

    @section scripts {
        <script language="javascript" type="text/javascript">
            $(function () {
                    closedIcon: $('<i class="fa fa-plus"></i>'),
                    openedIcon: $('<i class="fa fa-minus"></i>'),
                    dragAndDrop: false,
                    selectable: false
                // bind 'tree.click' event
                    function (event) {
                        // The clicked node is 'event.node'
                        var node = event.node;
                        console.log('clicked ' + node.name );

    This is all you need to do, and it’s possible (and quite easy too) to modify the look of the tree in the view, have your own icons and such. Ask questions in the “issues” section of the project and I’m sure you’ll get your answers - https://github.com/mbraak/jqTree/issues

    Thanks to mbraak for cool stuff, me likes Ler

  • Converting from Silverlight To Universal Apps – MVVM, ListView and Commands

    Converting a Windows Phone Silverlight app to a Universal WinRT app isn’t straight forward, and it’s hard to Google for answers. I converted one of my not too advanced apps to universal Windows/Phone and here are some of the things I had to do. The quick-list for Xaml changes is here.

    I’m using MVVMLight because it makes it so much easier to develop apps. When developing the Silverlight app I used Interation.Triggers and EventTrigger/EventToCommand to fire off commands in my ViewModel from clicked ListBox items. When converting to universal/winrt I ran into problems with referencing the Microsoft.Expression.Interactions assemblies for the Windows and Windows Phone projects so I decided to code up a simple ItemClickCommand instead which uses an attach property on the ListView. Based (more or less a replica) on the code by Marco Minerva, the command-class looks like this:

    public static class ItemClickCommand
    public static readonly DependencyProperty CommandProperty =
    DependencyProperty.RegisterAttached("Command", typeof (ICommand),
    typeof (ItemClickCommand), new PropertyMetadata(null, OnCommandPropertyChanged));

    public static void SetCommand(DependencyObject d, ICommand value)
    d.SetValue(CommandProperty, value);

    public static ICommand GetCommand(DependencyObject d)
    return (ICommand) d.GetValue(CommandProperty);

    private static void OnCommandPropertyChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
    var listView = dependencyObject as ListViewBase;
    if (listView != null)
    listView.ItemClick += (sender, itemClickEventArgs) =>
    var viewBase = sender as ListViewBase;
    var command = GetCommand(viewBase);

    if (command != null && command.CanExecute(itemClickEventArgs.ClickedItem))
    The command in the ViewModel is set up like this:

    public class SportsViewModel : ViewModelBase
    public ObservableCollection<Sport> Sports { get; set; }
    public RelayCommand<Sport> SportSelected { get; private set; }

    public SportsViewModel()
    SportSelected = new RelayCommand<Sport>(sport =>
    if (sport == null) return; //should not happen
    _navigationService.NavigateTo(typeof(LeaguesView), sport.Id);


    //and so on...
    And this is how I use this command in the XAML view:

    <ListView IsItemClickEnabled="True" SelectionMode="None"
    commands:ItemClickCommand.Command="{Binding SportSelected}"
    ItemsSource="{Binding Sports}" >
    <TextBlock Text="{Binding Name}" />

    Remember to set the IsItemClickEnabled and SelectionMode properties for your ListView or nothing will happen when you click the items in the list Smile

  • Converting from Silverlight To Universal Apps – Themes and Styles

    Converting a Windows Phone Silverlight app to a Universal WinRT app isn’t straight forward, and it’s hard to Google for answers. I converted one of my not too advanced apps to universal Windows/Phone and here are some of the things I had to do. The quick-list for Xaml changes is here.

    In my Windows Phone Silverlight app I used a whole bunch of built in static resources for the control styles. You’ll have to go through them all and create your own or use new ones that work well on both Windows-devices and the Phone. To get better control of how controls are styled for shared views in Windows and Phone, I create 2 different MyStyles.xaml resources and place one in each project, then reference them in the App.xaml like this:

    <ResourceDictionary >
    <ResourceDictionary Source="ms-appx:///MyStyles.xaml"></ResourceDictionary>
    <!-- MVVMLight viewmodel locator -->
    <viewModel:ViewModelLocator x:Key="Locator" />

    This way I can fine tune font sizes and such in both Windows and Phone view. The MyStyles.xaml for the Windows project may look like this:
    <!--     WINDOWS      -->

    <Style x:Key="MyTitleStyle" TargetType="TextBlock">
    <Setter Property="FontSize" Value="40"></Setter>
    <Setter Property="Foreground" Value="DarkOliveGreen"></Setter>
    <Style x:Key="MyGameDetailsBigStyle" TargetType="TextBlock">
    <Setter Property="FontSize" Value="60"></Setter>
    <Style x:Key="MyDateBorderStyle" TargetType="Border">
    <Setter Property="Height" Value="100" />
    <Setter Property="Width" Value="100" />

    And in the same file in the Windows Phone project I can actually use a resource that displays the phone accent color:

    <!--     WINDOWS PHONE    -->
    <Style x:Key="MyTitleStyle" TargetType="TextBlock">
    <Setter Property="FontSize" Value="30"></Setter>
    <Setter Property="Foreground" Value="{ThemeResource PhoneAccentBrush}"></Setter>
    <Style x:Key="MyGameDetailsBigStyle" TargetType="TextBlock">
    <Setter Property="FontSize" Value="30"></Setter>
    <Style x:Key="MyDateBorderStyle" TargetType="Border">
    <Setter Property="Height" Value="60" />
    <Setter Property="Width" Value="60" />

  • Converting from Silverlight To Universal Apps – Xaml Stuff

    Converting a Windows Phone Silverlight app to a Universal WinRT app isn’t straight forward, and it’s hard to Google for answers. I converted one of my not too advanced apps to universal Windows/Phone and here are some of the things I had to do.

    The xaml needs a lot of changes…  and here’s the quick-list of things I needed to change in my XAML views to make them work in universal winrt.

    The XAML quick-list

    1) In the “header”, change the type PhoneApplicationPage to Page (obviously in the code behind too).

    2) Remove the SupportedOrientation and Orientation properties from the Page tag.

    3) Remove the SystemTray properties from the Page tag.

    4) Remove all references to StaticResource-properties that reference Phone* stuff.

    5) If you use TransitionService-stuff from the Windows Phone Toolkit – remove them! You get basic transitions set up for free in the new App-class you get from a new universal project.

    6) If you use transparent background in your page, grid or controls, change to the new ThemeResource ApplicationPageBackgroundThemeBrush. This will reflect the theme background on your phone and/or computer and works as expected on Windows too.

    7) Change your ListBox controls to ListView.

    8) Convert your ApplicationBar to use the new BottomAppBar instead.

    I’ll post some more details about commands and styles soon.