Toolroom Tech Blog

Devlopers Digest

Objective-C versus C# Syntax

A few major differences between C# and Objective-C

You are .net developer and think about starting iDevice development? Ok, have fun ... It's different. It's nearly impossible to show all differences between C# and Objective-C. I will just provide you with a very few important things to know. 

  • Basically, Objective-C is unmanaged, so the developer is responsible for memory management. Why basically? There is a garbage collector is available since 2010, but not for older versions of OS X and iOS and it seems the GC dramatically decreases the app performance.
  • Objective-C is a superset of C, therefore it requires a header file 'LotteryEntry.h' (aka interface file) to declare variables and methods. Those methods are then implemented in the implementation file 'LotteryEntry.m'. 
  • The syntax is in the style of Smalltalk... 
  • OC has no properties like C#, instead apple has a accessor guidlance. I.e. to provide accessors for the variable firstNumber, we need to provide a get-method called firstNumber and a set-method called setFirstNumber.
  • The Cocoa API is very simple and easy. It is really not what we can call voluminous.

In the following example I will create a simple .NET class with two properties and one overridden method. Then, to give you an idea how Objective-C Looks like, I'll show the same class translated to Objective-C.

Due to the smalltalk syntax, Objective-C looks crazy for C# or Java developers. But here a few things to know before you start reading the code.




- (NSString *)getString:(NSString *)myString
    return myString;
public string GetMyString(string myString)
    return myString;
[self getString:anyDefinedString];
NSDate *now = [[NSDate alloc] init];
var now = new DateTime();


using System;

namespace Dweedo.Web.Common
    public class LotteryEntry
        readonly Random _rand = new Random();

        public LotteryEntry(DateTime? entryDate = null)
            EntryDate = entryDate jQuery15203358672992216089_1349763670826 DateTime.Now;

            FirstNumber = _rand.Next(1, 101);
            SecondNumber = _rand.Next(1, 101);

        public int FirstNumber { get; private set; }

        public int SecondNumber { get; private set; }

        public DateTime EntryDate { get; set; }

        public override string ToString()
            return string.Format("{0} = {1} and {2}",



#import <Foundation/Foundation.h>

@interface LotteryEntry : NSObject {
    NSDate *entryDate;
    int firstNumber;
    int secondNumber;

- (id)initWithEntryDate:(NSDate *)date;
- (void)setEntryDate:(NSDate *)date;
- (NSDate *)entryDate;
- (int)firstNumber;
- (int)secondNumber;



#import "LotteryEntry.h"

@implementation LotteryEntry

- (id)init{
    return [self initWithEntryDate:[NSDate date]];

- (id)initWithEntryDate:(NSDate *)date{
    if(![super init]) return nil;
    [self setEntryDate:date];
    firstNumber = random() % 100 +1;
    secondNumber = random() % 100 +1;
    return self;

- (void)setEntryDate:(NSDate *)date{
    entryDate = date;

- (NSDate *)entryDate{
    return entryDate;

- (int)firstNumber{
    return firstNumber;

- (int)secondNumber{
    return secondNumber;

- (NSString *)description{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setTimeStyle:NSDateFormatterNoStyle];
    [dateFormatter setDateStyle:NSDateFormatterShortStyle];
    return [[NSString alloc] initWithFormat:@"%@ = %d and %d",
              [dateFormatter stringFromDate:entryDate],


Using Windows 8 with classic Start Menu

How to get the Start Menu back into Windows 8 final release.

I swear, I tried to "work" with Windows 8. In my opinion, the Startscreen is great when working with Touch enabled devices. But on desktop view, I really miss the Windows Button and/or Windows-Key function. I'm not only accustomed to it, I need it, it makes me somewhat crazy, that the Start Menu was not included in the final Version of Windows 8. And also the well known registry hacks known from the Windows 8 Betas and RCs do not work anymore.

But thanks to Stardock, primarily known for their great Windows UI customization Tools, you can get the start menu back. The Little tool is known as Start8, find the download link below. You can also try ViStart from Lee Soft. Both re-enable the classic Start-Button with all its comfort :)


Links to the Downloads


AJAX templating with JQuery and MVC

Example how to add AJAX templating automation with ASP MVC and JQuery.

AJAX Templating with MVC and JQuery

In principle, when using dynamically created web pages, i.e. by Asp or PHP, the web server creates the HTML, sends it to the client, and the client renders the whole stuff.

Now you might want to load additional content without refreshing the whole page. You can do this with simple callbacks to the server, where the server again produces some HTML and sends it back to the server. This means, that lots of HTML is sent. Such asynchronous calls should need the shortest roundtrip time as possible, since users wait for content. And, believe me, users cannot wait.

Templating is a great way to gain performance in asynchronous server interaction with AJAX. Therefore the server produces a invisible template on the initial response. Then, instead of sending HTML, the server just provides us with plain data.

In the following example I load a table with data from a log file. When the user clicks a refresh button and/or a timer triggers a refresh function, we get new data.

Step One: Create base HTML

Based on the LogItem collection we create a simple table in the index file that may contain initial static data.

@model JQueryTemplating.Models.LogItemCollection
<table id="logItemData" style="width:100%;">
                @Html.LabelFor(l => fakeLogItem.TimeStamp)
                @Html.LabelFor(l => fakeLogItem.Title)
                @Html.LabelFor(l => fakeLogItem.Type)
                @Html.LabelFor(l => fakeLogItem.Description)
        @Html.DisplayFor(l => l)

For initial rows we need a DisplayTemplate, that goes into the DisplayTemplates folder.

@model JQueryTemplating.Models.LogItem
<tr class="line@(Model.Type)">
        @Html.DisplayFor(i => i.TimeStampStr)
        @Html.DisplayFor(i => i.Title)
        @Html.DisplayFor(i => i.Type)
        @Html.DisplayFor(i => i.Description)

Step Two: Add Attribute and Extension 

Now I do some Voodoo to allow model driven templating and Razor support. Therefore I first add an annotation to markup a models property for templating inclusion.

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class TemplateAttribute : Attribute
	public string Value { get; set; }

	private string _displayFormat = "{{{0}}}";
	public string DisplayFormat
		get { return _displayFormat; }
		set { _displayFormat = value; }

Then I add an extension method to the MvcHtmlString in order to access the template values i.e. with Razor.

public static MvcHtmlString TemplateValueFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
	var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);

	var prop = metaData.ContainerType.GetProperty(metaData.PropertyName);
	if (prop == null)
		return null;

	var templateAttribute = prop.GetCustomAttributes(typeof(TemplateAttribute), false).FirstOrDefault() as TemplateAttribute;
	if (templateAttribute == null)
		return null;

	var result = string.Format(templateAttribute.DisplayFormat, templateAttribute.Value jQuery1520833310639602945_1349033015193 metaData.PropertyName);
	return new MvcHtmlString(result);

Step Three: Add HTML Template for AJAX

Now, let's add Ajax stuff. Therefore, in we create a template row within the document that contains the table. To have valid HTML, i put it into a separate table. In principle the row is equal to the DisplayTemplate.

<table id="logItemTemplate" style="display:none;">
        <tr class="line@(Html.TemplateValueFor(i => i.Template.Type))">
                @Html.TemplateValueFor(i => i.Template.TimeStampStr)
                @Html.TemplateValueFor(i => i.Template.Title)
                @Html.TemplateValueFor(i => i.Template.Type)
                @Html.TemplateValueFor(i => i.Template.Description)


Step Four: Add Action that provides data

Now we need an MVC Action to call for new data. Optionally we can provide it with a timestamp that defines the time of the latest item we have already received, so that we only get new log entries.

public class DataController : Controller
	// GET: /Data/
	public ActionResult Get(DateTime? timestamp)
		var repository = new LogItemRepository();
		var items = repository.GetData(timestamp);

		return Json(items);

Step Four: Add AJAX functionality

Finally, let's add the jquery part for asynchronous updates and a button to enable/disable those updates.

$(function () {
        //Attach to the click event of the start/stop button
        $('#start').click(function () { start(); });

        //Used for the delegate function for periodic calls
        var refreshDelegate = false;

        //AJAX function that fetches new data from the server
        var refresh = function () {
                url: '/Data/Get',
                type: 'POST',
                dataType: 'json',
                success: function (data) { handleData(data); },
                error: function () {
                    if (confirm('Connection refused. Please click ok to try it again.')) { start(); };
                cache: false

        //handles the JSON response
        function handleData(data) {
            //Iterate throught all items
            $.each(data, function () {
                //Clone the Template
                var html = $('#logItemTemplate>tbody').clone().html();
                //Iterate through the key/value pairs
                $.each(this, function (k, v) {
                    if (v != null && v.indexOf('/Date(') == 0) {
                        v = convertToDate(v);
                    //Replace the key by its corresponding value
                    var regex = new RegExp('{' + k + '}', "g");
                    html = html.replace(regex, v);

                //Finally prepend the processed row to the table

        //Helper function to convert the serialized .net datetime format
        function convertToDate(str) {
            var re = /-?\d+/;
            var m = re.exec(str);
            return new Date(parseInt(m[0]));

        //Sets or stops the periodic timer
        function start() {
            if (refreshDelegate == false) {
                refreshDelegate = setInterval(refresh, 1000);
            } else {
                refreshDelegate = false;

Download sample solution (2.35 mb)

Using Windows 8 with keyboard and mouse

A short but effective list of tips how to use Windows 8 with your Keyboard.

Curious ... I've never thought I would write something like this. But in fact I'll really provide you with some Tips how to use Windows with your Keyboard.

  1. [any key] unlocks the Locked Screen (if you cannot find this key, stop reading immediately!)
  2. [Windows]+[x] shows something like a Start-Menu replacement called 'quick link power user commands'
  3. [Windows] switches between the Startscreen and the active App
  4. [Windows]+[z] or right click show the application bar on the start Screen
  5. [Page-Up] and [Page-Down] scroll the start Screen
  6. [Windows]+[Page-Up] and [Windows]+[Page-Down] moves the start Screen to another Monitor
  7. [Windows]+[p] Shows projection options, i.e. to connect more screens
  8. [Windows]+[c] toggles the charms
  9. [Windows]+[h] opens the share charm directly
  10. [Windows]+[i] opens the settings charm directly
  11. [Windows]+[k] opens the devices charm directly
  12. [Windows]+[q] opens the search charm and the App List directly
  13. [Windows]+[f] opens the search charm and directly focuses to files 
  14. [Windows]+[CTRL]+[f] opens the Computer search within AD
  15. [Windows]+[Tab] cycles through the app history (more or less the open apps)
  16. [Windows]+[,] shows your pretty Desktop as Long your fingers do not leave the Keys
  17. [Windows]+[.] moves a Metro app to the right (cyclic)
  18. [Windows]+[Shift]+[.] moves a Metro app to the left (cyclic)
  19. [Windows]+[Break] opens the System Properties window

Utilization of Conditional Statements for Internet Explorer

A typical HTML comment is ignored by the web browser. But Internet Explorer utilizes the well known HTML comment for something that we could call a conditional notation.

A typical HTML comment is ignored by the web browser. But Internet Explorer utilizes the well known HTML comment since version 5 for something that we can call a conditional notation.

Those Conditional Comments are not contained within any HTML Standard, they're only noticed by Internet Explorer and some parts of the Microsoft Office Suite. As the name already says, they offer something like conditional statements within HTML, without disrupting the validity of a HTML document.

How does it look like

<!--This is a typicall HTML comment-->
<!--[if expression]>This is a conditional comment for IE<![endif]-->
<![if expression]>This is a conditional comment for IE and others<![endif]> 

The conditional expression is formed from a combination of feature, operator, and/or value, depending on the feature.

The first line is a typical HTML comment, not visible to anyone. Even the Browser does not interpret its content. The second line shows the structure for a conditional comment, visible only for Microsofts Internet Explorer. Its content is hidden from browsers that do not support conditional comments, this type of conditional comment is called downlevel-hidden.
Now take a look at the third line. Internet Explorer will parse the expression, even tough this is a non valid HTML node: note, that the -- is missing at the start and at the end of the comment. All other browsers should typically ignore this invalid node, but display its content. That's why it is called downloevel-revealed conditional comment.


<!--[if lte IE 7]>
    <SCRIPT LANGUAGE="javascript">
        alert("This is a fix for Internet Explorer 6 and .");
    <br style="clear:both;"/>

This condition and its content is visible for IE only. It will execute Java Script and load a HTML fix for IE Versions lower than or equal 7.

<![if lt IE 9]>
    <p>This application requires at least Internet Explorer 9.</p>

This expression is noticed as valid expression for IE. All IE versions lower than 9 will show, that at least IE9 is required to show this content. Since other browsers ignore the invalid comment declaration, they will also show this requirement.


IE [if IE] The string "IE" is a feature corresponding to the version of Internet Explorer used to view the Web page.
value [if IE 7] An integer or floating point numeral corresponding to the version of the browser.
WindowsEdition [if WindowsEdition] Windows Internet Explorer 8 on Windows 7. The string "WindowsEdition" is a feature corresponding to the edition of Windows used to view the Web page.
value [if WindowsEdition 1] An integer corresponding to the edition of Windows used to view the Web page (More about the version)
true [if true] Always evaluates to true.
false [if false] Always evaluates to false.


! [if !IE]

The NOT operator.

lt [if lt IE 5.5] The less-than operator.
lte [if lte IE 6] The less-than or equal operator.
gt [if gt IE 5] The greater-than operator.
gte [if gte IE 7] The greater-than or equal operator.
( ) [if !(IE 7)] Subexpression operators. Used in conjunction with boolean operators to create more complex expressions.
& [if (gt IE 5)&(lt IE 7)] The AND operator. Returns true if all subexpressions evaluate to true
| [if (IE 6)|(IE 7)] The OR operator. Returns true if any of the subexpressions evaluates to true.

Integrate your own AddOn

Developers of AddOns for IE may also utilize conditional comments in order to query their versions. Therefore, just add a REG_SZ value to the Version Vector Registry key. The name of the new key defines the feature value to use in a conditional comment, as shown in the following example.


         Internet Explorer
            Version Vector
               ToolroomBar = 1.1

Then use it on your web page in the following manner:

<!-- [if (gte ToolroomBar 1)&(lt ToolroomBar 2)]>
    You are using the ToolroomBar Version 1.x

Conditional Comment Summary

  1. Load CSS and Script fixes for a subset of Browser versions
  2. Show special content for a subset of IE versions and Windows Versions
  3. Allows utilization for own Browser Extensions on IE
  4. Low client-side impact
  5. No script required
  6. Cross Browser compatible (because they don't know it :))

Should I really use it?

I do not recommend it, only for certain cases ... if there's no other clean way.

Windows Server 2012 - Editions and Licensing Model

Today, Microsoft releases the next generation of its Server operating system &quot;Windows Server 2012&quot;. A short overview over the new Editions and the Licensing Model

A simpler version scheme with 4 different versions at all.

Today, Microsoft releases the next generation of its Server operating system Windows Server 2012.

Like the Windows 8 Client it builds upon the Windows NT 6.2 kernel and interacts over the same New User Interface, formerly known as Metro. And it shares the same cloud-centric focus, but not only by connecting to clloud services: Windows Server 2012 provides cloud services.

In principle, lots of features of Windows Server 2012 are incremental enhancements of its predecessor, i.e. it uses the Server Manager and the PowerShell from Server 2008R2, and extends on them. But other really new features could brake bones. A closer look on the new Hyper-V shows stuff that could disrupt the business of other companies, that focus on virtualization ...

Two Fully Featured Editions

There are just two fully featured major versions avaliable. Both, the Standard and the Datacenter edition, will support the same set of features and the same hardware limits. Both will require CALs for authenticated server access. Both will be licensed on a per-socket-pair basis. The only difference will be in virtualization rights.

  • Windows Server 2012 Standard
    Standard edition can be run in up to two virtual machines (in addition to the host operating system)

  • Windows Server 2012 Datacenter
    Datacenter edition can be run in an unlimited number of virtual machines. 

That means: Windows Server 2008 R2 Enterprise, Web, and HPC products are all replaced by Standard and Datacenter licenses. Standard licenses will be priced at $882, Datacenter licenses at $4,809.

Server 2012 Standard and Datacenter can handle up to 320 “logical processors,” or CPU cores and double the processing maximum for R2. Memory capacity is also doubled to a max of 4 terabytes. And the failover clustering capabilities of Server 2012 have been vastly expanded, supporting up to 64 cluster nodes—up from 16 in the previous release.

2 Limited Capability Editions

Essentials and Foundation are the two limited-capability versions, supporting fewer processor sockets and less RAM.

  • Windows Server 2012 Essentials

Essentials supports a large subset of Windows Server functionality for $425, but many features, including Active Directory and file server features, will be preconfigured and preinstalled. It will support up to 25 clients and will hereby replace Small Business Server Essentials and Small Business Server Standard.

  • Windows Server 2012 Foundation

Windows Server 2012 Foundation is even more restricted than Essentials, and will be restricted to cheap servers designed for the very smallest of businesses, supporting only a maximum of 15 clients.

Charts in the Web: SVG or HTML5 Canvas?

When to use what? Short differentiation between SVG and HTML5 Canvas.

Currently I am working on a dashboard, where I need to show various graphs rendered by the Browser. I didn't want to encapsule everything into a almost inaccessible blackbox, so I banned Flash & Silverlight and decided to rely on SVG or HTML5 Canvas. But what's the difference? 

The following samples will produce two identical graphics:

Scalable Vector Graphics (SVG)

Primarily, SVG is a XML based language to describe 2-dimensional vector graphics. Because of its XML based definition, each object within the SVG DOM is accessible by Java Script. It means you can attach to events and customize the layout by css.

All modern Browsers, even Internet Explorer (>=9) and mobile Browsers, can directly interpret it.

The following example produces this browser output:

		<title>SVG Demo</title>
		<svg width="100" height="200" xmlns="" version="1.1">
			<style type="text/css" >
					fill:   #DD9900;
				circle.outer {
				   stroke: #FFFFFF;
				   fill:   #FFCC00;
			   circle.inner {
				   stroke: #FFFFFF;
				   fill:   #cc0000;

			<rect class="outer" x="0" y="0" width="100" height="200" rx="5" ry="5" />
			<circle class="outer" cx="50" cy="50"  r="100"/>
			<circle class="inner" cx="50" cy="100" r="24"/>

HTML5 Canvas

The HTML5 Canvas provides JavaScript with an area to create 2-dimensional pixel-graphics. In difference to SVG, the canvas' objects and paths are not accessible by the DOM. In order to change parts of the graphic, the whole canvas needs to be redrawn.

The following lines will draw our graphic from above with Canvas:

<html lang="en">
		<meta charset=utf-8>
		<title>Sample HTML5 Structure</title>
			function drawCanvas(){
				var canvas = document.getElementsByTagName('canvas')[0];
					var context = canvas.getContext('2d');
					context.fillStyle = "#DD9900";
					context.fillRect(0, 0, canvas.width, canvas.height);
					var centerX = canvas.width / 2;
					var centerY = canvas.height / 2;
					context.arc(centerX, 50, 100, 0, 2 * Math.PI, false);
					context.fillStyle = "#FFCC00";
					context.lineWidth = 15;
					context.strokeStyle = "#FFFFFF";
					context.arc(centerX, centerY, 24, 0, 2 * Math.PI, false);
					context.fillStyle = "#CC0000";
					context.lineWidth = 15;
					context.strokeStyle = "#FFFFFF";
	<body onload="drawCanvas()">	
		<canvas id="canvasOne" name="canvasOne" width="100" height="200">
			HTML5 Canvas not supported by your Browser.

Pixels vs. Vector

Let's (browser-) zoom into both graphics. As you can see, SVG on the right remains clear and sharp, while Canvas gets blurred.


Finally, here's what you should think of when decide between Canvas and SVG. 



  • Pixel-based graphics, therefore resolution dependent
  • No DOM integration, therefore no event handler support
  • Animations are frame based, the whole canvas needs to be recalculated.
  • Allows to save graphics in various formats (Right Click > Save as ...)
  • Very fast, can be used for graphic intensive applications, i.e. games
  • Vector graphics, therefore NOT resolution dependent
  • SVG DOM supports event handler support
  • Objects are directly accessible by script and can be animated by object.
  • Great for large rendering areas like Google maps
  • Due to DOM integration resource intensive, not suitable for games


Download Sample

svg-vs-canvas.html (2,24 kb)

Database Comparison Utility

If you should ever need to compare two (running) databases, i.e. two versions of a model, i recommend to do it with the free utility called &quot;DB Comparer&quot;.

If you should ever need to compare two running databases, i.e. two versions of a model, i recommend to do it with the free utility called "DB Comparer":


DBComparer is a professional database comparison tool for analyzing the differences in Microsoft SQL Server 2008 (and 2005) database structures. It is an excellent tool for any project development team or DBA managing multiple copies of the same database on an SQL Server. This database comparison tool has a clean and straight-forward user interface. Results are clearly presented so that you can immediately see the differences in your databases. It will make locating and eliminating differences in your database fast and easy.


  • Automate compare database
  • Compare all database objects or selected ones only
  • Compare database by all or selected properties of objects only
  • A wide variety of options for comparison
  • Compare databases using all or selected object properties
  • Advanced visual build tree interface for an intuitive visual representation of any differences
  • Built-in text differences control with SQL syntax highlighting
  • Native database comparison support for Microsoft SQL Server 2008 (and 2005)



Fix by Rewrite for XAML ScrollViewer issue

How to fix strange scrolling behavior within a Windows Phone Pivot by rewriting a few lines of XAML 1:1 :)

Yesterday I had the strangest XAML behaviour ever ... I have to share this!

The issue 

In a Windows Phone app I have this object tree in my ApplicationPage, where each View contains a ScrollViewer with simple Grid content - nothing special.

<Grid x:Name="LayoutRoot">
	<controls:Pivot Title="{Binding PageTitle}">
		<controls:PivotItem Header="Page 1">
				<Views:ItemOneView DataContext="{Binding Data}"/>
		<controls:PivotItem Header="Page 2">
				<Views:ItemTwoView DataContext="{Binding Data}"/>
		<controls:PivotItem Header="Page 3">
				<Views:ItemThreeView DataContext="{Binding Data}"/>

The issue was, that the runtime didn't allow me to scroll down to hidden content of ItemTwoView. The scrollbar didn't come up and altough I saw the content while scrolling, it moved back to the original position when I stopped.

The fix

After hours of debugging, I just rewrote the 5 lines from <controls:PivotItem Header="Page 2"> to </controls:PivotItem> exactly 1:1. And it worked!

I really didn't believe it ... so I pushed undo and had the behavior again, although the code didn't change. Hidden characters? Encoding issue? Bug? Don't know.

Hex string to Color conversion on Windows Phone 7.x

Function to convert a hex string to a Color

In a Windows Phone 7 project I recently needed a function that does the work of System.Drawing.ColorTranslator.FromHtml(string color). Therefore I wrote this little extension method.

It deals with RGB and ARGB input values, with or without the leading hash.

public static Color FromHtml(this string s)
	// Check fore a valid code (RGB = 6 chars, ARGB = 8 chars)
	var regex = new Regex(@"^[A-Fa-f0-9]*$");
	if (s == null || ((s = s.Trim().TrimStart('#')).Length != 6 && s.Length != 8) || !regex.IsMatch(s))
		return Colors.White;

	int index = 0;

	// If the color length is 8, the first 2 chars contain the alpha part
	byte a = 255;
	if (s.Length == 8) 
		a = Convert.ToByte(s.Substring(0, 2), 16);
		index += 2;

	// Get R value
	byte r = Convert.ToByte(s.Substring(index, 2), 16);
	index += 2;
	// Get G value
	byte g = Convert.ToByte(s.Substring(index, 2), 16);
	index += 2;
	// Get B value
	byte b = Convert.ToByte(s.Substring(index, 2), 16);

	return Color.FromArgb(a, r, g, b);


var color1 = "#CC3333".FromHtml();

var color2 = "CC3333".FromHtml();

var color3 = "#FFCC3333".FromHtml();