As 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.
05.03
06.03
07.03
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
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.

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

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

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.

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.
Conclusion
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.
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.
Prerequisites
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:
We have function to be maximized:
f(x,y) = c1x1 + c2x2.
- We have constraints like:
a1x1 + b1x2 <= d1,
a2x2 + b2x2 <= d2.
- 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.
- 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.
- 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.
- Function to maximize:
f(x, y) = 50x + 40y
- Constraints (check out Vitutor page for good explanations):
2x + 3y <= 1500,
2x + y <= 1000
- 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;
using System;
using System.Linq;
namespace LinearProgrammingSFS
{
class Program
{
static void Main(string[] args)
{
// Create solver context and model
SolverContext context = SolverContext.GetContext();
Model 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
model.AddConstraints("production",
2 * x + 3 * y <= 1500,
2 * x + y <= 1000);
// Add non-negative variables
model.AddConstraints("nonnegative",
x >= 0,
y >= 0);
// Add goal - what we want to maximize
model.AddGoal("cost", GoalKind.Maximize,
50 * x + 40 * y);
Solution solution = context.Solve(new SimplexDirective());
Report report = solution.GetReport();
Console.WriteLine("result: " + solution.Goals.First().ToDouble());
Console.WriteLine("x: {0}, y: {1}", x.ToDouble(), y.ToDouble());
Console.Write("{0}", report);
Console.ReadLine();
}
}
}
If we run this program we will get the following output:

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

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
And 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?
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.

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.

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.

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.

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.

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.

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.
Conclusion
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 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)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include(
"~/Scripts/jquery-ui-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.unobtrusive*",
"~/Scripts/jquery.validate*"));
// Use the development version of Modernizr to develop with and learn from.
// Then, when you're ready for production, use the build tool at
//http://modernizr.com to pick only the tests you need.
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.css"));
bundles.Add(new StyleBundle("~/Content/themes/base/css").Include(
"~/Content/themes/base/jquery.ui.core.css",
"~/Content/themes/base/jquery.ui.resizable.css",
"~/Content/themes/base/jquery.ui.selectable.css",
"~/Content/themes/base/jquery.ui.accordion.css",
"~/Content/themes/base/jquery.ui.autocomplete.css",
"~/Content/themes/base/jquery.ui.button.css",
"~/Content/themes/base/jquery.ui.dialog.css",
"~/Content/themes/base/jquery.ui.slider.css",
"~/Content/themes/base/jquery.ui.tabs.css",
"~/Content/themes/base/jquery.ui.datepicker.css",
"~/Content/themes/base/jquery.ui.progressbar.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:
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
@Scripts.Render("~/bundles/jquery")
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.
Conclusion
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.
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.
Prerequisites
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
When 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;
TodoItemId: any;
Title: any;
IsDone: any;
TodoListId: any;
public ErrorMessage: any;
public save;
constructor(data, datacontext: TodoApp.DataContext) {
this.datacontext = datacontext;
data = data || {};
// Persisted properties
this.TodoItemId = data.TodoItemId;
this.Title = ko.observable(data.Title);
this.IsDone = ko.observable(data.IsDone);
this.TodoListId = data.TodoListId;
// Non-persisted properties
this.ErrorMessage = ko.observable();
var _self = this;
this.save = function () {
return todoApp.datacontext.saveChangedTodoItem(_self);
}
// Auto-save when these properties change
this.IsDone.subscribe(this.save);
this.Title.subscribe(this.save);
}
}
}
And this is the JavaScript that is generated from TypeScript above:
var TodoApp;
(function (TodoApp) {
var TodoItem = (function () {
function TodoItem(data, datacontext) {
this.datacontext = datacontext;
data = data || {};
this.TodoItemId = data.TodoItemId;
this.Title = ko.observable(data.Title);
this.IsDone = ko.observable(data.IsDone);
this.TodoListId = data.TodoListId;
this.ErrorMessage = ko.observable();
var _self = this;
this.save = function () {
return todoApp.datacontext.saveChangedTodoItem(_self);
};
this.IsDone.subscribe(this.save);
this.Title.subscribe(this.save);
}
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(
"~/Scripts/app/todo.bindings.js",
"~/Scripts/app/DataContext.js",
"~/Scripts/app/TodoItem.js",
"~/Scripts/app/TodoList.js",
"~/Scripts/app/TodoListViewModel.js",
"~/Scripts/app/Application.js"
));
JavaScript files generated by TypeScript are in same folder with TypeScript files and they have same name as TypeScript files.
Conclusion
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.
I have to use webcam images in one of applications I build and when playing with different components I found free and easy to use Flash and jQuery based webcam component called jQuery webcam plugin. In this posting I will show you how to use jQuery webcam plugin with ASP.NET MVC application to save captured image to server hard disc.
Preparation
Here are some steps to take before writing any ASP.NET code:
- Create new ASP.NET MVC application.
- Download jQuery webcam plugin and extract it.
- Put jquery.webcam.js, jscam.swf and jscam_canvas_only.swf files to Scripts folder of web application.
Now we are ready to go.
Create webcam page
We start with creating default page of web application. I’m using Index view of Home controller.
@{
ViewBag.Title = "Index";
}
@section scripts
{
<script src="@Url.Content("~/Scripts/jquery.webcam.js")">
</script>
<script>
$("#Camera").webcam({
width: 320,
height: 240,
mode: "save",
swffile: "@Url.Content("~/Scripts/jscam.swf")",
onTick: function () { },
onSave: function () {
},
onCapture: function () {
webcam.save("@Url.Content("~/Home/Capture")/");
},
debug: function () { },
onLoad: function () { }
});
</script>
}
<h2>Index</h2>
<input type="button" value="Shoot!" onclick="webcam.capture();" />
<div id="Camera"></div>
We initialize webcam plugin in additional scripts block offered by layout view. To send webcam capture to server we have to use webcam plugin in save mode. onCapture event is the one where we actually give command to send captured image to server. Button with value “Shoot!” is the one we click at right moment.
Saving image to server hard disk
Now let’s save captured image to server hard disk. We add new action called Capture to Home controller. This action reads image from input stream, converts it from hex dump to byte array and then saves the result to disk.
Credits for String_To_Bytes2() method that I quickly borrowed go to Kenneth Scott and his blog posting Convert Hex String to Byte Array and Vice-Versa.
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public void Capture()
{
var stream = Request.InputStream;
string dump;
using (var reader = new StreamReader(stream))
dump = reader.ReadToEnd();
var path = Server.MapPath("~/test.jpg");
System.IO.File.WriteAllBytes(path, String_To_Bytes2(dump));
}
private byte[] String_To_Bytes2(string strInput)
{
int numBytes = (strInput.Length) / 2;
byte[] bytes = new byte[numBytes];
for (int x = 0; x < numBytes; ++x)
{
bytes[x] = Convert.ToByte(strInput.Substring(x * 2, 2), 16);
}
return bytes;
}
}
Before running the code make sure you can write files to disk. Otherwise nasty access denied errors will come.
Testing application
Now let’s run the application and see what happens.

Whoops… we have to give permission to use webcam and microphone to Flash before we can use webcam. Okay, it is for our security.
After clicking Allow I was able to see picture that was forgot to protect with security message.

This tired hacker in dark room is actually me, so it seems like JQuery webcam plugin works okay :)
Conclusion
jQuery webcam plugin is simple and easy to use plugin that brings basic webcam functionalities to your web application. It was pretty easy to get it working and to get image from webcam to server hard disk. On ASP.NET side we needed simple hex dump conversion to make hex dump sent by webcam plugin to byte array before saving it as JPG-file.
NLog on is popular logging component for .NET applications. I am using it in one project where I built multi-threaded server that is running similar threads with different configuration. As those thread are independent services I needed way how to configure NLog to create different log file for each thread. Here is my solution.
When new service starts in its thread I will configure NLog in code to create log file to correct folder with correct name and layout. Image on right shows how server is keeping instances data on disk. Each instance has its own folder and for logs there is subfolder because for every date there will be new log file.
var target = new FileTarget();
target.Name = InstanceName;
target.FileName = LogsFolder + "/${shortdate}.log";
target.Layout = "${date:format=HH\\:MM\\:ss} ${logger} ${message}";
var config = new LoggingConfiguration();
config.AddTarget(this.Name, target);
var rule = new LoggingRule("*", LogLevel.Info, target);
config.LoggingRules.Add(rule);
LogManager.Configuration = config;
_logger = LogManager.GetLogger(InstanceName);
_logger.Info("Logger is initialized");
This way I got all logging done on code level and as there is arbitrarily small probability that logging ever changes I am very sure that this seemingly temporary solution will live with project for long time.
I downloaded last version of ASP.NET and Web Tools 2012.2 and digging around in Single Page Application project template. It has changed a lot compared to last beta (it was not part of stable version) and it is interesting to me to see what’s going on. I also found some good resources about SPA-s to share with your.
New default project
There is new default project for SPA-s now and it looks different than previous one. Now there is support for multiple to-do lists and of course, new design.

When we take a look at project structure we will still see almost same set of files than before but there are some changes.
Upshot is gone
Big surprise to me is the fact that I cannot find upshot anymore. It was there, it provided a little bit complex but still very powerful data layer with local caching and connection detecting etc. But now it’s gone. I actually hoped to see some progress on upshot library and support for local cache based data source.
Now it seems to be up to developers to handle data caching logic which is also not bad option as upshot code was at least for me a little bit hard to follow and debug. Now there is pure jQuery and Knockout and less JavaScript code than before.
Getting started
When searching some more information I found very good postings series by John Papa: Building Single Page Apps with Knockout, jQuery, and Web API – Part 1 – The Story Begins. Take a look at postings and examples the series provides. Although it is ten postings the postings are not too long and they are very well focused. Also I suggest reading John Papa blog post Inside the ASP.NET Single Page Apps Template Beta that explains how new SPA template works.
Conclusion
As upshot is gone and there is enough reading now about SPA-s in ASP.NET I think I come out with some new ideas when I have gone through all the materials. It’s good to see the progress and I’m happy because SPA template is back again. Hopefully it is now simpler beast to manage than it was during upshot days.
More Posts
Next page »