IBlog<JohanDanforth>

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!

  • 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.

    Html:

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

    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.left,
            .active.right {
                left: 0;
                opacity: 0;
                z-index: 1;
            }
    
            .next.left,
            .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):

    image

    <div class="editor-label">
        <label>Fil</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">
                </span>
            </span>
            <input type="text" id="valdfil" class="form-control" readonly />
        </div>
    </div>
    
    <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) {
                console.log(numFiles);
                console.log(label);
                $("#valdfil").val(label);
            });
        });
    
    </script>
    
  • 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:

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

    And you should see:

    image

    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"         
    xmlns
    ="http://schemas.microsoft.com/winfx/2006/xaml/presentation"       
    xmlns
    :x="http://schemas.microsoft.com/winfx/2006/xaml"       
    Title
    ="MainWindow"       
    Height
    ="350"       
    Width
    ="525">     <Grid>         <Viewbox>             <TextBlock Text="&#xf09b;"
                           FontFamily="pack://application:,,,/fonts/#FontAwesome" />         </Viewbox>     </Grid> </Window>

    Run it and you should see this:

    image

    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:

    Text=”&#f1fc;”

  • 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(
                          "~/Scripts/bootstrap.js",
                          "~/Scripts/tree.jquery.js",    
                          "~/Scripts/respond.js"));
    
      bundles.Add(new StyleBundle("~/Content/css").Include(
                          "~/Content/bootstrap.css",
                          "~/Content/jqtree.css",
                          "~/Content/font-awesome.min.css", 
                          "~/Content/site.css"));

    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)));
            }
        }
        else
        {
            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 () {
                 $('#tree1').tree({
                    closedIcon: $('<i class="fa fa-plus"></i>'),
                    openedIcon: $('<i class="fa fa-minus"></i>'),
                    dragAndDrop: false,
                    selectable: false
                });
    
                // bind 'tree.click' event
                $('#tree1').bind(
                    'tree.click',
                    function (event) {
                        // The clicked node is 'event.node'
                        var node = event.node;
                        console.log('clicked ' + node.name );
                    }
                );
            });
    
        </script>
    }

    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))
    command.Execute(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}" >
    <ListView.ItemTemplate>
    <DataTemplate>
    <TextBlock Text="{Binding Name}" />
    </DataTemplate>
    </ListView.ItemTemplate>
    </ListView>

    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:

    <Application
    x:Class="Danforth.Matchkalender.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:viewModel="using:danforth.matchkalender.matchkalender.ViewModel">
    <Application.Resources>
    <ResourceDictionary >
    <ResourceDictionary.MergedDictionaries>
    <ResourceDictionary Source="ms-appx:///MyStyles.xaml"></ResourceDictionary>
    </ResourceDictionary.MergedDictionaries>
    <!-- MVVMLight viewmodel locator -->
    <viewModel:ViewModelLocator x:Key="Locator" />
    </ResourceDictionary>
    </Application.Resources>
    </Application>

    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      -->
    <ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

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

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

    <!--     WINDOWS PHONE    -->
    <ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Style x:Key="MyTitleStyle" TargetType="TextBlock">
    <Setter Property="FontSize" Value="30"></Setter>
    <Setter Property="Foreground" Value="{ThemeResource PhoneAccentBrush}"></Setter>
    </Style>
    <Style x:Key="MyGameDetailsBigStyle" TargetType="TextBlock">
    <Setter Property="FontSize" Value="30"></Setter>
    </Style>
    <Style x:Key="MyDateBorderStyle" TargetType="Border">
    <Setter Property="Height" Value="60" />
    <Setter Property="Width" Value="60" />
    </Style>
    </ResourceDictionary>

  • 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.