Gunnar Peipman's ASP.NET blog

ASP.NET, C#, SharePoint, SQL Server and general software development topics.






February 2013 - Posts

Sessions I plan to visit at TechDays 2013 Belgium

TechDays 2013 BelgiumAs I’m going to TechDays 2013 Belgium I made my first plans about sessions I want to visit. It’s always good idea to make some home work before event because it is the only way how to make good decisions. Here is the list of sessions I plan to visit.




Four new single page application templates

ASP.NET and Web Tools 2012.2 are officially out and although it brings a lot of new stuff to us I want to stop on new Single Page Application templates available by community. I was able to get them all work and now let’s take a look at them.


Ember template uses Emberjs and Handlebars. It mimics the out-of-box Single Page Application template and therefore it is good to compare these two. Out-of-box template is more lightweight by implementation but Ember is more powerful by features, more here.

Single Page Application: Ember

Default application looks almost like the one provided out-of-box. I suggest this template to guys who are more familiar with JavaScript because in the case of problems – it seems to me – you need good skills on debugging complex code.


Durandal template uses Durandal (it’s single page applications framework), Bootstrap, Knockout and Sammy. Their sample application shows you how to show photos from Flickr.

Single Page Application: Durandal

Durandal guys make it clear on sample application front page why to go with Durandal:

  • Clean MV* Architecture
  • JS & HTML Modularity
  • Simple App Lifecycle
  • Eventing, Modals, Message Boxes, etc.
  • Navigation & Screen State Management
  • Consistent Async Programming w/ Promises
  • App Bundling and Optimization
  • Use any Backend Technology
  • Built on top of jQuery, Knockout & RequireJS
  • Integrates with other libraries such as SammyJS & Bootstrap
  • Make jQuery & Bootstrap widgets templatable and bindable (or build your own widgets).

Well, seems like good offer for me. Also their views and model seem simple and seems like there is not very much code writing overhead.


Breeze template uses Breeze, Knockout and q (a tool for making and composing asynchronous promises in JavaScript). Breeze template is also another implementation of out-of-box ToDo application.

Single Page Application: Breeze

By code Breeze is like a little bit familiar to me. Don’t know why but it reminds me upshot library a little bit. At least the way how server-side and client-side data communication is done is familiar to me.

NB! Hopefully it will be fixed soon but when creating project based on this template you may get errors. Don’t be afraid – just add references to Web API OData and tracing and your solution may run with no issues.

Hot Towel

Hot Towel template by John Papa uses Durandal, Bootstrap, Breeze, Knockout, q, Sammy and Toastr (simple javascript toast notifications). This template has a lot of scripts with it and some sample code but no samples about how data moves between client and server.

Single Page Application: Hot Towel

As John Papa states then this template is starting point to get started with building single page applications and I really hope he will add some data access samples too because his template looks very cool.


It’s good to see these new community templates for SPA-s coming and hopefully growing and getting better too. Good thing is we can build client-side applications that work on (almost) all browsers without worrying about compatibility issues and from the existing selection every interested developer can find the template he likes and start building his application with it.

Using Microsoft Solver Foundation to solve linear programming tasks

One of soon-to-starts projects uses linear programming for some optimizations. As it is not very familiar topic to me I started looking for examples and tools so I am prepared better when action starts. In this posting I will show you how to solve simple linear programming tasks using Microsoft Solver Foundation – free math package available by DevLabs.

Linear programming is used in many real-life calculations: business, economy, transportation, energy, telecommunications, manufacturing etc. The goal is holy: to make optimal decisions and save resources like money, time and materials.


What is linear programming?

Linear programming is specific case of mathematical programming or optimization. There is linear function we want to maximize or minimize, there are some constraints and non-negative variables. Practically this is how it goes:

  1. Feasible regionWe have function to be maximized:

    f(x,y) = c1x1 + c2x2.
  2. We have constraints like:
    a1x1 + b1x2 <= d1,
    a2x2 + b2x2 <= d2.
  3. Non-negative variables:
    x1 >= 0,
    x2 >= 0.

Based on this information we will find the maximum value. We can do it graphically but we can also calculate the value. On graph above the grey area is called feasible region. Somewhere on the lines that draw this area are points where maximum values are located.

Example exercises

I found some good linear programming exercises from Brunel University home page.

  1. A company makes two products (X and Y) using two machines (A and B). Each unit of X that is produced requires 50 minutes processing time on machine A and 30 minutes processing time on machine B. Each unit of Y that is produced requires 24 minutes processing time on machine A and 33 minutes processing time on machine B.

    At the start of the current week there are 30 units of X and 90 units of Y in stock. Available processing time on machine A is forecast to be 40 hours and on machine B is forecast to be 35 hours.

    The demand for X in the current week is forecast to be 75 units and for Y is forecast to be 95 units. Company policy is to maximize the combined sum of the units of X and the units of Y in stock at the end of the week.

    Formulate the problem of deciding how much of each product to make in the current week as a linear program. Solve this linear program graphically.
  2. A carpenter makes tables and chairs. Each table can be sold for a profit of £30 and each chair for a profit of £10. The carpenter can afford to spend up to 40 hours per week working and takes six hours to make a table and three hours to make a chair. Customer demand requires that he makes at least three times as many chairs as tables. Tables take up four times as much storage space as chairs and there is room for at most four tables each week.

    Formulate this problem as a linear programming problem and solve it graphically.

You can find more exercises like this when searching from web.

Using Microsoft Solver Foundation

Now let’s solve one exercise using Microsoft Solver Foundation. The API it is offering is not very familiar to developers who build usual web applications and it takes some math to understand how and why it is built this way. But still it is not something complex, it’s just a little bit different.

Exercise from Vitutor. A store has requested a manufacturer to produce pants and sports jackets.

For materials, the manufacturer has 750 m2 of cotton textile and 1,000 m2 of polyester. Every pair of pants (1 unit) needs 1 m2 of cotton and 2 m2 of polyester. Every jacket needs 1.5 m2 of cotton and 1 m2 of polyester.

The price of the pants is fixed at $50 and the jacket, $40.

What is the number of pants and jackets that the manufacturer must give to the stores so that these items obtain a maximum sale?

First we have to find out what is the function to maximize and what are the constraints. It’s like described above.

Let’s suppose x = number of pants and y = number of jackets.

  1. Function to maximize:

    f(x, y) = 50x + 40y
  2. Constraints (check out Vitutor page for good explanations):

    2x + 3y <= 1500,
    2x + y <= 1000
  3. Non-negative variables:

    x >= 0,
    y >= 0.

Now we have all information in place based on what we know and it’s time to write some code.

We create Windows console application and create reference to Microsoft.SolverFoundation.Services assembly that is located in the following place on your hard disk:

c:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\Microsoft.Solver.Foundation.dll

using Microsoft.SolverFoundation.Services;

class Program
static void Main(string
[] args)
// Create solver context and model
            SolverContext context = SolverContext
model = context.CreateModel();

// Create decision for objective function
            Decision x = new Decision(Domain.RealNonnegative, "pants"
Decision y = new Decision(Domain.RealNonnegative, "jackets"
             model.AddDecisions(x, y);

// Add constraints
               2 * x + 3 * y <= 1500,
               2 * x + y <= 1000);

// Add non-negative variables
               x >= 0,
               y >= 0);

// Add goal - what we want to maximize
            model.AddGoal("cost", GoalKind
               50 * x + 40 * y);

Solution solution = context.Solve(new SimplexDirective
report = solution.GetReport();
Console.WriteLine("result: "
+ solution.Goals.First().ToDouble());
Console.WriteLine("x: {0}, y: {1}"
, x.ToDouble(), y.ToDouble());
, report);
     } }

If we run this program we will get the following output:

Output of Microsoft Solver Foundation

The first two lines in output give us solution: manufacturer has to make 375 pants and 250 jackets to earn $28.750 that is maximally possible. All the other output is Solver Foundation report about calculation made.


Microsoft Solver Foundation is set of math tools that allows you to solve some mathematical problems you face in real-world applications. Although the API it provides is not very similar to what many of us have seen before it is still simple enough to get started with it when math side is clear. In this posting we solved simple linear programming task. When we got preparation work done we wrote some simple lines of code to get answers we were looking for. Microsoft Solver Foundation is wider platform for different calculations and before writing math manually I suggest you to take a look at what Solver Foundation has to offer.

Let’s go to TechDays 2013 Belgium!

Last autumn I found some very good presentations from Channel9 and they all were made during TechDays 2012 Netherlands and Belgium. One of those sessions was even so useful that I made some updates to my community presentations I worked on. This year I will visit TechDays 2013 Belgium to get better idea what is and see who’s there. Who knows, maybe I can find some new friends from Belgium.

TechDays 2013 Belgium

What is coming?

To concentrate all things to short list here’s what’s coming:

  • one day of active training about SharePoint, Visual Studio Application Life-Cycle, Exchange and security,
  • two days of sessions about Winodws 8, Visual Studio, Windows Server 2012, Windows Azure, System Center, Exchange 2013, Office 2013, Windows Phone and more,
  • speakers like Clemens Vasters, Bart de Smet, Jeff Prosise, Corey Hynes, John Craddock, Kurt Roggen, Dan Holme, Paula Januzskiewicz, Laurent Bugnion, Maarten Balliauw,
  • networking – good option to make contacts with fellow developers and IT-PROs.

When and where it happens?

05-07.03.2012 @ Kinepolis Antwerp. Antwerp is nice small city in northern part of Belgium. It’s easy to get there from near-by countries and guys who don’t live near can take flight to Brussels or Eindhoven and come with train (like I do). Kinepolis Antwerp is about 4km away from Antwerp central railway station and other popular areas. So if you take hotel near railway station then you can go with public transportation – it’s not a long distance.

Why Belgium is cool?

Well… Belgium and also Netherlands are cute countries with nice towns and friendly people. For me these countries are relaxing as in my country people are always in hurry and stressed and pretty much closed. There it’s different and it fits better with my nature. Also weather there is milder than in north.

Special beers

Kasteel RougeAnd here’s more – beer and food! Take a look at this dark red beauty on this image. Yes, it’s cherry beer and no, it’s not done “like usually”. This one is made using high quality cherry liquor – it’s so damn good that I even buy it with damn high price here in Estonia.

There are more special beers like this – just take some cozy pub with big selection and enjoy. These beers are often strong ones but consequences in morning are not awful like with most beers in this world.

Anyway, our days there are spent in conference and evenings are free, so …. :)

Why I go there?

I go there as the materials of TechDays Belgium for previous years have been very good. When I find some event with good sessions and speakers then I go there for sure. Also TechDays is not extremely expensive. Two days of conference and one day of training is around 600EUR per person. Add there nice small town, nice people, cute small shops and damn good beers – what else you may want?

Using database unit tests in Visual Studio

Stored procedures in SQL Server database can be unit tested using Visual Studio database unit tests. It may seem as simple thing to do at first but when you start writing tests then you will find out it’s more complex task to do then expected. In this posting I will introduce database testing with Visual Studio tools.

NB! In this posting I will use Visual Studio 2010 as I was not able to make database unit tests run on Visual Studio 2012. VS2012 has also these tests available but it seems to me that this support is still raw and waits for stabilization and fixes.

Are they actually unit tests?

I am not very sure that these tests can be called unit tests. They are different than unit tests we are used from applications development. As these tests may also test integrated components in database I would rather call these tests as database tests. Considering these tests to be wider than unit tests is okay because same mechanism allows us write very different tests for databases.

Why database testing?

Databases are often more complex beasts than just some tables, keys and indexes. Often databases contain complex queries, stored procedures and user-defined functions. SQL Server has also support for CLR libraries. All these database objects contain some logic that is usually very important.

Systems that make heavy use of stored procedures are good targets for database tests. Actually there are two ways how to test these databases:

  • regular integration tests against some service or set of classes that make data available to system,
  • database tests.

Database tests seems better option to me because then we don’t include code from other layers to tests and therefore bugs in other layers cannot affect the results of database tests.

Testing user defined function

Let’s start with simple test that can be considered as unit test. Here is the definition of our function:

CREATE FUNCTION [dbo].[GetImportantValue] 
( @n int ) RETURNS float AS BEGIN if(ABS(@n)=2) begin return
0 end return 1.0 / (4 - @n*@n) END

What can be tested here? Couple of things:

  • does the function give expected results with normal values?
  • does the function give expected results with special values?

Okay, what’s normal and what’s special value? Normal values are the one that function is expected to accept in all usual cases. Special values in current case are values that cause division by zero. We don’t want to find errors like this in public test or production environments.

Creating database test

We start with creating new test project in Visual Studio and adding database unit test to this project.

Add new database unit test

After project is created we have there one default unit test and we must remove it as we don’t need it. If we run it we get exception and there is always one failed test in our tests list.

Now let’s add database unit test. Our first test is just call to our function with value 3.

Simple database unit test body

We remove default test condition. Instead of it we will add Scalar value condition as we expect back scalar value. Clicking on condition we can set expected value.

Setting properties for scalar valued test condition

Now the first test is ready.

Running test

Build project and from top menu select Test => Run => All Tests in Solution. Npw all tests in current solution are run and results are shown in test results Windows.

Database unit test result

Our test passed and everything this far is okay.

Adding more conditions

We had more than one value to test our function. We can add more tests to our test project but we can also use same test with more than one test condition.

Let’s add tests for these values: –3, –2, 0, 2, 3. As first thing we will modify our test query. As it has to return only five numbers we can add scalar value conditions for these numbers without making test too complex to handle.

More complex database unit test

Here is one trick with test conditions. We have to change also column index of each scalar condition as our test will return one row with five columns. Running the test we get the following result.

Result of more complex database unit test

Visual Studio database tests let us actually do much more but this posting is long enough and I will come back to database tests some other time.


Database unit tests are power tool to use when building database that implements some business logic or performs sensitive calculations and we want to be sure that code in database works correctly. There are many ways how database tests can be written and here we started with simple case that gets you going. Database tests have much more to offer and I suggest you to try them out.

Bundling and minifying in ASP.NET MVC

Bundling and minifying in ASP.NET is powerful feature that helps you to optimize your web sites and save some expenses on traffic. As any other machinery in this world, bundling and minifying is not silver bullet and it has it’s own limitations. In this posting I will show you how bundling and minifying works in ASP.NET MVC.

What is bundling and minifying?

Bundling helps you to download files of same type using one request instead of multiple requests. This way you can download styles and scripts using less requests than it takes to request all files separately. Minifying helps you make files smaller by removing unnecessary whitespace.

Together these two lessen the amount of requests and bytes to get page loaded by browser.

How bundling and minifying works in ASP.NET MVC

In ASP.NET MVC 4 web application you can find BundleConfig.cs file under App_Start folder. This file contains BundleConfig class that has only one method – RegisterBundles(). In this method files that must be downloaded with one request are added to bundles.

public static void RegisterBundles(BundleCollection bundles) {
new ScriptBundle("~/bundles/jquery"

new ScriptBundle("~/bundles/jqueryui"

new ScriptBundle("~/bundles/jqueryval"

// Use the development version of Modernizr to develop with and learn from.
// Then, when you're
ready for production, use the build tool at
// to pick only the tests you need.
    bundles.Add(new ScriptBundle("~/bundles/modernizr"

new StyleBundle("~/Content/css").Include("~/Content/site.css"
new StyleBundle("~/Content/themes/base/css"
"~/Content/themes/base/jquery.ui.theme.css")); }

Here all files in each bundle are concatenated together and downloaded as one file. It means that this method defines the following URL-s to download files:

  • ~/bundles/jquery
  • ~/bundles/jqueryui
  • ~/bundles/jqueryval
  • ~/bundles/modernizr
  • ~/Content/css
  • ~/Content/themes/base/css

Take a good look at file definitions. You can see that you can specify files not only by name but also by name pattern. Special placeholder {version} in file name means that file name may contain version number. This name pattern is specially good for jQuery that is updated often. When you replace your old jQuery file that has version number in its name with newer version then you don’t have to rename the file. It is enough when file has different version number in its name.

NB! In debug-mode bundling is switched off by default. To force bundling in debug-mode add the following line in the beginning of RegisterBundles() method:

BundleTable.EnableOptimizations = true;

If you open _Layout.cs view of your application you can see how style and script bundles are included to page:


Although we have more bundles defined these are there for using with pages where they are actually needed.

ScriptBundle and StyleBundle

If you noticed then script bundle and style bundle have different classes. ScriptBundle is targeted to scripts and you shouldn’t add any other files to script bundles. Same with styles goes for StyleBundle. Both of these classes extend general Bundle class that offers bundling functionality.

Taking care of minifying is tricky. Neither of these classes have no functionality like this. All they do is they add correct minifier to their transforms collection. There are two minifying classes defined in System.Web.Optimizations namespace:

These are the classes that make the actual work. Same way can everybody write minification transforms one needs and if it is desired to keep same style as built-in bundles then one can create new bundle class that adds custom minifier to transforms collection when new bundle is created.

Switching off minifying

Yesterday I found out that CssMinify gets stuck with some style files. In the case of problems bundlers write problems out as comments to file they are transforming. Problems are reported in the beginning of file. While developers try to find out what is wrong with those style files we cannot keep minifying turned on for styles but we still want bundling to work.

There are two ways how to do it.

  • Use Bundle class. Bundle class that other bundling classes extend is not abstract class. We can create instance of it. This way we can bundle whatever files we want.
  • Clear transforms collection of StyleBundle. Clearing transforms collection is same as using Bundle class with empty transforms collection.

Tips and tricks

Here are some tips and tricks related to bundling.

  • Bundles are cached. If not specified differently in bundle class then bundle is created on first request and cached on server. All following requests for bundles are served from cache.
  • Always test bundling. Bundling may seems like what-can-go-wrong feature. You just turn it on before deploying your system to production. But don’t forget these to transform classes I introduced. These classes may face unexpected situations they are not able to handle. Before deploying your system to production make sure that bundling and minifying works like expected.
  • Be careful with styles. When bundling style sheets make sure that bundle path is same “deep” as style sheet path. If style sheet refers to images or other styles using relative URL-s and you change depth of path then all these references are broken.


Bundling and minifying is powerful feature that helps us optimize our web pages. Bundles are easy to use and they are supported out-of-box. Actually almost all ASP.NET MVC templates use bundles. Thanks to easy and flexible API we can control almost every aspect of bundling. Also we can create our own custom bundle types and define custom transforms that are applied to files in bundles. Although bundling is very good it has its own limits and tricks you must know to use them successfully. Good thing is – there are only few things that can go wrong.

Moving ASP.NET Single Page Application to TypeScript

I just moved ASP.NET Single Page Application out-of-box example to TypeScript. My idea was to try out how TypeScript works and what it means to move existing JavaScript application to it. Here is overview about what I did and what was my experience with my first steps on TypeScript.


You need the following pieces of software installed on your machine to use my code:

What is TypeScript?

TypeScript is superset of JavaScript that is targeted to building large JavaScript application. It supports type hinting, modules and variable scopes. It is not separate language – every JavaScript application is TypeScript application and vice versa.

TypeScript files are “compiled” to JavaScript when you build your application and all rules given in TypeScript files are checked. Errors are shown as usual compile errors that stop the building process. It is easy to avoid mistakes this way that otherwise maybe hard to find.

TypeScript has more familiar object-oriented syntax but it doesn’t do any magic. It is close to JavaScript and to write it one must know how JavaScript works.

ASP.NET SPA default application

ASP.NET Single Page Application JavaScript filesWhen you create new ASP.NET Single Page Application project it has some files already there that make up the sample application.

Besides Web API controllers that are used to move data between user interface and server there are some JavaScript files under Scripts folder:

  • todo.binding.js – additional Knockout bindings for sample application (clearing textbox when user clicks enter, placeholder text functionality for non-HTML5 browsers etc),
  • todo.datacontext.js – one-class-data-layer that coordinates all data operations,
  • todo.model.js – model for sample application, contains classes used by sample application (take these classes as models and not as browser-side version of domain classes),
  • todo.viewmodel.js – view model for sample application.

Some things I don’t like about these files is the fact that each of these files contains one large function that has classes defined inside it. I would like if code is written more object-oriented way and I don’t keep have to keep in mind the fact that these files are actually one big JavaScript calls.

Moving to TypeScript

I moved JavaScript files mentioned above to TypeScript. The only exception was bindings file as it was simple and straight-forward enough. For other files I made the following steps:

  • create new TypeScript files (I prefer one class per file style),
  • add module definition,
  • port code from current file to TypeScript class,
  • make sure all code that is not part of JavaScript class gets called,
  • add new file to JavaScripts bundle,
  • uncomment code in old file,
  • run application and test.

There are some things I made differently:

  • there is one class per TypeScript file,
  • I added special Application.ts file that contains application initialization code.

I like when class files are clean and doesn’t contain code that starts doing something when loaded. If all initialization code is in same file (Application.ts in my case) then it makes me easier to control how application is initialized and started.

Example class

As an example of TypeScript class let’s take TodoItem.ts from my application:

/// <reference path="DataContext.ts" /> declare var ko; declare var todoApp; module TodoApp {
export class
TodoItem {
         datacontext: TodoApp.DataContext;

public ErrorMessage: any

(data, datacontext: TodoApp.DataContext) {
.datacontext = datacontext;
             data = data || {};

// Persisted properties             this
.TodoItemId = data.TodoItemId;
.Title = ko.observable(data.Title);
.IsDone = ko.observable(data.IsDone);
.TodoListId = data.TodoListId;

// Non-persisted properties             this
.ErrorMessage = ko.observable();

var _self = this
    = function
() {

// Auto-save when these properties change             this.IsDone.subscribe(this
     } }

And this is the JavaScript that is generated from TypeScript above:

var TodoApp;
(TodoApp) {
var TodoItem = (function
() {
TodoItem(data, datacontext) {
.datacontext = datacontext;
             data = data || {};
.TodoItemId = data.TodoItemId;
.Title = ko.observable(data.Title);
.IsDone = ko.observable(data.IsDone);
.TodoListId = data.TodoListId;
.ErrorMessage = ko.observable();
var _self = this
    = function
() {
return TodoItem;
     TodoApp.TodoItem = TodoItem;
})(TodoApp || (TodoApp = {}));

One thing is miss is some good way to write object-oriented code without using typical self-closure hack to refer to class instance safely in methods.

Configuring bundling

Although your TypeScript files are not downloaded to browser when page loads you have to load JavaScript files that were generated by TypeScript. I’m doing the loading of these files in bundling configuration of my web application. It’s done in BundleConfig.cs file under App_Start folder.

bundles.Add(new ScriptBundle("~/bundles/todo").Include(

JavaScript files generated by TypeScript are in same folder with TypeScript files and they have same name as TypeScript files.


TypeScript is cool thing and I think it’s very good fit for large JavaScript applications as it helps to detect places in code where things are not used the way that was expected. As TypeScript is superset of JavaScript it is easy to convert between those two and also language rules are almost the same. It wasn’t very hard to convert SPA default application JavaScript to TypeScript and I am sure that over next years we will see JavaScript projects that make heavy use of TypeScript.

More Posts