Wednesday, December 25, 2013

Channel 9 series: What’s new in Visual Studio 2013

If you get bored, during the Christmas holidays, have a look at the Channel 9 series: What’s new in Visual Studio 2013.

Developers, are you trying to figure out what Visual Studio 2013 has to offer you? Whether you develop for the web, Windows, or Windows Phone, and whether you are using C#, XAML, HTML, or Visual Basic, this course is for you. It focuses on some of the key new features, addressed individually in sessions throughout the day, so that you can tune in to the specific tools that will help you develop more quickly and easily. Start by learning about the integrated development environment (IDE), and then attend sessions including improved IntelliSense, easier debugging, and better tools for application lifecycle management (ALM).

Channel9Series

Tuesday, December 24, 2013

OpenSSL: Creating an ADFS certificate

Just as a quick reference for myself, here are the required statements to create your own certificate using OpenSSL:

  • Create the ADFS certificate:

openssl req -x509 -nodes -days 3650 -newkey rsa:1024 -keyout adfs01.pem -out adfs01.pem-extensions v3_ca

  • Pack the certificate and the key into a pfx file so we can easily import it into the Windows Certificate store:

openssl pkcs12 -export -out adfs01.pfx -in adfs01.pem -name "adfs01"

Monday, December 23, 2013

OpenSSL: Unable to load config info from /usr/local/ssl/openssl.cnf

When trying to create a new certificate using OpenSSL, it failed with the following error message:

“unable to load config info from /usr/local/ssl/openssl.cnf”

OpenSSL

This error was an easy one to solve. Just restarting the computer fixed it. Jippie! Glimlach

Friday, December 20, 2013

Angular.js: Combining $index and orderBy filter

When creating an application with Angular.js, I was using the $index variable inside an ng-repeat to track the index of the current item. The problem was that the moment I start combining this with an orderBy filter, the $index value was no longer correct.

I worked around the issue by passing the item itself around instead of the index.  In my function I used the indexOf method of an array.

Anyone with a better solution?

Thursday, December 19, 2013

NHibernate: Unrecognised method call:Boolean Contains(Int64)

A colleague asked me for help with a complex NHibernate query. He had written a query using the NHibernate Linq support but when he tried to execute the query, NHibernate complained with the following error message:

‘'Unrecognised method call: System.Int64:Boolean Contains(Int64)”

Let’s have a look at his query first:

It seems that NHibernate cannot translate the Contains() call in a related NHibernate query. To fix this, we switched from the Linq syntax to the QueryOver syntax:

Wednesday, December 18, 2013

Angular.js: Simple orderby sample

In the Angular.js documentation you can find a sample of how to use the orderby filter.

The problem is that this sample is already quite complex and allows you to specify a custom filter based on a predicate value.

Here is a simple sample that applies the order filter based on a specific column:

Tuesday, December 17, 2013

Combining oData and a custom authentication module

If you are looking for a way to integrate oData and custom authentication, I can recommend the following article: Securing OData services using Basic Authentication.

There is one thing that you should notice:

The moment you start using a custom authentication module, it’s important that you configure IIS for Anonymous Access. Otherwise the built-in authentication modules will kick in even when your own custom authentication module is called.

We forgot to change this and it took us some time to figure out why we always got a login dialog although the authentication module authenticated us successfully.

Monday, December 16, 2013

Visual Studio 2013: RunSettings vs TestSettings?

After creating some tests, I wanted to exclude some assemblies from the code coverage. In Visual Studio 2010 this could be done through the .testsettings file. In Visual Studio 2013you’ll notice that a .testsettings file is no longer included in a unit test project. The newer test framework, introduced in Visual Studio 2013, can be configured using a .runsettings file.

If you use a .testsettings file, the MSTest test framework will be used to run your tests. This runs more slowly and does not allow you to run tests from third-party test frameworks.

The stupid thing is that, although the .runsettings file is the recommended solution, Microsoft only added a .testsettings template to Visual Studio 2013. In the MSDN documentation they mention creating a custom XML file and renaming it, but there is a better solution.

In the Visual Studio Gallery, you can find a solution item template that creates a default runsettings file under Solution Items, and saves you from having to do this manually.  See http://msdn.microsoft.com/en-us/library/vstudio/jj159530.aspx for information on how to change the default settings.

The runsettings file is used to change the code coverage analysis settings for a test run, in particular which files to be included and excluded from analysis,  and also used to set symbol search paths.

Friday, December 13, 2013

Things I learned at NDC London: ElasticSearch River Plugin

After the first 2 days of workshops, NDC London continued with lots of great speakers and sessions. I was planning to share some information during the conference itself but due to technical difficulties I had to postpone it. For the next few days I will be sharing some of the great content.

I’m already using ElasticSearch, so one of the sessions I didn’t want to miss was Full Text Searching & Ranking with ElasticSearch.

It was a great session overall. One of the things that was new to me was the concept of a ‘River’.  The ‘River’ is a metaphor for the stream of constant data. That constant data stream can come in different forms and from different sources.

Rivers in elasticsearch provides you with functionality that listens for changes in another data source and apply them to elasticsearch. Rivers are allocated to nodes within the cluster. They are provided with automatic failover in case of node failure, and allow to store state associated with them.

There are multiple River plugins out there, some of them are build by the ElasticSearch team themselves, other come from the community.

Supported by Elasticsearch

Supported by the community

Note: If you are looking for SQL support, this is possible through the JDBC driver.

More information: http://www.elasticsearch.org/blog/the-river/

Thursday, December 12, 2013

Things I learned at NDC London: OAuth integration in ASP.NET SPA template

After the first 2 days of workshops, NDC London continued with lots of great speakers and sessions. I was planning to share some information during the conference itself but due to technical difficulties I had to postpone it. For the next few days I will be sharing some of the great content.

Security was one of the hot topics at the conference. With sessions about Layered Security, OAuth, OWASP, Security of ASP.NET Web API, and so on… there was no excuse to follow at least one security related session.

One of the things that was shown to us by Dominick Baier was the new OAuth integration in the Visual Studio 2013 SPA template. The SPA template has been completely rewritten and uses OAuth with a bearer token and  OWIN for authentication purposes.

Have a look at following blog posts to learn more about it:

Enjoy!

Wednesday, December 11, 2013

Things I learned at NDC London: The Future of C#

After the first 2 days of workshops, NDC London continued with lots of great speakers and sessions. I was planning to share some information during the conference itself but due to technical difficulties I had to postpone it. For the next few days I will be sharing some of the great content.
One of the sessions that got a lot of traction, was ‘The Future of C#’ session by Mads Torgersen.
Here is a list of some of the language features the C# team is considering:
  • Primary constructors - public class Point(int x, int y) { }
  • Read-only support for auto implemented properties - public int X { get; }=x;
  • Using statement support for static types - using System.Math; Sqrt(X);
  • Support for Property Expressions - public double Distance => Sqrt(X * X + Y * Y);
  • Improved null checking - if (points?.FirstOrDefault()?.X ?? -1) { }
  • Support for Method Expressions - public Point Move(int dx, int dy) => new Point(X + dx, Y + dy);
  • Inline declarations for out parameters - public void Foo(out var x, out var y) { }
  • Support for using enumerables in combination with the params keyword - public Point Average(params IEnumerable<Point> points) { }
I probably missed some features. So if you were there, feel free to share your info. I’ll add the items to the list…

Update: After creating this post, I noticed the following blog post that contains the same info+ some extra details: http://damieng.com/blog/2013/12/09/probable-c-6-0-features-illustrated

Tuesday, December 10, 2013

Things I learned at NDC London: Reactive Extensions Training Camp

After the first 2 days of workshops, NDC London continued with lots of great speakers and sessions. I was planning to share some information during the conference itself but due to technical difficulties I had to postpone it. For the next few days I will be sharing some of the great content.

Rx (Reactive Extensions)I’m a big fan of reactive extensions although I still have a hard time to grab my head around it. During one of the Rx sessions I heard that Netflix contributed a great series of interactive exercises for learning Microsoft's Reactive Extensions (Rx) Library for JavaScript as well as some fundamentals for functional programming techniques:

This is a series of interactive exercises for learning Microsoft's Reactive Extensions (Rx) Library for Javascript. So why is the title "Functional Programming in Javascript"? Well it turns out that the key to learning Rx is training yourself to use functional programming to manipulate collections. Functional programming provides developers with the tools to abstract common collection operations into reusable, composable building blocks. You'll be surprised to learn that most of the operations you perform on collections can be accomplished with five simple functions:

  1. map
  2. filter
  3. mergeAll
  4. reduce
  5. zip

Try this tutorial on-line.

Monday, December 9, 2013

Things I learned at NDC London: Azure Friday

After the first 2 days of workshops, NDC London continued with lots of great speakers and sessions. I was planning to share some information during the conference itself but due to technical difficulties I had to postpone it. For the next few days I will be sharing some of the great content.

Today we start with Windows Azure Friday.

Every Friday Scott Hanselman tries out some stuff on Windows Azure and shares his experiences. This video series was new to me but I started watching it yesterday and I’m already hooked. You can bookmark the link or add a reminder to your calendar.

image

Tuesday, December 3, 2013

NDC London–Day 2

Yes, we survived day 2 of NDC London. With our heads filled with AngularJs, SignalR and Web API knowledge we spent the evening shopping in the Westfield mall after enjoying a delicious meal at one of Jamie Oliver’s Italian restaurant.  I’m still digesting the great food and all the new things we learned. 

You can find my sample code here: https://github.com/wullemsb/NDC-London---Angular-Day-2

And here are my notes of day 2 of the workshop.

Overriding Services

  • You can overwrite any service bij creating a new factory registration
  • Last registration wins…

Decorating Services

  • Add pre- and post processing logic
  • Use $provide.decorator()

Service Providers

  • Different way to create services(there are multiple, remember)
  • Use $provide
  • Configure the service during the configuration phase(2 phases as you should know; configuration and run phase)

Service Constants

  • Inject primitives as a service

Service Values

  • Similar to Constants, can also inject a value
  • The only difference is that constants are available in the config phase, values are only available during the run phase

Service factories

  • Another way to create a service and service provider

Service operator

  • Another(yes indeed) way to create a service and provider
  • Difference is that with a service you need to attach the service to the this object
  • Scott says "don't use it"

HTTP Interceptors

  • Request and response interceptors

HTTP Transforms

  • Transform the request and response itself

Resources

  • Gives you a very simple GET,PUT, POST, DELETE interface to your Web API

Extending HTML

  • Give you custom HTML elements through the use of directives
  • Most directives work in multiple ways
    • As an element <accordion>
    • As an attribute <div accordion>
    • As a class <div class=accordion> --> Avoid this one, it's confusing to find out if its a CSS class or directive

Event Directives

  • Multiple events are available out-of-the-box

Custom Directives

  • Build your own directives through a Directive Definition Object
  • Can become quit complex
  • With the restrict option you can specify how the directive can be used(as an element,…)

clip_image001

  • Note that you should call it as otc-greeting

clip_image002

  • Transclude option
    • Take the content from your custom directive and merge it with the template
  • Scope option
    • Allows you to create an isolated scope(by default the scope of the parent controller is used)
      • Useful for re-usable widgets
    • You can also create a new inherited scope
  • Compile function
    • Is called once for every directive
    • Can be used to manipulate the template
    • Most of the time you don't need this
  • Link function
    • Is called

Angular.element

  • Uses jQuery Lite; "the 20% jQuery you used all the time"

Testing

  • One of the core concepts of Angular is that it should be testable
  • Helps avoid global state and singletons through dependency injection
  • Helps separation of concerns by splitting out responsabilities over controllers, templates, services, etc…
  • Framework options
    • Qunit
    • Jasmine
    • Mocha
  • Test runner options
    • Karma
    • Grunt
    • Chutzpah

Mocking

  • Through angular-mock.js(part of the NuGet package)
  • Use $httpBackend to test HTTP interaction

Routing

  • Very important part of Angular
  • Use ngView
  • RouteProvider used during configuration phase
  • Is available as a separate NuGet package
  • Include the module

clip_image003

  • Multiple Routing Events are available
  • You can also use HTML 5 routing if you don't like the # sign in your URL's

ngAnimate

  • Separate module(angular-animate.js)
  • Supports CSS transitions and animations
  • Contains a list of built in animations

UI Bootstrap

clip_image004

Annoyances(again) :-(

  • Kind of confusing combination of service constants and service values
  • Custom directives can be quit complex
    • Especially if you start to play with the scope

NDC London–Day 1

Day 1 at NDC London is over. Learned a lot about Angular.js and looking forward for the next day.

You can find my sample code here: https://github.com/wullemsb/NDC-London---Angular-Day-1

If you are interested, I added all my notes during the workshop. You’ll see that we learned a lot Glimlach

Introduction

  • More like MVVM & Silverlight building experience
  • Very extensible framework
  • Forward looking
    • Takes into account future evolutions in JavaScript & HTML

Getting started

  • Use Nuget

clip_image001

  • Multiple modules available
  • Angular.core is the only one required
  • Angular does not have any dependencies(!)
  • 'ng-app' : bootstrap element

Other starting points

  • Yeoman: does scaffolding(more designed for MAC, Linux)

clip_image002

  • Angular-Seed: gives you an example of how to structure your app

https://github.com/angular/angular-seed

Ng-directives

  • Default directive syntax is not HTML compliant
    • Will not pass through an Html validator
    • Alternative syntaxes available

Templates and Views

  • Representation of the model
  • Uses a combination of {{ }} and directives

Change detection

  • Not done through observables but through snapshot change detection
    • Is a little more expensive than what Knockout etc… does
  • In EcmaScript 6 this will be fixed, it will have an object.observe function

ng-cloak directive

  • It's annoying to see the raw html before the template is applied
  • To fix this, you can use the ng-cloak element in combination with a css rule

clip_image003

Browser support

  • Angular officially supports IE8 and up
    • Most things should also work on IE6 and up

Expressions

  • Uses a subset of JavaScript in {{ }}

ng-show

  • Hides an element when the expression evaluates 'falsy'

clip_image004

Batarang

clip_image005

Modules

  • Default module that we are using is the 'ng'-module
  • Always a good idea to split up your application into modules
  • Use 'angular.module'
  • Specify the root module through ng-app=""

Controllers

  • My first modularized controller:

clip_image006

Services

  • Multiple ways to create services(at least 5 :-))
  • Easiest way is through the factory
  • Angular has its own IOC container
    • Makes it easy to mock dependencies
  • By default every service is a singleton by default

Bootstrap phase

  • 2 parts
    • config phase: app.configure()
    • Run phase: app.run()
  • During the config phase NO services are available, but you can use serviceProviders
  • During the run phase NO serviceProviders are available, but you can use services
  • Example:

clip_image007

clip_image008

Injector

  • The DI container that is used behind the scenes
  • Be careful when using a minifier!
    • 2 ways to fix this:
      • One way is to use a minifier that knows angular
      • Another way is to use a specific annotation syntax
        • Specify all dependencies as a string array

clip_image009

  • Or specify the $inject property --> Use this one, it's cleaner…

clip_image010

Code Organization

  • Not everyone has the same opinion
  • Most people use a different file per abstraction(e.g. Angular-Seed)
  • Possible structure(folder per abstraction):
    • Apps
      • reportApp
      • adminApp
      • patientApp
      • common
        • common.js
        • custom directives
        • controllers
        • Services
  • Alternative structure(folder per feature)
    • Apps
      • reportApp
        • search
          • SearchDirective.js
          • SearchController.js
        • saveReport

Core Angular API

  • equals: does a 'deep' equal check on 2 objects
  • copy: create a copy of the movie
  • Has an embedded jqLite library(=20% of jQuery that you use all the time)

$scope inheritance

  • Uses prototypical inheritance
  • Use objects on your scope if you want to point multiple scopes to the same object

Digest loop

  • To detect changes Angular goes through a digest loop
  • After a change a second digest loop is triggered
  • Be careful to not create an infinite loop of digest loop updates
    • Angular will throw an error after 10 $digest() iterations

$apply

  • Don't call an $apply inside an $apply

$watch

  • Allows you to listen for changes

Working with forms

  • FormController can attach to named forms
  • Angular understands HTML5 validation attributes

Filters

  • Format and modify model data
  • Filters can be piped together

clip_image011

clip_image012

ngInclude

  • Includes other templates or views

Services

  • Services can be anything in Angular
    • Doesn't have to be fancy objects
    • Anything that is not a filter, controller, directive
  • Services are singletons
  • There is a long list of built-in services

Annoyances Bedroefde emoticon

  • Most typo's will not result in exceptions, makes it sometimes hard to find out why you don't see your data
  • Strange way to resolve promises(should be fixed in AngularJs 1.2)
  • Minification in combination with injector
  • Angular only updates it's view when it thinks something has changed
    • It only knows this if something happens inside the angular context(otherwise Angular has no clue)
    • The so called '$digest loop'
      • You can trigger a digest by calling $scope.$apply();
  • Beware of browser versions <IE 8

Friday, November 29, 2013

NDC London: Here we come!

Next week I will not be blogging about my day-to-day development problems. Instead I will share my experiences from NDC London.

Together with 11 other colleagues from Ordina, we will spend 6 days in London with the hope to go home a lot smarter, with new knowledge and maybe some new friends(and certainly a list of great pubs Knipogende emoticon).

image

Thursday, November 28, 2013

Web Essentials Browser Link Integration

Last week I discovered a new feature of the Web Essentials:

When you start debugging your web application, you get an extra toolbar by hitting ctrl:

image

This toolbar gives you the following options:

  • Design: Click on any element and edit its text directly in the browser, the results of the edit are reflected in source code
  • Inspect: Click on any element to jump to the corresponding source code in Visual Studio
  • Save F12 changes: Saves the changes that you did in the IE Developer tools back to the source code
  • F12 auto-sync: Any change to CSS properties in the browser dev tools is reflected in your CSS files in Visual Studio
  • Unused CSS detector: Audit your CSS selectors and see which ones don’t match anything in the page

All these features are based on the new Browser Link feature in Visual Studio 2013.

image

Wednesday, November 27, 2013

Enterprise Library 6 development guide

A few months after the release of Enterprise Library 6, Microsoft announced the second edition of the Enterprise Library development guide. The guide explains the concepts that drove development of the blocks, the kinds of tasks they can accomplish, and how they help you implement many well-known design patterns. And, it explains — by way of code extracts and sample programs — how you can actually use the blocks in your applications.

image

Download the free PDF version.

Tuesday, November 26, 2013

ADFS error: The Federation Service could not fulfill the token-issuance request.

After configuring an ASP.NET MVC application to use WIF and ADFS, authentication failed with the following error message:

The Federation Service could not fulfill the token-issuance request because the relying party 'https://localhost/ADFSSampleApp' is missing a WS-Federation Passive endpoint address.

Relying party: https://localhost/ADFSSampleApp

The problem was that I forgot to configure an endpoint address for the relying party configuration in ADFS. To do this, execute the following steps:

  • Open the ADFS Management snap-in
  • Go to the list of Relying Parties
  • Click on the application you want to configure.
  • Go to the properties and open the Endpoints tab
  • Add the URL of your web app

That should fix the problem…

Monday, November 25, 2013

EmbeddedSTS

Since the release of Windows Identity Foundation, Microsoft always provided us with a development STS that was easy to setup and configure.

However with the release of Visual Studio 2013, the development STS(provided through the Identity and Access Control extension) is gone. A good alternative is the EmbeddedSTS provided by Thinktecture:

EmbeddedSts is intended to be used from an ASP.NET application that is using .NET 4.5 and the Federated Authentication Module (FAM) from WIF. It allows for a simple and easy to use STS instead of a production STS that might require installation and configuration. It does this by embedding itself a proper WS-Federation security token service within the application itself. When the ASP.NET application would normally redirect to the production STS, it will instead redirect to the EmbeddedSts. The EmbeddedSts will provide a list of users that can login and will then issue a SAML token back to the application that contains the selcted user's claims. This list of users and their associated claims is configurable in a JSON file (which can also be checked into your project, which is useful for testing).

Thursday, November 21, 2013

WIF: ID3206: A SignInResponse message may only redirect within the current web application: '/app' is not allowed.

After creating a web application, I configured it to authenticate with ADFS through WIF. However when I browsed to the application, after authenticating, it failed with the following message:

ID3206: A SignInResponse message may only redirect within the current web application: '/app' is not allowed. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: Microsoft.IdentityModel.Protocols.FederationException: ID3206: A SignInResponse message may only redirect within the current web application: '/app' is not allowed.

The strange thing is that it works when I add a trailing slash to the application url, e.g. https://localhost/app/ instead of https://localhost/app 

Anyone with a suggestion how to fix it?

Wednesday, November 20, 2013

Make your SQL Server Express 2012 available from the outside

By default when you install a SQL Server Express, it is configured to be only accessible from the local machine.

Here are the steps required to make your SQL Server Express database available from the outside:

  • Run SQL Server Configuration Manager.
  • Go to SQL Server Network Configuration > Protocols for SQLEXPRESS.
  • Enable TCP/IP.
  • In the SQL Server Configuration Manager also verify that SQL Server Browser is running.

Now before you continue you have to know if you want to use a dynamic port range for SQLExpress or not. If you want to use a dynamic port range, you can immediately jump to the firewall configuration, otherwise you’ll have to do some extra configuration first:

  • Right-click on TCP/IP and select Properties.
  • Scroll down to IPAll.
  • Make the TCP Dynamic Ports empty
  • Set the TCP Port value to 1433.

Last step is to configure the firewall and add an exception that allows SQL Server traffic:

  • If you are using the dynamic ports, choose Add a program on the Exceptions tab of the Windows Firewall item.
  • Browse to the location of the instance of SQL Server that you want to allow through the firewall, for example C:\Program Files\Microsoft SQL Server\MSSQL11.<instance_name>\MSSQL\Binn, select sqlservr.exe, and then click Open.
  • If you are using a specific port, add a new inbound rule for TCP traffic on port 1433.

More information here: http://technet.microsoft.com/en-us/library/cc646023.aspx

Tuesday, November 19, 2013

Help, how can I log off in Windows Server 2012?

Years of experience in software development, computers and Windows systems and still sometimes I struggle finding the correct command. This time I was looking for a way to log off from a Windows Server 2012 system. The ‘Modern’ UI paradigm gave me a hard time…

So where is this Log off button?

  • Open the Windows Charms by hovering at the bottom right corner of your screen.

WindowsServer2012-1

  • On the Charms, choose the Start option to open the Metro Style start screen.Click on your User account Icon at the Top Right Corner of your Screen and there it is: the Sign out option!

WindowsServer2012-2

Monday, November 18, 2013

Combining ASP.NET Bundling and Minification and LESS

The ASP.NET bundling and minification framework supports frameworks like LESS but it took me some time to figure out how to use it. What’s important to understand is that although the framework supports other languages like LESS, you have to do some extra work to get this working.

One option is to add your own IBundleTransform  implementation, based on the .less NuGet package:

  • Add some LESS files to your web application(to improve the experience, install the Web Essentials).
  • Add the .less NuGet package dotless to your project.
  • Create a BundleTransform:
  • Create a bundle of LESS files with the LessTransform and the CssMinify transform. Add the following code to the RegisterBundles method in the App_Start\BundleConfig.cs file:

Another option is to use the System.Web.Optimization.Less library available through NuGet.

Friday, November 15, 2013

Azure: Create an Azure package file without using a Cloud Service project

A customer asked me if there was a way to keep their existing solutions intact and still be able to create an Azure package. Normally you have to add a Cloud Service project to your solution. This Cloud Service project contains all the information and required configuration to correctly build your Azure package.

But if you don’t want to do this, there is way around it by using the cspack command line tool for this(available as part of the Windows Azure SDK: http://msdn.microsoft.com/en-us/library/windowsazure/gg432988.aspx )

This tool allows you to create a deployment package from scratch.

Here are the required steps:

  • Create a servicedefinition file(.csdef). Probably the easiest way is to copy it from an existing cloud service project and adapt it to your needs
  • Build the (web) applications that you want to deploy
  • Execute the cspack command line tool using the following parameters:

cspack “c:\<path to the csdeffile>\servicedefinition.csdef” /role:<Name of the role as defined in the csdef file>;<location of the binaries> /sites:<Name of the role>;<name of the site path>;<location of the website files>

If you have multiple roles and sites, you have to add multiple /role & /sites arguments.

An example if you have the following servicedefinition file:

cspack “c:\testazurecloud\sampledefinition.csdef” /role:WebApplicationRole;c:\testazurecloud\MyWebApplication\bin /sites:WebApplicationRole;Web;c:\testazurecloud

Thursday, November 14, 2013

Coded UI Tests: Automatically take screenshots while running your tests

One of the nice things that you can do while running your Coded UI tests, is capturing screenshots of the executed actions.

Doing this is easy, to capture a screenshot of the whole screen, execute the following code:

If you only want to take a screenshot of a specific UI element, call the CaptureImage method on the element:

Wednesday, November 13, 2013

Validate your OData feed: The OData validator

You’ve created your own OData feed and want to check if it is following the OData Specifications? Check out the OData Service Validation Tool, an OData protocol validation tool. It contains a set of rules to validate against a given OData payload.

How does it work?

image

  • Choose the response type that you want to validate(AtomPub/XML, JSON-Verbose, JSON-Min,… )
  • Specify the OData version of your endpoint
  • Click on Validate to send a request to the OData service. The tool will send a request to the service and run the right set of rules against the returned payload.
  • For each rule a result is shown together with a link to the relevant spec section.

image

Tuesday, November 12, 2013

Visual Studio 2013: Where is the Identity and Access tool?

In Visual Studio 2012, you had the Identity and Access tool which gave you an easy way to configure your WIF configuration and integrate with an existing STS.

After installing Visual Studio 2013, I started looking on the Visual Studio Gallery for a new version of the tool. But no luck, only a VS 2012 version was available Bedroefde emoticon. And it seems that a version for Visual Studio 2013 will never appear.

Vittorio  Bertocci shared the following information:

In VS2013 Microsoft added support for claims-based identity directly into the ASP.NET project creation experience (see http://blogs.technet.com/b/ad/archive/2013/06/26/improved-windows-azure-active-directory-integration-with-asp-net-amp-visual-studio.aspx ), hence there are no plans of porting the Identity and Access tool to VS2013. We are aware of the fact that as of today the feature set of the two approaches are not 100% equivalent. VS2012 and VS2013 work well side by side, if you depend on functionality only available on the Identity & Access tool we recommend you keep both available until functional parity is reached (see below).

Here there are some comments on the main differences:

Friday, November 8, 2013

TypeScript: Create a type definition file for a jQuery widget

As I mentioned in a previous blog post, one of the great features of TypeScript is the support for definition files. For most popular JavaScript libraries a definition file exists, but last week I wanted to use a jQuery widget that didn’t had a type definition file(yet).

So I decided to create one myself. The important part is to understand how to link your widget to the existing jQuery type definitions.

If you want to extend the $ sign directly, you have to create an interface JQueryStatic and put your functions in it.

If you want to extend the $(‘’) selector method, you have to create an interface JQuery and put your functions there.

Thursday, November 7, 2013

TypeScript: How to create a static class

One thing that took me some time to figure out is how to create a construct like static classes in TypeScript. I wanted to directly expose some functions without instantiating a class.

Here is how I did it:

It’s not completely the same as a static class in C# but it provides a similar experience.

Wednesday, November 6, 2013

TypeScript: Internal vs External Modules

I only recently started looking at TypeScript, so there are still some concepts that are new to me. One the things I struggle with is the difference between internal and external modules.

As far as I understand it, you can define Namespaces in TypeScript by using internal modules:

By using the ‘module’ keyword I can create a Module. Everything that I put inside this module will only available inside the module itself. If I want to make something available outside the module I should apply the ‘export’ keyword.

So far so good. Now things start to get complex(at least for me) when you bring external modules into the mix. These are modules that use the AMD conventions and make it possible to export an entire module and then import it into another module. This defines a dependency chain that AMD and require.js can manage for you.

Something that took me some time to figure out is that you cannot mix internal and external modules. I wanted to use external modules but split one module out over multiple *.ts files. I had to take a look at the language specification to understand that this is ‘as designed’:

External modules (section 9.4) are separately loaded bodies of code referenced using external module names. An external module is written as a separate source file that contains at least one import or export declaration.

Further down it says that internal modules are open ended and can extend over multiple files:

Internal modules are “open-ended” and internal module declarations with the same qualified name relative to a common root (as defined in section 2.2) contribute to a single module.

If you want to read more about the difference, have a look at following StackOverflow post: http://stackoverflow.com/questions/12882748/how-do-you-put-multiple-external-modules-into-the-same-namespace-in-typescript

Tuesday, November 5, 2013

Visual Studio 2013: Search for TypeScript Typings

One of the nice features that TypeScript offers is the support for declaration files. With these declaration files you get better Intellisense and error detection for many popular JavaScript libraries. On GitHub you can find a long list of libraries that have a declaration file available.

To simplify finding these definition files for a specific JavaScript library, the TypeScript team added a nice feature to the Visual Studio IDE: “Search for TypeScript Typings…”.

image

By right clicking on any JavaScript file inside your project and choosing this option, it will start a search on NuGet for TypeScript-related packages matching the name of the JavaScript file. If you install a typing package, it will automatically be referenced by all of the TypeScript files in your project. You no longer need to explicitly add reference tags in your TypeScript code to each of the declaration files.

image

Monday, November 4, 2013

UI testing using Selenium: The IEDriverServer.exe file does not exist in the current directory or in a directory on the PATH environment variable

In my continuing conquest to find the best tool for UI testing, I also had a look at Selenium, one of the oldest and most well known browser automation frameworks.

I started simple by creating a new Test project, adding references to Selenium through NuGet, and writing a small test(based on a sample on their website):

Unfortunately when I ran the test, it failed with the following error message:

  Initialization method OLASeleniumTestProject.UnitTest1.Setup threw exception. OpenQA.Selenium.DriverServiceNotFoundException: OpenQA.Selenium.DriverServiceNotFoundException: The IEDriverServer.exe file does not exist in the current directory or in a directory on the PATH environment variable. The driver can be downloaded at http://code.google.com/p/selenium/downloads/list..

Result StackTrace:         

at OpenQA.Selenium.DriverService.FindDriverServiceExecutable(String executableName, Uri downloadUrl)

   at OpenQA.Selenium.IE.InternetExplorerDriverService.CreateDefaultService()

   at OpenQA.Selenium.IE.InternetExplorerDriver..ctor()

   at SeleniumTestProject.UnitTest1.Setup() in c:\Projects\Test\SeleniumTestProject\SeleniumTestProject\UnitTest1.cs:line 18

It seems like that just installing the NuGet packages isn’t enough. Behind the scenes Selenium is using a driver executable depending on the browser you want to test on.

To solve the issue, I had to execute 2 steps:

  • Step 1: Download and unpack the correct driver on your system. I am using a 32bit Internet Explorer so I downloaded the related driver. I  unpacked it in the same folders as my tests.
  • Step 2: I changed my code to tell Selenium where it can find the correct driver:

That’s it!

Thursday, October 31, 2013

Kendo UI Window Widget: Window only opens once

On a project I’m using the Telerik Kendo UI widgets and I’m enjoying the experience so far. They are a lot better than the default jQuery UI controls(and better documented).

However with the Window widget I had a small issue I wanted to share(together with a solution).

The first time I used the Window widget I used the following JavaScript:

This code will open a Window when the user clicks on a specific link on my webpage. This code works as expected BUT only the first time that I load my page. If I close the window and click on the link again nothing happens…

After some trial and error I found a solution, it seems like you have to create the Window widget only once and then re-use it each time you want to open a new Window. Here is my updated code:

You can see that we only create a Window object once and then re-access it through the data property of the div.

Wednesday, October 30, 2013

Free ebook: 45 database performance tips for developers

imageRedgate provides us with a free copy of 45 Database Performance Tips for Developers. It contains SQL Server performance tips and tricks recommended by some of the smartest minds in the Simple Talk community, including SQL Server MVPs.

Download your copy here.

Remark: Registration is required.

Tuesday, October 29, 2013

TFS Build Server Error: The build service host XXX is currently owned by XXX. A service host may only be active on one machine at a time.

A customer reported me the following problem with their TFS Build Server:

We had several occurrences of an error on the build development server that prevents the build controller from starting.

In the TFS Event log on the server, this error message appears:

Exception Message: The build service host XXX is currently owned by XXX. A service host may only be active on one machine at a time. (type BuildServiceHostOwnershipException)

A service restart will not correct this error.

One workaround we found is to reinitialize the build server status in the Team Foundation Server collection database.

Execute the following steps to do this:

  • Determine what is the ServiceHostId of your build server (to get a key for the update):
  • Update the record to reinitialize status:

Remark: Be careful! This is a workaround, NOT an officially supported solution.

Monday, October 28, 2013

WatiN error: Could not load file or assembly 'Interop.SHDocVw’

For a customer I’m comparing multiple UI testing frameworks. One of these frameworks I’m looking at is WatiN.

I started simple, I created a new test project in Visual Studio, installed the required assemblies through NuGet and copied the sample code from the website.

But when I tried to run this test, it failed with the following error message:

Test Name:        TestMethod1

Test FullName: WatinTestProject.UnitTest1.TestMethod1

Test Source:      c:\Projects\Test\WatinTestProject\WatinTestProject\UnitTest1.cs : line 12

Test Outcome: Failed

Test Duration:   0:00:00,0910315

Result Message:             

Test method WatinTestProject.UnitTest1.TestMethod1 threw exception:

System.IO.FileNotFoundException: Could not load file or assembly 'Interop.SHDocVw, Version=1.1.0.0, Culture=neutral, PublicKeyToken=db7cfd3acb5ad44e' or one of its dependencies. The system cannot find the file specified.WRN: Assembly binding logging is turned OFF.

The error indicated that the Interop.SHDocVw file could not be found, but when I took a look at the references, the file was correctly referenced. To solve the problem you have to go to the properties of this reference and change the Embed Interop Types property to False. This will copy the assembly to your bin folder and solve the issue.

Friday, October 25, 2013

Secure your cookies!

As we are building more and more web applications in the Cloud, security becomes a key aspect of every application. Before we felt a little bit more safe behind the company firewall but these days are gone…

And as your security is as strong as your weakest link, it is important to understand every aspect of it. One possible risk is the (wrong) usage of cookies. Most of the time when you create a cookie inside your ASP.NET application, you  don’t want to read it on the client. With a tool like https://www.cookiecadger.com/, it becomes very easy to steal someone's authentication cookie. How can we prevent this? In ASP.NET, you have to set the HttpOnly flag to true when creating a cookie:

Unfortunately the default for HttpOnly=false, so if you forget to set it somewhere you’re in trouble. Probably better is to set HTTP only as the default for all cookies to via the web.config:

<httpCookies httpOnlyCookies="true" />

More info: http://www.troyhunt.com/2013/03/c-is-for-cookie-h-is-for-hacker.html

Thursday, October 24, 2013

Saxon: Write XQuery in .NET

They are not many solutions out there in .NET that allow you to combine the power of XQuery with a C# API. The built-in XSLT support in .NET is very limited and only supports the XSLT 1.0 specifications.

One of the best options you have is Saxon, a powerful XSLT and XQuery processor. The only disadvantage of this tool is that the syntax is very JAVA oriented, which makes it sometimes counterintuitive for .NET developers.

A sample:

Wednesday, October 23, 2013

Simplify XPath development by using XQuery

Most people have heard about XPath, it gives you a powerful syntax to navigate through elements and attributes in an XML document.  Most of the time XPath is used to transform one XML document to another(through XSLT). I always found the XPath syntax hard to read, especially if your expression start to get more complex.

That’s one of the reasons why I always tried to avoid using XPath and preferred writing a small C# program and use Linq to XML.

What I didn’t know is that XML had it’s own query language, XQuery, which offers you a similar more readable experience when walking through XML files. XQuery itself uses XPath underneath but it hides the complex expressions behind a nice and clean functional-style syntax.

From w3schools:

image

And here is a sample of the syntax:

Tuesday, October 22, 2013

Sharpen your TDD skills: Coding Katas

Looking for some good exercises to train your Test Driven Development skills(or train your programming language skills)? On https://github.com/garora/TDD-Katas you find a list with some of the most well known Coding Katas, like the Bowling Game kata, the FizzBuzz kata, and so on…

codingkata

For each of these Katas a solution is available in C# together with all the test. Certainly worth checking out!

Monday, October 21, 2013

Caliburn.Micro: Async/Await

Caliburn.Micro always had the concept of Coroutines which allowed you to write asynchronous code in a synchronous way.

Starting from .NET 4.5 with the introduction of the async and await keywords, Microsoft introduced the concept of Coroutines in the language itself.

So if you want to use the same code in Caliburn.Micro with the async syntax, it becomes:

More information here: http://caraulean.com/blog/2013/07/15/using-caliburn-micro-with-async-await/

Friday, October 18, 2013

Dependency Injection with Microsoft Unity Guide

imageThanks to frameworks like Unity, StructureMap,… concepts like Inversion of Control and Dependency Injection have become mainstream in the .NET world. They allow the removal of hard-coded dependencies and make it possible to assemble a service by changing dependencies easily, whether at run-time or compile-time. They promote code reuse and loosely-coupled design which leads to more easily maintainable and flexible code.

The Microsoft Patterns and Practices team released a new guide about Microsoft Unity. It covers various styles of dependency injection and also additional capabilities of Unity container, such as object lifetime management, interception, and registration by convention. It also discusses the advanced topics of enhancing Unity with your custom extensions.

The guide contains plenty of trade-off discussions and tips and tricks for managing your application cross-cutting concerns and making the most out of both dependency injection and Unity. These are accompanied by a real world example that will help you master the techniques.

The guide is available here.

Thursday, October 17, 2013

Android Emulator performance tips

The most annoying part of the whole Android development experience is the Android emulator. Even on up-to-date hardware it remains a slow beast.

android slow

Here are some general tips and recommendations to improve the experience:

  • Tip 1: Avoid the emulator at all. Test on a real device when possible.
  • Tip 2: Keep the emulator resolution as low as possible.
  • Tip 3: Install the Intel HAXM and use an x86 emulator image instead of an ARM one.
  • Tip 4: Use VirtualBox as an Android emulator.
  • Tip 5: Create a snapshot and load the emulator from this snapshot afterwards.
  • Tip 6: Use the BlueStacks player.

Wednesday, October 16, 2013

Xamarin: Saving and loading preferences in Android

Loading and saving preferences on Xamarin.Android should be done through the ISharedPreferences interface.

Here’s a quick sample to save preferences:

And another one to load them again:

Tuesday, October 15, 2013

SQL Server: Get a list of most expensive queries

I’m not a DBA but still I want to know what’s happening inside our SQL Server. You never know what you can achieve with a little bit of optimization.

On Brent Ozar’s blog I found the following query that returns the top 20 most resource-expensive  queries:

If you execute this query, you not only get the Average CPU, Duration, … but also the query plan.

image

By clicking on the query plan XML, you can even get a graphical representation:

image

Nice!

Monday, October 14, 2013

An incompatible DacFx version is installed

When trying to connect to a SQL Server Database using Visual Studio 2012, I was welcomed by the following error message:

clip_image002

I recently installed the SQL Server Data Tools – BI package which is not the same as the SQL Server Data Tools itself(always fun to use confusing names). This seemed to have messed up my Visual Studio Installation. Luckily you can fix it by installing the latest version of the SQL Server Data Tools – October 2013 Update.

Friday, October 11, 2013

Team Foundation Server: Error when creating a new Team Project

A customer forwarded me the following error message they got when trying to create a new Team Project in TFS 2012:

Error
TF30169: The New Team Project Wizard was unable to download the process template MSF for Agile Software Development v5.0.

Explanation
The New Team Project Wizard encountered an unexpected error while attempting to download the process template. The download returned the following error: The process cannot access the file 'C:\Users\username\AppData\Local\Temp\TPW_tmp931A.tmp\Build\Templates\' because it is being used by another process.

User Action
Contact your Team Foundation Server administrator.

I was able to solve it by clearing the Visual Studio Team Explorer cache.

Execute the following steps:

  • Close Visual Studio if it’s open
  • Delete the Team Foundation cache on the client (be careful, delete the content of the folder only, not the cache folder itself)
    C:\Users\<yourusername>\Local Settings\Application Data\Microsoft\Team Foundation\3.0\Cache

Thursday, October 10, 2013

Using sequential guids as identifiers in Entity Framework

The default strategy for ID fields in Entity Framework is the usage of IDENTITY columns. This means that an identity value is generated for you by the database. Disadvantage of this approach is that an extra roundtrip to the database is required to get an ID assigned to an Entity.

An alternative approach is the use of GUID’s. They make it easy to generate an unique identity value on the client without the need to connect to the database. However the usage of GUID’s doesn’t come without it’s own set of disadvantages. First of all extra space is required to store the information and second of all it leads to fragmented indexes(due to the randomness of the generated values).

To combine the best of both worlds, you can use Sequential Guids. Using sequential guids in NHibernate is easy thanks to the build in guid.comb strategy(read more about it here). But how can we do this in Entity Framework?

I found 2 possible solutions to do this:

Use NewSequentialId()

One option you have is to still specify your ID field as an Identity column in Entity framework but update your database to use the newsequentialid() SQL function to provide a default value. Disadvantage of this approach is that you still need to go the database to get your ID value.

A good article explaining this approach can be found here: http://blog.jongallant.com/2013/04/guid-comb-ef-code-first.html

Replicate the Guid.Comb implementation from NHibernate

Another option(and the one that I prefer) is to copy the Guid.Comb implementation in NHibernate and embed it in your Entity Framework application.

Wednesday, October 9, 2013

Fun fact: TFS is using Lernout and Hauspie Speech Technology

While looking through some TFS information I noticed the following fun fact. It seems that Team Foundation Server is using the Lernout & Hauspie speech technology Glimlach:

image

Remark: This is a blog post that probably only the Belgian readers will understand. It’s a long story about what happened with Lernout & Hauspie(read the wikipedia article if you want to know more).

Friday, October 4, 2013

Help! The Microsoft BIDS are gone?!

After doing a clean install of my pc I also wanted to install the BIDS(=Business Intelligence Designer Studio) to start some Microsoft Report Services development. But I couldn’t find a version for Visual Studio 2012? So where did it go and how should I develop SSIS, SSRS and SSAS stuff using VS 2012?

I discovered that with the 2012 release of SQL Server, the BIDS plugin for Visual Studio was renamed to SSDT, SQL Server Data Tools. SSDT is available for both Visual Studio 2010 and 2012. You no longer need the SQL Server installation media to install it but instead you can just download it from the Microsoft Download Center:

image

You can use this version of the Data Tools to develop applications for both SQL 2008, SQL 2008 R2 and SQL 2012(and of course SQL Azure).

After installing it, some new templates are added to your Visual Studio:

image