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!

  • New features in Dapper.Contrib

    I’ve given the official Dapper.Contrip package some love lately. So now all methods include support for lists! So instead of doing lots of insert calls in a loop, just call connection.Insert(myList); and Dapper/Contrib will interate and insert your entities effectively and fast!

    Dapper.Contrib now contains these methods:

    T Get<T>(id);
    IEnumerable<T> GetAll<T>();
    int Insert<T>(T obj);
    int Insert<T>(IEnumerable<T> list);
    bool Update<T>(T obj);
    bool Update<T>(IEnumerable<T> list);
    bool Delete<T>(T obj);
    bool Delete<T>(IEnumerable<T> list);
    bool DeleteAll<T>();

    For .NET 4.5 users there are also async methods available. For a complete and (almost) up-to-date help page on how Dapper.Contrib works, please visit https://github.com/StackExchange/dapper-dot-net/tree/master/Dapper.Contrib

    Dapper.Contrib can be installed from Nuget, read more at https://www.nuget.org/packages/Dapper.Contrib/

  • Effectively insert list of objects with Dapper

    If you are using Dapper as your sql/object mapper for .Net, you often find yourself inserting lists of objects. There are several ways of doing it, but maybe you're not doing it the fastest way possible (apart from hand-coding)?

    What most people do is iterating over the list add execute the insert for each item like this:

    foreach (var item in myList
        connection.Execute("INSERT INTO MYTABLE VALUES (@A, @B)", item);

    but this is not the fastest way becuse the Dapper Execute() extension takes a list as parameter and iterates for you:

    connection.Execute("INSERT INTO MYTABLE VALUES (@A, @B)", myList);

    I tested by inserting 10.000 simple objects into an SqlCe database and clocked the resuts. The first option took 1.88 seconds, and the second took 1.19 seconds! So, letting Dapper iterate and insert is not twice as fast, but almost!

    To install Dapper, run the following command in the Package Manager Console

    PM> Install-Package Dapper

  • jQuery validate and the comma decimal separator

    Oh this is such a simple and good solution that I must put it on my blog at least for my own future reference. Big THANKS to Lenard Gunda for writing this blog post


    If you live outside the US and have problems with getting client side validation accepting comma decimal separator in input fields - just overwrite jQuery validation range and number methods with these javascript lines in the end of all your javascript loading.

    $.validator.methods.range = function (value, element, param) {
        var globalizedValue = value.replace(",", ".");
        return this.optional(element) || (globalizedValue >= param[0] && globalizedValue <= param[1]);
    $.validator.methods.number = function (value, element) {
        return this.optional(element) || /^-?(?:\d+|\d{1,3}(?:[\s\.,]\d{3})+)(?:[\.,]\d+)?$/.test(value);

  • Bootstrap Image Carousel Fade Transition

    The built in image carousel animation for Bootstrap is a slide, which is nice, but I found this fade transition while Googling, and it seems to work well. I found it here on http://codepen.io/Rowno/pen/Afykb and it’s penned by Roland Warmerdam.


    <div class="carousel slide carousel-fade" data-ride="carousel">
        <div class="carousel-inner">
            <div class="item active">
                <img class="img-rounded" src="..." alt="...">
            <div class="item">
                <img class="img-rounded" src="..." alt="...">
            <div class="item">
                <img class="img-rounded" src="..." alt="...">

    Css (less):

    .carousel-fade {
        .carousel-inner {
            .item {
                opacity: 0;
                -moz-transition-property: opacity;
                -o-transition-property: opacity;
                -webkit-transition-property: opacity;
                transition-property: opacity;
            .active {
                opacity: 1;
            .active.right {
                left: 0;
                opacity: 0;
                z-index: 1;
            .prev.right {
                opacity: 1;
        .carousel-control {
            z-index: 2;
  • 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) {

    You must also add these CSS lines:

    .btn-file {
        position: relative;
        overflow: hidden;
    .btn-file input[type=file] {
        position: absolute;
        top: 0;
        right: 0;
        min-width: 100%;
        min-height: 100%;
        font-size: 100px;
        text-align: right;
        filter: alpha(opacity=0);
        opacity: 0;
        outline: none;
        background: white;
        cursor: inherit;
        display: block;
  • 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