post image

Polymer 0.5.4 Released

Polymer versions 0.5.3 and 0.5.4 released

Version 0.5.3 had a small dependency bug for Safari, this resulted in the rapid release of 0.5.4 to fix it.

Notable changes in the release are some paper-elements redesigned to adhere to the Material Design guideline.

Namely:

  1. paper-toggle-button
  2. paper-checkbox

The patch also had some fixes for some ShadowDOM polyfill issues in webcomponents.js.

For more info read the full release doc.

post image

Visual Studio 2015, Web Components & Sass

Visual Studio 2015 & Sass  – Clean styling of Polymer elements

Just a few years ago, or even less, if some one would have said “I’m working with a Google framework and a lot of open source plugins – in Visual Studio“, the instant reply would probably have been slightly Pythonesque, like -“He’s a witch, burn him!!!”. But what once might have been considered an unholy trifecta is now not only doable, but it’s even enjoyable.

The last few days I have been thinking about how to set up the styling of my Polymer elements in an easy way that would help me keep the CSS dry, preferably by use of variables, linked files and mixins. At the same time the tooling had to produce my desired file/folder structure and be usable from VS2015. The solution also had to be generic enough, install and setup once with no need for changes when adding new elements and stylesheets.

What I came up with was Sass run with Grunt, and here is the steps needed to set it up in Visual Studio.

Install Ruby and Sass

chocolatey logoFirst off, to be able to run Sass you need to install Ruby, as Sass is a Ruby gem.

The easiest way to install Ruby and Sass is to use Chocolatey (if you aren’t running Chocolatey yet you must check it out, just follow the link). When you have Chocolatey installed, just type the following two lines in your command window to install SASS and Ruby

choco install ruby

and

choco install sass

However, when installing Sass I got an error saying:

ERROR: Could not find a valid gem 'sass' (= 3.2.10), here is why:
 Unable to download data from https://rubygems.org/ - SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed (https://api.rubygems.org/specs.4.8.gz)

A workaround to this is to add the unsecured source for rubygems, enter the following in PowerShell

gem sources -a http://rubygems.org

This is a hack so don’t use this as a constant solution! But after this, installing Sass with Chocolatey worked fine.

Then remove the unsecured source after you installed Sass by executing the following

gem sources -r http://rubygems.org

Install Grunt-Contrib-Sass in VS2015

NPM-Restore_Packages

NPM – Restore Packages

Now it’s time to set up the tooling in Visual Studio.

1. Add “grunt-contrib-sass” to package.json, right click the NPM folder under Dependencies and choose “Restore Packages”. Expand thumbnail for visual description.

2. Configure Grunt by editing the gruntfile.js.

2.1 Enable Sass by adding this line of Javascript at the end of the file

grunt.loadNpmTasks('grunt-contrib-sass');

2.2 Enter the Sass task configuration you want to use, for example

 sass: {
            default: {
                files: [{
                    expand: true,
                    src: ['wwwroot/components/*/*.scss'],
                    dest: '<%= src %>',
                    ext: '.css',
                }]
            }
        }

This is all the setup needed in Visual Studio 2015 to enable you to run Sass from the Task Runner Explorer.

Path error – “You need to have Ruby and Sass installed and in your PATH for this task to work”

To be able to use the Sass task from VS2015, it needs Sass and Ruby not only to be installed but to be on the PATH as well. If you haven’t got Sass and Ruby on your path you will get this error message

Running "sass:default" (sass) task
Process terminated with code 6.
Warning:
You need to have Ruby and Sass installed and in your PATH for this task to work.
More info: https://github.com/gruntjs/grunt-contrib-sass
 Use --force to continue.

Aborted due to warnings.

You can check what’s on your path from PowerShell by typing

$env:path

Adding Ruby to your path from PowerShell permanently can be done with this PowerShell command

[Environment]::SetEnvironmentVariable("Path", $env:Path + ";C:\ruby215\bin", "Machine")

In my case “C:\ruby215″ is where Ruby was installed, this needs to be changed if your path is different!

Making sure Ruby and Sass are in the machines PATH

Use the following two commands in PowerShell to make sure that Ruby and Sass now are reachable from your path

ruby -v
sass -v

Both lines should report the current installed version, if everything is setup correctly.

Trying to run the task again

Trying to re-run the Sass task from Visual Studio now will result in the same problem as before, it’s telling us that Ruby and Sass needs to be on the path. But that’s because it’s keeping the state of the path since it was loaded, so just restart VS2015 and it will pick up the new path. Running the task after restart will now result in a successful run, given everything is setup properly.

A few words about the Sass config and presumed folder structure

The folder and file structure I’m using looks like something below

wwwroot
|- components
   |- my-element
   |   |- my-element.html
   |   |- my-element.scss
   |- another-element
   |   |- another-element.html
   |   |- another-element.scss
   |- styling
   |   |- _includes.scss
   |   |- _variables.scss
   |   |- misc-styling.html

What I wanted was to:

  1. Traverse my component tree
  2. Get all relevant linked scss files
  3. Output each compiled CSS file in to the respective components folder

Dissecting the Sass task configuration

The task configuration I used was:

 sass: {
            default: {
                files: [{
                    expand: true,
                    src: ['wwwroot/components/*/*.scss'],
                    dest: '<%= src %>',
                    ext: '.css',
                }]
            }
        }

The detailed explanation of the options

  • expand: true – needed to enable a dynamic file object
  • src: [‘wwwroot/components/*/*.scss’] – look for all sources that matches this pattern
  • dest: ‘<%= src %>’ - dynamically sets the destination path using a template, this will output the css file under the same directory as the source file
  • ext: ‘.css’ – replaces existing file endings on generated destination paths (in our case switching .scss to .css)

For more information about how to setup grunt tasks with dynamic file objects – see the documentation for Grunt.

 

Happy coding! :)

post image

Polymer in Visual Studio 2015 – Grunt-Vulcanize

Setting up a Vulcanize Grunt task in Visual Studio 2015

Developing Web Components from the new Visual Studio 2015 is a great experience with the added tooling. One problem with Web Components can be the large number of html-imports a big app will trigger. Even though an app might not be that large in actual code base size, it might be performing badly due to the sheer amount of loads needed to for all sub components.

The best way to reduce the amount of calls is to use Vulcanize, a tool that will concatenate your web components into one file.

Prerequisites and notes

First off, this solution builds upon the assumptions that all your html-imports are gathered in one file and one file only. This would be the file referred to as elements.html.
In my projects I have no html-imports in any of my Polymer elements. Any new imports I need I just add to the elements.html file instead, and I make sure I load that first thing in the apps life cycle. I am importing the polyfill library webcomponents.js and Polymer.html prior to my own components. I am keeping Polymer outside my own elements file to reduce time slightly, but mostly just because I had some initial problems when including it and in lack of having time to tinker with it so I just kept it out. You can see this exclusion under the configuration section, and you can expand on this to exclude other elements should you feel like it.

Secondly, a folder named built needs to exist under your wwwroot to accept the output from the vulcanization.

Install the grunt-vulcanize task

First install the grunt-vulcanize task by adding it to package.json:

{
    "version": "0.0.0",
    "name": "app_name",
    "devDependencies": {
        "grunt": "^0.4.5",
        "grunt-bower-task": "^0.4.0",

        //add the row below (version number might of course vary depending on point in time)
        "grunt-vulcanize": "^0.6.1"
    }
}

Configure the vulcanize task

Setup the vulcanize task in gruntfile.js by adding the section below to the grunt.initConfig method:

  vulcanize: {
            default: {
                options: {
                    strip: true,
                    excludes: {
                        imports: [
                          "polymer.html"
                        ]
                    }
                },
                files: {
                    'wwwroot/built/elements.html': 'wwwroot/pages/elements.html'
                },
            },
        }

In the task you can see how it is setup to exclude the polymer.html file, and also how removing comments and blocks of white-space by setting strip to true (it’s default is false). For all the options refer to the Grunt-Vulcanize ReadMe.
Under the files setup, do notice that the first parameter is the destination file and that the second parameter is the original file that should be vulcanized.

If you want it you can add a task alias for your vulcanize setup with:

grunt.registerTask("main_vulcanize", ["vulcanize:default"]);

And then don’t forget load the grunt-vulcanize plugin at the end of your file:

grunt.loadNpmTasks("grunt-vulcanize");

Running Vulcanize from Task Runner Explorer

First open the Task Runner Explorer in Visual Studio 2015 by expanding View>Other Windows and click Task Runner Explorer. Expand image to the right to see location of the Task Runner Explorer in the menu. TaskRunnerExplorer_menu

In the Task Runner Explorer window you can then see your vulcanize task as well as any Alias you setup for it, see image below.

Running your vulcanize task is now as simple as:

  1. Double clicking your alias name or the task name
  2. Right clicking alias name or task name and selecting “Run” from the context menu
  3. Binding the task or alias in the context menu to one of the build steps, below I choose to bind it to “After Build” which means my vulcanization will be run automatically after every time I build my project. Very nice since ctrl-shift-b is inprinted in muscle memory by now ;)

Grunt Tasks in Task Runner Explorer

 

post image

Rookie mistakes developing Web Components in Polymer

Developing Web Components is both fun as well as frustrating at times. Maybe it’s the fact that I’m so used to coding typed languages (C# & Java) with loads of compiler help, or maybe it’s the fact that debugging web pages aren’t always a breeze combined with that Web Components are still fairly raw. But I often found myself scratching my chin thinking “What the …?”. Here’s a short list of three confounding issues you might run in to when starting to develop Web Components and using Polymer.

1. Nothing is being rendered on screen, nothing!

Q: I just added a new component and now nothing is being rendered on my screen. I’m not kidding, NOTHING! My entire site is just white, there seems to be elements there when I mouse over but they are all just withe?!?!

A: This is done by declaring a new Polymer element that hasn’t got a noscript attribute, has a script tag but it lacks a call to the Polymer method. See code snippet below.

<polymer-element name="demo-element">
    <template>
        some awesome html code
    </template>

    <script>
        //scary empty script tag!!
    </script>
</polymer-element>

2. My new element isn’t just lacking style, it’s refusing all styling!

Q: I have this cool new Polymer element that I just made and it’s not being styled by the CSS I defined in it, what gives?

A: This is probably due to a slightly misplaced style tag. It’s easy to miss that the style tag must be located within the template tag and that it can’t be located just below the Polymer element declaration. See code snippet below.

<polymer-element name="demo-element">
    <style>
        /*this is a misplaced style tag, it should be within the template tag below!*/
    </style>

    <template>
        some awesome html code
    </template>

    <script>
        //scary empty script tag!!
    </script>
</polymer-element>

3. Console keeps nagging: Uncaught Already registered (Polymer) prototype for element my-element

Q: I have this great app written all in web components, but I see a lot of errors in the console saying “Uncaught Already registered (Polymer) prototype for element new-list”, what gives?

A: This is what happens if you forget to remove the noscript attribute as you later register the element with the Polymer method. I often start first draft of my elements by defining noscript on them and all too often I forget to remove the attribute as the elements evolve. :( See code snippet below.

<polymer-element name="demo-element" noscript>
    <template>
        <style>
            /*this is a correctly placed style tag!*/
        </style>

        some awesome html code
    </template>

    <script>
        Polymer({
            //some rad JavaScript code!!
        });
    </script>
</polymer-element>
post image

Deploy ASP.Net 5 apps in IIS

Deploying an ASP.Net 5 web application in IIS

The preview of Visual Studio 2015 contains no built in tooling to directly deploy web apps to an IIS, this post describes a way of doing it without tooling.

Prepare project for IIS deploying using command line tools

Running commands can be done from any prompt that has the K tools in the current path. The Package Manager Console from within VS2015 works fine if you have installed the K toolset already.

First off, pack the site you intend to publish by:

1. Make sure you are located in the project root, the folder containing the project.json file.

2. Execute the following ‘kpm pack –out outputDirectory –runtime choosenRuntime‘, for ex ‘kpm pack –out C:\tmp\WebApp –runtime KRE-CLR-amd64.1.0.0-beta1′.

(If you are going to host this on an IIS locally or on a server, use a CLR version of the runtime. If you plan on deploying the package to Azure, use a Core version of the runtime.)

3. Create a new Website in IIS pointing to the chosen outputDirectory/wwwroot. (In our ex above C:\tmp\WebApp\wwwroot)

Happy Hacking! :)

post image

Polymer Bower packages in Visual Studio 2015

Working with Polymer in Visual Studio 2015 (Preview)

In the new VS2015, there is built in Bower and npm support. This is great if you want to use Visual Studio to build Polymer components and apps. Importing the basic Polymer packages in to VS2015 is not completely straight forward unfortunately, as the autocomplete for the Bower packages doesn’t seem to work a 100% just yet.

Importing the Polymer packages with Bower in to VS2015

To import the packages polymer, polymer/core-elements and polymer/paper-elements you first edit the bower.json file in your VS2015 web project. The way to insert them is under the dependencies tag, see code snippet.

"dependencies": {
     "polymer": "^0.5.1",
     "core-elements": "Polymer/core-elements#^0.5.1",
     "paper-elements": "Polymer/paper-elements#^0.5.0"
}

After the bower.json file is edited, you will see the packages pop up under your Bower dependencies. Then you need to right click the Bower packages header and select Restore Packages to actually download the packages from Bower. See picture.
VS2015BowerRestore

Then check your Output Window and select Package Manager Log to see what’s being imported from Bower and make sure there are no errors!

Happy Coding! :)

PowerShell – Working with JSon

Manipulating JSon with PowerShell

A few tips about working with JSon in PowerShell. (more…)

post image

Windows 8.1 Command Binding in a DataTemplate

DataTemplate and Bindings

In Windows 8 there are a few controls that rely on a DataTemplate to show item collections.

The DataTemplate is used to define visual layout for each item that will be rendered in an ItemsControl, it data binds nicely to collections of objects. It then iterates through the collection and uses each item as context for every new Template that is created.

Binding to Commands in the DataTemplate

When binding Commands to controls we usually bind them to Commands in the ViewModel, set as datacontext.

But if you, for example, have a button defined in the DataTemplate and bind that to a Command defined in your ViewModel, set as the datacontext for the page, it won’t work.

Why doesn’t Binding to Commands work in the DataTemplate?

The reason that the Command isn’t executed is that the Command can’t be found.

Since it’s an item in the collection that’s actually the current DataContext for the item being created, the command can’t be found if it’s defined globally in your ViewModel.

The solution is to refer the Command binding to look further up the object tree to find the Command.

In WPF it was solved using FindAncestor, but that’s removed now in WinRT.

The easiest way to solve it is to actually give the view/page an x:Name. Then refer to the Command in the binding as DataContext.MyCommandName, and set ElementName to the name of the view/page. See code snippets below, how the Command is defined, the x:Name set in Page and the Command defined in the ViewModel.

Code Snippets

ViewModel snippet:

        private RelayCommand headerClickedCommand;
        public RelayCommand HeaderClickedCommand
        {
            get { return headerClickedCommand ?? (headerClickedCommand = new RelayCommand(ExecuteHeaderClickedCommand)); }
        }

        private void ExecuteHeaderClickedCommand()
        {
            NavigateSomewhere();
        }

XAML PageRoot snippet:

<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
      x:Name="MyView"
      ...
      >

XAML DataTemplate snippet:

<DataTemplate>
  <Grid Margin="0,0,0,2">
    <Button Foreground="{ThemeResource ApplicationHeaderForegroundThemeBrush}"
				    AutomationProperties.Name="Group Title"
                                    Command="{Binding DataContext.HeaderClickedCommand, ElementName=MyView}"
                                    Style="{StaticResource TextBlockButtonStyle}">
     <StackPanel Orientation="Horizontal">
       <TextBlock Text="{Binding Category}" Margin="0,-11,10,10" Style="{StaticResource SubheaderTextBlockStyle}" TextWrapping="NoWrap" />
        <TextBlock Text="{StaticResource ChevronGlyph}" FontFamily="Segoe UI Symbol" Margin="0,-11,0,10" Style="{StaticResource SubheaderTextBlockStyle}" TextWrapping="NoWrap" />
      </StackPanel>
    </Button>
  </Grid>
</DataTemplate>

Happy Coding :)

Tests not running in Visual Studio 2013 with ReSharper 8

Unit tests not executing from ReSharper’s Unit Test Sessions

Pressing Ctrl+U,L resulting in nothing but spinning bars? I had this problem trying to run my unit tests from Visual studio 2013 using ReSharper 8.

The test indicators would keep spinning but nothing happened, setting breakpoints on the first row on the code showed that the unit tests actually never even started executing. No matter how long time that passed (ok I stopped waiting after 3 minutes to be honest) the bars just kept spinning and no error shows up.

After searching the web it turns out this is a known issue, stated to be solved in several ReSharper releases. Not sure if it’s the case and the bug has just resurfaced in the new ReSharper 8 version.

The easy solution

Turns out this problem is avoidable just by starting Visual Studio 2013 as an administrator.

If you got VS2013 pinned ot the taskbar in Windows 8/8.1, this is the easiest way to make it always start in admin mode:

1. Right click the pinned Vs2013 icon and select properties.

Pinned VS2013 Properties2. Click the “Advanced” button in the properties window.

3. Check the “Run as Administrator” checkbox.

Advanced Properties

After this your Visual Studio will always be run as Administrator.

 

Happy Testing :)

The .winmd file ‘Microsoft.Advertising.WinRT.UI.winmd’ contains duplicate type names

Error when using Microsoft Advertising SDK in Windows 8 / Windows 8.1 projects

After updating my Windows 8 app to Windows 8.1 I got a compilation error saying:

"The .winmd file 'Microsoft.Advertising.WinRT.UI.winmd' contains duplicate type names.
Type 'Microsoft.Advertising.WinRT.UI.AdControl' is already registered with the in-process
 server 'CLRHost.dll'.	ListWee_W8_Tests"

For me, this occurred in the test project.

 

After scouring the web I found a few solutions but most of them seemed like hacks, and I feared I would have to revert them later on if I used them now.

The easy solution

The easiest solution for me was to just add a reference to the Microsoft Advertising SDK in the test project.

Adding Microsoft Advertising SDK

After that the compilation works and there’s no need for more hacks :)