ASP.NET MVC 4 Beta Info and Resources

By DimitriC at February 27, 2012 14:58
Filed Under: ASP.NET, Architecture, Documentation, Programming, tools & Utilities

On Katrien’s MSDN Blog:

 

During TechDays Belgium 2012 two weeks ago, Scott Guthrie announced the Beta release of ASP.NE MVC 4 slated for that same week. Since February 16th you can now download ASP.NET MVC4 Beta.
Interesting to note is the availability of a Go-Live license with this release. In other words, if you feel like using these bits on production you now can!

 

A few important updates and features are part of the Beta:

 

  • - Bundling and Minification, brought to ASP.NET 4.5 and now also integrated into ASP.NET MVC 4. This allows you to build faster applications by minimizing the number of requests to the server (bundling requests).
  • - Web API integration into ASP.NET: new support for creating HTTP REST services, has built-in support for content negotiation with support for JSON, XML and Form URL-encoded formats
  • - ASP.NET Mobile support through custom view engines for mobile sit.es and jQuery Mobile integration.
  • - Async and WebSockets: when using ASP.NET MVC 4 with .NET 4.5 and VS 11 you’ll also be able to take advantage of the new async and WebSocket support built-into .NET 4.5.
  • - Single Page Applications: new in the beta is support for building better end-to-end experience for building applications with client-side interactions using JavaScript (Upshot, History.js) and the MVVM pattern (knockout.js). On the server side the ASP.NET NET Web API is used, mainly an abstract class DataController. Note this is a new project template type in experimental phase.
  • For more information on creating Single Page Applications with ASP.NET MVC 4 I recommend you watch the fantastic session Steve Sanderson did during TechDays: Building rich Single Page Applications (SPAs) for desktop, mobile, and tablet with ASP.NET MVC 4. Worth watching until the end where Steve even shows an offline capable implementation using HTML5 application cache and offline storage. These latter ones however are not yet part of the beta.
 
Resources

 

Decimal 2 Binary

By DimitriC at February 21, 2012 11:23
Filed Under: Programming, tips & tricks

From time to time I get a fun question. One of them was this: Please provide a list with powers of 2 accompanied by their binary representation, for let’s say up to 50.

 

First version:

 

   1:  int temp=1;
   2:   
   3:  for(int i = 1; i<=50; i++)
   4:  {
   5:      Console.WriteLine(i+": Dec: "+temp+" - Bin: "+Convert.ToString(temp,2));
   6:      temp = temp*2;
   7:  }

 

This gives the following result:

 

image

 

Here we bump into the maximum of information that can be held by an integer. So for going up to 50, it suffices to change the type of the decimal number to long:

 

   1:  long temp=1;
   2:   
   3:  for(int i = 1; i<=50; i++)
   4:  {
   5:      Console.WriteLine(i+": Dec: "+temp+" - Bin: "+Convert.ToString(temp,2));
   6:      temp = temp*2;
   7:  }

image

So, I could answer the question. But the same problem occurs when you come to the limit of the long-data type (which is at 64).

 

Double, float or decimal are not supported by the Convert.ToString(…) implementation where you can define the toBase-parameter.

What is "binding" and what makes it late?

By DimitriC at February 14, 2012 08:39
Filed Under: Programming, Training

Another interesting post on Eric Lipper’s blog. In this post, he explains his understanding of the concept of “late binding” (with a couple of small samples).

 

Read the full article here.

Log4net for .NET 4.0 & .NET 3.5/4.0 client

By DimitriC at January 19, 2012 08:26
Filed Under: General, log4net, tools & Utilities, Programming

Release 1.2.11 of log4net has these changes (source):

 

General:

 

log4net 1.2.11 is not only a bug fix release, it also adds support for Microsoft® .NET 4.0 as well as the client profiles of .NET 3.5 and .NET 4.0. … The binary distributions no longer contain assemblies built for the Compact Framework 1.0 or the Shared Source CLI - you can build those yourself using the source distribution.

NOTE: The signature of ILoggerFactory.CreateLogger has changed!

 

Some of the bug fixes:

- Visual Studio 2010 .NET 4.0 Application does not copy log4net lib to bin directory

- RemoteFileAppender Tests fail on Windows 7

- log4net doesn't log when running a .Net 4.0 Windows application built in Release mode

- EventLogAppender's ActivateOptions throws SecurityException on Vista/Win2k3 and later when not run as administrator

 

Some of the improvements:

 

- support .NET 2.0 connectionStrings configuration section

- IPAddressConverter improvement for .NET 2 or .NET 3

- Add Cc and Bcc support to SmtpAppender

 

Some new features:

 

- add the ability to roll files based on universal time (UTC).

- Support ASP.Net related PatternConverters to allow items from the HttpContext.Current.Session, Cache, Request, etc. to be captured.

- Build for Compact Framework 2.0

- Added ExceptionEvaluator

- Add TimeEvaluator

- New property ReplyTo address for the SmtpAppender required

- Buildable with VS 2008 and .NET FW 3.5

  • - Support .NET 4.0 including Client Profile

 

 

Previous articles:

 

- Logging: Log4Net Part I

- Logging: Log4Net Part II

- Logging: Log4Net Part III

- Logging: What/When to log?

- Logging: Log4Net Custom AdoNetAdapter and RollingFileAppender with XML

 

Links:

 

- Log4net web site

- Download Log4net

Visual Studio 11 Developer Preview

Found the MSDN newsletter in my mailbox this morning. First topic that caught my eye: Visual Studio 11 Dev Preview! Another one? Indeed!!! So here is some more information on the new kid on the block.

 

What's New in Visual Studio 11 Developer Preview

Visual Studio 11 Developer Preview Training Kit

 

.NET Framework 4.5 Developer Preview

Read geographical information from the Windows Regional and Language Settings

By DimitriC at December 13, 2011 08:19
Filed Under: Programming, tips & tricks

Recently I got a question of how in .NET it was possible to read from the Windows Regional and Language Settings. Rather than messing around with the Windows registry, the best way to get this information is to use the RegionInfo-object in the System.Globalization namespace.

 

The code:

 

First of all, don’t forget to add the correct using statement:

   1:  using System.Globalization;

After that it’s just declaring the RegionInfo object and reading the settings you’d like (for the example, i’m reading all the settings):

 

   1:  RegionInfo local = RegionInfo.CurrentRegion;
   2:   
   3:  Console.WriteLine("CurrentEnglishName: "+local.CurrencyEnglishName);
   4:  Console.WriteLine("CurrencyNativeName: " + local.CurrencyNativeName);
   5:  Console.WriteLine("CurrencySymbol: " + local.CurrencySymbol);
   6:  Console.WriteLine("DisplayName: " + local.DisplayName);
   7:  Console.WriteLine("EnglishName: " + local.EnglishName);
   8:  Console.WriteLine("GeoId: " + local.GeoId);
   9:  Console.WriteLine("IsMetric: " + local.IsMetric);
  10:  Console.WriteLine("ISOCurrencySymbol: " + local.ISOCurrencySymbol);
  11:  Console.WriteLine("Name: " + local.Name);
  12:  Console.WriteLine("NativeName: " + local.NativeName);
  13:  Console.WriteLine("ThreeLetterISORegionName: " + local.ThreeLetterISORegionName);
  14:  Console.WriteLine("ThreeLetterWindowsRegionName: " + local.ThreeLetterWindowsRegionName);
  15:  Console.WriteLine("TwoLetterISORegionName: " + local.TwoLetterISORegionName);
  16:  Console.WriteLine("ToString: " + local.ToString());

 

image

 

NOTE: Notice that the ToString() method is also implemented for this class. So calling RegionInfo.CurrentRegion.ToString() will give you the TwoLetterISORegionName.

Visual Studio SLN-file tools

By DimitriC at December 12, 2011 11:19
Filed Under: Programming, tools & Utilities, Visual Studio

On Hosam Kamel’s blog there is an interesting post on a tool that helps you finding your way in an SLN-file (Visual Studio Solution file).

 

“Tools for SLN File” is a tool that makes it easier for developers to compare, merge or filter the Solution (.Sln) Files generated by Visual Studio. (source)

Benefits and Features

Using the SLNTools provides the following advantages:

  • - Make it easier to compare SLN files versus a 'generic' file comparer. For more information on the compare function see SLNTools Compare.
  • - Make it easier to merge SLN files versus a 'generic' file merger. For more information on the merge function see SLNTools Merge.
  • - Make it possible to create filters for a SLN file. The way it work is that when the filter file is opened, a temporary solution is created dynamically. The created solution file contain only the projects that are specified in the filter, and all the dependencies of those projects. This make it possible to have a mega-solution that contain all the projects needed to build the complete system but still have the possibility to work efficiently on a subset of the system. As you might know, Visual Studio is a lot faster when you have a solution with 10-20 projects instead of one with 200+ projects (opening the solution, building, etc). For more information on the filter function see SLNTools Filter.

 

For downloading the tools or viewing the full article, please visit the original blog post.

Read from the Windows Registry using C#

By DimitriC at December 08, 2011 09:49
Filed Under: Programming, Windows, tips & tricks

I’ve added an example in the MSDN Samples repository which explains how to read values from the Windows Registry.

 

Description:

 

The example is a simple Console-application that shows you how to select the correct RegistryHive, and afterwards navigate to the correct key and read the value. Keep in mind that reading from the Windows registry always returns an object of type 'object' so you'll need to cast this value to something that makes more sense. This means that you'll be expected to know what you're going to read (integer, binary, string,...). And last but not least, don't forget to add the Microsoft.Win32 using statement!

The available RegistryHives you can read from (and their corresponding names in the Registry Editor (Start => Run => regedit.exe):

  • - ClassesRoot (in RegEdit: HKEY_CLASSES_ROOT)
  • - CurrentConfig (in RegEdit:HKEY_CURRENT_CONFIG)
  • - CurrentUser (in RegEdit:HKEY_CURRENT_USER)
  • - DynData (Windows' own hive with dynamic data. Some configuration information in Windows must be stored in RAM because it requires fast modification and retrieval that cannot wait for the registry to send it to the hard disk. You can find all this data in the HKEY_DYN_DATA registry key. The information in this key is newly created every time Windows starts. Not visible in RegEdit)
  • - LocalMachine (in RegEdit:HKEY_LOCAL_MACHINE)
  • - PerformanceData (Is used to access performance counters but is not visible in Regedit)
  • - Users (in RegEdit:HKEY_USERS)

You can find the example here.

Security Development Lifecycle resources

There are a bunch of new SDL resources available on the Microsoft Security Development Lifecycle page. For every step in the software development process (Requirements, Design, Implementation, Verification, Release) there are tools and/or training videos available. For a video giving an overview of the SDL tools, click here.

 

Source

 

Requirements

Templates:

- SDL Process Template for Visual Studio Team System 2008

- MSF-Agile + SDL Process Template for Visual Studio Team System 2010

- MSF-Agile + SDL Process Template for Visual Studio Team System 2008

 

Videos:

 

 

Design

 

SDL Threat Modeling Tool

 

For more information on the treat modeling tool, click here.

 

Implementation

 

FxCop 

 

FxCop analyzes managed code assemblies (code that targets the .NET Framework common language runtime) and reports information about the assemblies, such as possible design, localization, performance, and security improvements. For more information, click here. Watch the video here.

 

Anti-Cross Site Scripting Library

 

This is specifically designed to help mitigate the potential of Cross-Site Scripting (XSS) attacks in web-based applications. Watch the video here.

 

Microsoft Code Analysis Tool .NET

 

CAT.NET is a binary code analysis tool that helps identify common variants of certain prevailing vulnerabilities that can give rise to common attack vectors such as Cross-Site Scripting (XSS), SQL Injection, and XPath Injection. Watch the video here.

 

 

Verification

BinScope Binary Analyzer

 

BinScope Binary Analyzer is a verification tool that analyzes binaries to ensure that they have been built in compliance with the SDL requirements and recommendations. Watch the video here.

 

SDL MiniFuzz File Fuzzer

 

MiniFuzz is a basic testing tool designed to help detect code flaws that may expose security vulnerabilities in file-handling code. Watch the video here.

 

AppVerifier

 

Application Verifier is a runtime verification tool for native code that assists in finding subtle programming errors that can be difficult to identify with normal application testing. For more information, click here.

 

SDL Regex Fuzzer

 

SDL Regex Fuzzer is a verification tool to help test regular expressions for potential denial of service vulnerabilities. Watch the video here.

 

Attack Surface Analyzer Beta

 

Attack Surface Analyzer is a tool that highlights the changes in system state, runtime parameters and securable objects on the Windows operating system.

 

 

Release

The release resources are the same templates and videos as the ones in the Requirements section.

WCF and certificate-based authentication

By DimitriC at October 06, 2011 08:30
Filed Under: Architecture, Programming, Security, tips & tricks, WCF

If you want your WCF service to use certificate-based (X.509) certification to authenticate the users accessing your service, you’ll need to provide the right configuration on both the client and the server side. The keyword here is configuration. When I first started searching for a solution I knew it had to be done in the configuration file, but, as usual, I kind of underestimated the amount of configuring that had to be done.

 

Especially when you’re looking at the generated configuration file provided by Visual Studio, it’s easy to get lost in all the possible security settings. I once attended a course given by Juval Löwy (IDesign) on WCF where he applauded the fact that the WCF-team had made everything configurable and at the same time warned us for the complexity that came with it.

 

The solution: There is a easy-to-follow example where you can learn how certificate-based authentication for WCF can be done at Mitch Denny’s blog - Using Certificate-based Authentication and Protection with Windows Communication Foundation (WCF)

 

He starts out by creating a simple WCF service (with 1 HelloWorld-method) and afterwards adding the authentication configuration.

Visual Studio LightSwitch

By DimitriC at August 31, 2011 17:07
Filed Under: Documentation, Microsoft, Programming, Visual Studio, Training, tools & Utilities

The first post I did about this was the announcement of it's beta release. The final version has been available for a while now, so here we go :)

 

What is Visual Studio LightSwitch?

Microsoft Visual Studio LightSwitch is a simplified self-service development tool that enables you to build business applications quickly and easily for the desktop and cloud. What can your business do with LightSwitch? Watch this brief introduction to find out.

 

Links & resources:

Visual Studio LightSwitch page
MSDN LightSwitch Development Center
Visual Studio LightSwitch Technical White Paper Series

 

LightSwitch videos:

 

Overview with Jason Zander
Build Custom Business Apps. Coding Optional.

Introductory videos

Creating Your First Business Application
Data, Queries and Code in LightSwitch 2011
Controlling Access to Your Business Application
Publishing Your LightSwitch Application

Advanced videos

Understanding the LightSwitch Architecture
Deploying Your Application to the Cloud
Advanced LightSwitch Customization
Advanced LightSwitch Extensions

Extension videos

DevExpress LightSwitch Extensions
Infragistics LightSwitch Extensions
RSSBus LightSwitch Extensions

Visual Studio 2010: Team explorer issue

Recently I’ve been working on a project with a friend of mine. One of the things we were playing with was Team Foundation Server 2010. So we set it up and I connected to it using Visual Studio 2010 Ultimate. Collaborating was not an issue. Sharing documents, using source control,… everything worked fine. Now I wanted to work on some of my ideas. I wanted to start a new project in Visual Studio, but the only option that was available to me was the “Start new team project” issue:

 

image

 

When clicking here, I got the following error (which is ok since my rights on that TFS server have been revoked):

 

image

The weird thing here is that I have a fully working version of Visual Studio 2010 Ultimate installed, but I only get the Team Explorer functionality. You can verify this by checking the installed components of Visual Studio in the “About”-window (Help –> About Microsoft Visual Studio).

 

To get back to the “normal” mode in Visual Studio (meaning: being able to create new projects and working with VS2010 normally) you need to reset your preferences by doing Tools > Import/Export settings > Import. Here you can choose to reset everything or to import a certain configuration. I chose to import a predefined configuration without backing up my current configuration (wasn’t much use to me anyhow):

 

image

 

I selected the Visual C# Development Settings and pressed “Next”. There I chose to reset all settings and clicked the “Finish” button:

 

image

 

Now that my configuration settings have been restored, I have the regular view in my Visual Studio and I can create projects again!

 

image

Microsoft All-in-one code framework

Something I found that might come in handy:

 

The Microsoft All-In-One Code Framework is a free, centralized code sample library driven by developers' needs. Our goal is to provide typical code samples for all Microsoft development technologies, and reduce developers' efforts in solving typical programming tasks.

 

Codeplex page

Download (from Codeplex)

Request a code sample

 

For a full list of downloads (sorted by technology), please check the Codeplex download page. There are samples available for C++, ASP.NET, Silverlight, Azure, Office, Windows, WPF, Windows Security, and many more…

Book: Algorithms of the intelligent web

By DimitriC at March 31, 2011 18:40
Filed Under: Books, Architecture, Programming, Training

clip_image001

 

A very interesting read, written by Haralambos Marmanis, Dmitry Babenko, on how the web provides us with a rich user experience with the help of algorithms. Topics such as ranking and recommendation systems are explained very well and are illustrated with examples. Also, API's from well known sites such as Google, eBay and Facebook are discussed.

 

The book on amazon.

The Job Interview: Technical questions (Pt. IV)

By DimitriC at March 21, 2011 19:56
Filed Under: Programming, Training

An often requested piece of code is a sort algorithm. Of course, there are many sorting algorithms as you can see with our good friend wikipedia. A popularly one is the Bubble sort. In it’s essence it’s not a difficult algorithm once you know how it works. But in interviews it’s usually the case that you haven’t had to implement it for a long time or maybe you’ve just graduated and have never heard of it (but then you shouldn’t have graduated or the people responsible for your curriculum need a good talking to!) A good alternative for the bubble sort is the Insertion sort.

 

A short description:

 

“…a simple sorting algorithm that works by repeatedly stepping through the list to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. “ – Source: Wikipedia

The algorithm:

   1: void BubbleSort(int[] intArray)
   2: {
   3:     int tmp;
   4:     for (int i = intArray.Length - 1; i >= 0; i--)
   5:     {
   6:         for (int j = 1; j <= i; j++)
   7:         {
   8:             if (intArray[j - 1] > intArray[j])
   9:             {
  10:                 tmp = intArray[j - 1];
  11:                 intArray[j - 1] = intArray[j];
  12:                 intArray[j] = tmp;
  13:             }
  14:         }
  15:     }
  16: }

 

 

An example of using the method above:

 

   1: void Main(string[] args)
   2: {
   3:     int[] intArray = new int[] { 2, 8, 4, 9, 5, 1 };
   4:     PrintArray(intArray);
   5:     BubbleSort(intArray);
   6:     Console.WriteLine();
   7:     PrintArray(intArray);
   8:  
   9:     Console.ReadKey();
  10: }
  11:  
  12: public static void PrintArray(int[] intarray)
  13: {
  14:     foreach (int number in intarray)
  15:     {
  16:         Console.WriteLine(number);
  17:     }
  18: }

 

…gives the following output:

 

image

The Job Interview: Technical questions (Pt. III)

By DimitriC at March 14, 2011 19:22
Filed Under: Programming

Another fun question is when during a technical interview, they ask you to write a recursive program to display Fibonacci numbers.

 

The definition (from wikipedia, link above):

 

“By definition, the first two Fibonacci numbers are 0 and 1, and each subsequent number is the sum of the previous two. Some sources omit the initial 0, instead beginning the sequence with two 1s.”

 

The definition might give you a clue on how to solve this recursively since every result is the sum of the previous 2 result. What I’ve done is to create a method to calculate this that takes the number of times the recursion has to occur as a parameter:

 

   1: int Fibonacci(int x)
   2: {
   3:     if (x <= 1)
   4:         return 1;
   5:     return Fibonacci(x - 1) + Fibonacci(x - 2);
   6: }

 

Of course, this means that you will have to call this method from a loop-statement where you can say how many recursions you want:

 

   1: public static void Main()
   2: {
   3:     for (int i = 0; i < 10; i++)
   4:     {
   5:         Console.WriteLine(Fibonacci(i));
   6:     }
   7:  
   8:     Console.ReadKey();
   9: }

 

So this main-method will call the Fibonacci method 10 times, which gives the following output:

 

image

Free Microsoft e-books

A new list of free e-books on Microsoft technologies has been released on the Microsoft Press blog. Below is the list of available books (including sample code if available).

Programming Windows Phone 7 (Charles Petzold) PDF - Sample Code C# - Sample Code VB.NET
Introducing Microsoft SQL Server 2008 R2 (Ross Mistry and Stacia Misner) XPS - PDF
Understanding Microsoft Virtualization Solutions, From the Desktop to the Datacenter (Mitch Tulloch) XPS - PDF
Introducing Windows Server 2008 R2 (Charlie Russel and Craig Zacker with the Windows Server Team at Microsoft) XPS - PDF
First Look Microsoft Office 2010 (Katherine Murray) XPS - PDF
Deploying Windows 7, Essential Guidance (Mitch Tulloch, Tony Northrup, Jerry Honeycutt, Ed Wilson,...)  PDF
Moving to Microsoft Visual Studio 2010 (Patrice Pelland, Pascal Paré, and Ken Haines) XPS - PDF - Sample Code

 

(original post)

The Job Interview: Technical questions (Pt. II)

By DimitriC at March 09, 2011 19:10
Filed Under: Programming, Training, tips & tricks

Let’s have a look at a binary tree. In my implementation of the binary tree, I use a property to keep track of the fact that the node in question is the root node (= the node where the tree begins), the Parent-property. This refers to the node that has the current node as one of it’s children (or leafs). You can of course browse through your entire tree to find the node that’s not referenced by any other node, but that will probably take a lot of checks, especially if you have a big binary tree. Even when it’s a small binary tree I would use this property. It makes it easier to navigate through the tree.

 

   1: public class BTNode
   2: {
   3:     public BTNode LeftNode { get; set; }
   4:     public BTNode RightNode { get; set; }
   5:     public BTNode Parent { get; set; }
   6:  
   7:     public int value;    
   8:  
   9:     public BTNode(int val)
  10:     {
  11:         this.value = val;
  12:     }
  13:  
  14:     public void AddNode(BTNode newNode)
  15:     {
  16:         newNode.Parent = this;
  17:  
  18:         if (newNode.value >= this.value)
  19:         {
  20:             if (RightNode == null)
  21:             {
  22:                 RightNode = newNode;
  23:             }
  24:             else
  25:             {
  26:                 RightNode.AddNode(newNode);
  27:             }
  28:         }
  29:         else
  30:         {
  31:             if (LeftNode == null)
  32:             {
  33:                 LeftNode = newNode;
  34:             }
  35:             else
  36:             {
  37:                 LeftNode.AddNode(newNode);
  38:             }
  39:         }
  40:     }
  41:  
  42:     public BTNode Search(int srchValue)
  43:     {
  44:         if (srchValue == this.value)
  45:         {
  46:             return this;
  47:         }
  48:  
  49:         if (srchValue >= this.value)
  50:         {
  51:             if (this.RightNode == null)
  52:             {
  53:                 return null;
  54:             }
  55:             else
  56:             {
  57:                 return this.RightNode.Search(srchValue);
  58:             }
  59:         }
  60:         else
  61:         {
  62:             if (this.LeftNode == null)
  63:             {
  64:                 return null;
  65:             }
  66:             else
  67:             {
  68:                 return this.LeftNode.Search(srchValue);
  69:             }
  70:         }
  71:     }
  72:  
  73:     public void Delete()
  74:     {
  75:         //bottom of tree
  76:         if (this.LeftNode == null && this.RightNode == null)
  77:         {
  78:             if (this.Parent.LeftNode.value == this.value)
  79:             {
  80:                 this.Parent.LeftNode = null;
  81:             }
  82:             else
  83:             {
  84:                 this.Parent.RightNode = null;
  85:             }
  86:         }
  87:  
  88:         //Middle of tree - RightNode
  89:         if (this.LeftNode == null && this.RightNode != null)
  90:         {
  91:             if (this.Parent.LeftNode.value == this.value)
  92:             {
  93:                 this.Parent.LeftNode = this.RightNode;
  94:             }
  95:             else
  96:             {
  97:                 this.Parent.RightNode = this.RightNode;
  98:             }
  99:         }
 100:  
 101:         //Middle of tree - LeftNode
 102:         if (this.LeftNode != null && this.RightNode == null)
 103:         {
 104:             if (this.Parent.LeftNode.value == this.value)
 105:             {
 106:                 this.Parent.LeftNode = this.LeftNode;
 107:             }
 108:             else
 109:             {
 110:                 this.Parent.RightNode = this.LeftNode;
 111:             }
 112:         }
 113:  
 114:         if (this.LeftNode != null && this.RightNode != null)
 115:         {
 116:             if (this.Parent == null)
 117:             {
 118:                 throw new ApplicationException("You can not delete the root node!");
 119:             }
 120:  
 121:             if (this.Parent.LeftNode.value == this.value)
 122:             {
 123:                 this.Parent.LeftNode = this.LeftNode;
 124:                 this.LeftNode.RightNode = this.RightNode;
 125:             }
 126:             else
 127:             {
 128:                 this.Parent.RightNode = this.RightNode;
 129:                 this.RightNode.LeftNode = this.LeftNode;
 130:             }
 131:         }
 132:     }

 

To use it, you instantiate a node and assign new BTNodes to the leaves. Wherever you are in the tree-structure, you’ll find it easy to search for nodes. Keep in mind that the AddNode and Delete only reflect on the current node.

The Job Interview: Technical questions (Pt. I)

By DimitriC at March 01, 2011 08:56
Filed Under: Programming, Training

Ever since I graduated I’ve been employed as a .NET consultant. When applying for jobs (whether it’s at a consultancy firm or as a representative of your firm getting interviewed by a client) there is often a technical interview. Next to the fun object-orientation questions we all love so much (explain polymorphism, data abstraction, inheritance, Liskov’s substitution principle,…), there were sometimes these little exercises they used to test your approach to problem solving or to see how you react to a very unfamiliar problem. These questions can take different forms. You’ve got you’re here-is-a-piece-of-code-and-tell-me-what-the-output-is-questions, mathematical problems, writing code,…Even brain-teasers can be a part of the interview. 

 

In the “writing code” department you can be asked to write well known data structures yourself (e.g.: write your own linked list/binary tree), write an algorithm (sorting algorithm,search algorithm, reversing collections,…). The meaning of this series is to discuss some of these questions, find out where the pitfalls are and see what side-questions might be added to the exercise.

 

So let’s get to it! As a first exercise, let’s look at an implementation of a linked list.  In the .NET Framework, you can find a linked list in the System.Collections.Generic library.

 

For our basic implementation we need a Node-class where we can hold the references for the previous and the next item in the list. We’ll immediately keep references to both the next and the previous node as we’ll notice that it might be handy to navigate through the list. This is already a more complex version of a linked list (since the most simplistic version only holds the reference to the next node).

 

   1: public class Node
   2: {
   3:     private Node prevNode;
   4:     private Node nxtNode;
   5:     private string strValue;
   6:  
   7:     public Node(Node prevNode, Node nxtNode, string stringValue)
   8:     {
   9:         this.prevNode = prevNode;
  10:         this.nxtNode = nxtNode;
  11:         this.strValue = stringValue;
  12:     }
  13:  
  14:     public Node PrevNode
  15:     {
  16:         get { return this.prevNode; }
  17:         set { this.prevNode = value; }
  18:     }
  19:  
  20:     public Node NxtNode
  21:     {
  22:         get { return this.nxtNode; }
  23:         set { this.nxtNode = value; }
  24:     }
  25:  
  26:     public string StringValue
  27:     {
  28:         get { return this.strValue; }
  29:         set { this.strValue = value; }
  30:     }
  31:  
  32:     public void Delete()
  33:     {
  34:         this.prevNode.nxtNode = this.nxtNode;
  35:         this.nxtNode.prevNode = this.prevNode;
  36:     }
  37: }

 

This is a basic node-class. As a value I chose a string, but of course, that can be anything you want. This node is what we’ll use to create our list. We’ll have a list-object that contains the first node, and of course, since each node points to the next one in the list, the list-object will contain all the methods to navigate through the list.

 

   1: public class LinkedList
   2: {
   3:     public LinkedList(string stringValue)
   4:     {
   5:         nCurrent = new Node(null, null, stringValue);
   6:         nCurrent.NxtNode = null;
   7:         nCurrent.PrevNode = null;
   8:     }
   9:  
  10:     int iCount = 1;
  11:     int iCurrent = 0;
  12:     Node nCurrent;
  13:  
  14:     public int Count 
  15:     { 
  16:         get{return this.iCount; }
  17:     }
  18:  
  19:     public Node CurrentNode 
  20:     { 
  21:         get{return this.nCurrent;}
  22:     }
  23:  
  24:     public Node CurrentNodeIndex 
  25:     { 
  26:         get{return this.nCurrent;}  
  27:     }
  28:  
  29:     public void AddNode(string strValue)
  30:     {
  31:         if (nCurrent.NxtNode == null)
  32:         {
  33:             nCurrent.NxtNode = nCurrent;
  34:             nCurrent = new Node(nCurrent, null, strValue);
  35:         }
  36:         else
  37:         {
  38:             nCurrent.NxtNode = nCurrent;
  39:             nCurrent = new Node(nCurrent, nCurrent.NxtNode, strValue);
  40:         }
  41:         iCount++;
  42:         iCurrent++;
  43:     }
  44:  
  45:     public void ToNext()
  46:     {
  47:         Node tmpNode = null;
  48:  
  49:         if (nCurrent.NxtNode == null)
  50:         {
  51:             throw new Exception("there is no next node!");
  52:         }
  53:         else
  54:         {
  55:             tmpNode = nCurrent;
  56:             nCurrent = nCurrent.NxtNode;
  57:             nCurrent.PrevNode = tmpNode;
  58:             iCurrent++;
  59:         }
  60:     }
  61:  
  62:     public void ToPrevious()
  63:     {
  64:         Node tmpNode = null;
  65:  
  66:         if (nCurrent.PrevNode == null)
  67:         {
  68:             throw new Exception("there is no previous node!");
  69:         }
  70:         else
  71:         {
  72:             tmpNode = nCurrent;
  73:             nCurrent = nCurrent.PrevNode;
  74:             nCurrent.NxtNode = tmpNode;
  75:             iCurrent--;
  76:         }
  77:     }
  78:  
  79:     public void GoTo(int index)
  80:     {
  81:         while (iCurrent != index)
  82:         {
  83:             if (iCurrent < index)
  84:             {
  85:                 ToNext();
  86:             }
  87:             else if (iCurrent > index)
  88:             {
  89:                 ToPrevious();
  90:             }
  91:         }
  92:     }
  93:  
  94:     public void First()
  95:     {
  96:         while (nCurrent.PrevNode != null)
  97:         {
  98:             ToPrevious();
  99:         }
 100:     }
 101: }

Now you can instantiate the list. The constructor also requires a string value to define your first element in the list. Then you’ll find the methods to navigate through the list. And the nCurrent-property of the Linked List will contain the node where you navigated to.

 

A possible variation you might get asked is a circular linked list. This means that the last element you add (which points to null) actually should point to the first element in the list. For a full theoretical explanation I refer to wikipedia.

The known bug with the WCF Service Configuration Editor

By DimitriC at January 21, 2011 22:43
Filed Under: Programming, Visual Studio, tips & tricks, tools & Utilities, WCF

In both Visual Studio 2008 and 2010 there is a bug when you try to use the WCF Service Configuration Editor. The editor should be reachable through the Tools-menu or by right clicking a configuration file (web.config / app.config). This appears to be a known bug. It’s not blocking, but it’s easier to access the editor directly from the configuration file (then the file is immediately loaded in the editor). 

When you just started Visual Studio, and right-click a configuration file, the editor is not visible as an option:

 

image

 

 

Now open the editor from the tools menu (Tools –> WCF Service Configuration Editor):

 

image

 

Now the editor will open. You can close it immediately and go back to the configuration file. When you right-click it now, you will see that the option to open the editor is available:

 

image

Free e-books on .NET and architecture

By DimitriC at October 12, 2010 08:07
Filed Under: Architecture, Books, Microsoft, Programming, tools & Utilities, Training

The new MSDN Flash arrived this morning, and it offered 7 free e-books (actually 6 e-books and some reference cards) on .NET and architecture. For the original article that was posted in the newsletter, click here.

 

The books:

 

- Foundations of programming (Karl Seguin)
- Microsoft Application Architecture Guide, 2nd Edition (Microsoft)

- Rob Miles C# Yellow Book 2010 (Rob Miles)

- Threading in C# (Joe Albahari)

- Improving .NET Application Performance and scalability (Microsoft)

- Applying Design Patterns (Anoop Madhusudanan)

 

And some References Cards (RefCardz) from DZone:

 

- Getting Started with WCF 4.0 (Scott Seely)

- Getting Started with Silverlight + Expression Blend (Victor Gaudioso)

- Essential F# (Chance Coble, Ted Neward)

Log4Net logging framework, custom AdoNetAdapter and RollingFileAppender with XML

By DimitriC at October 04, 2010 10:00
Filed Under: Architecture, log4net, Programming, tips & tricks, tools & Utilities

Mike Bevers has done some cool work with log4net. Next to creating his own logging framework using L4N, he also implemented a custom AdoNetAdapter (logging to a database) and a RollingFileAppender with XML.

 

For more information, please check his blog, or the Log4Net posts:

 

- Logging Framework with Log4Net
- Log4Net: custom AdoNetAppender
- Log4Net: RollingFileAppender with XML

Generics part III: Constraints

By DimitriC at October 03, 2010 13:36
Filed Under: Programming

There are three kinds of type parameter constraints. There are primary constraints, secondary constraints and constructor constraints. The number of constraints that you can specify depends on the type of constraint, as shown in this table:

 

Constraint Type Allowed
Primary Constraint 0 or 1
Secondary Constraint 0 or more
Constructor Constraint 0 or 1

 

When applying primary constraints you actually make a deal with your compiler. The deal says that the type parameter you will pass on is of a certain type OR derived from this type. For example: if you have a system where you do the management of vehicles, you might have your model have a base class Vehicle, and some derived types: Car, Truck, Boat and Airplane. The syntax looks like this:

 

   1: internal sealed class ExampleOfConstraintOfVehicle<T> where T : Vehicle
   2: {
   3:     public void DoSomething(T vehicle)
   4:     {
   5:         //...do something with the vehicle
   6:     }
   7:
 

Now, when instantiating this class with something that isn’t a vehicle, you will get an error at compile time:

 

The type '[type]' must be convertible to 'SystemObject.Vehicle' in order to use it as parameter 'T' in the generic type or method 'SystemObject.Program.ExampleOfConstraintOfVehicle<T>'

 

You can also tell your compiler that the type you will pass along as a type parameter is a reference type or a value type. This is done by using the “class” or “struct” keyword. So changing the example above will result in the following:

 

Reference type:

internal sealed class ExampleOfConstraintOfRefType<T> where T : class

 

Value type:

internal sealed class ExampleOfConstraintOfValType<T> where T : struct

 

Secondary constraints represent interface types. Here your deal with the compiler says that any type you pass along as a type argument will implement that interface. The table in the beginning of the post mentions that 0 or more secondary constraints are allowed. This is logical since a class can implement several interfaces and so you can also demand that a secondary constraint checks that a number interfaces is implemented in the type argument.

 
internal sealed class ExampleOfConstraintOfIConstraint<T> where T : ICloneable

 

Again, here the argument is checked at compile time. If you pass a type argument that doesn’t comply with the constraint, you will see the following error:

 

'The type '[type]' must be convertible to '[IConstraint]' in order to use it as parameter 'T' in the generic type or method 'SystemObject.Program.ExampleOfConstraintOfIConstraint<T>'

 

Another type of constraints are the constructor constraints. Here the deal with the compiler is that the type argument you’re passing along implements a default constructor (public and no parameters). Passing a constructor with parameters is not possible.

Generics Part II: internals

By DimitriC at September 26, 2010 17:57
Filed Under: Programming

When the CLR builds our application, it will make an internal structure for each type we use in the application. The generic types we create are no different, on the condition that the generic type parameters have values assigned to them. If these parameters don’t have values (data types) assigned to them they are called an “open type” and the CLR will not allow the construction of such a type (because basically, the CLR doesn’t know what to build exactly). If the data type parameters are properly filled in, the CLR will create internal types for these objects. This is called a “closed type”.

 

When the compiling code that uses generic type parameters, the compiler generates IL, fills in the parameters and generates native code specific to that method for those types. This is exactly the same as how other code is compiled and is an advantage of generics (it behaves as you would expect). Of course, since no good deed goes unpunished, there is a down side to this. The CLR keeps generating native code for every method-type combination possible. This can increase the amount of memory required by your application enormously. This is called “code explosion”.

At Microsoft they were fully aware of this, so the CLR has built in optimizations to counter code explosion. The CLR will keep track of the method-type combinations it generates code for. If the same method-type combination is used somewhere else in the code, it will use the already generated IL-code. If you have several assemblies in your application that use List<string>, the CLR will emit code just once and re-use this code. Also, if you are using reference type arguments, the code for these types are only generated once. This is because the CLR thinks of all reference type arguments as the same (to the CLR these are all just pointers). Unfortunately, the issue with value types remains. Here the CLR must emit code for each type individually. Even if these types are basically the same (e.g.: Int32 and UInt32), every type will have its own native code since different native processor-instructions can be used to work with these values.

 

The following is something that you may not have heard of by name, but you’ve certainly used it, which is “type inference”. This concept is supported by the C# compiler and allows you not to define every type when assigning it.

 

For example:

 

Int32 number = 5;
String someText = “Some text”;

 

Here the compiler will check the type of the value (let’s say: “Some Text”), it will recognize the value as type String and see that you want to assign it to an object of type String, and so the compiler will assign the value to the object without complaining. You can see the problem that might arise when using generics. If you call a generic method without specifying a type, you will get a compiler error (error CS0411). I got a great example for this in Jeffrey Richter's book CLR via C#:

 

   1: private static void Display(String s) 
   2: {
   3:   Console.WriteLine(s);
   4: }
   5:  
   6: private static void Display<T>(T o) 
   7: {
   8:   Display(o.ToString()); 
   9: }
  10:  
  11: //In main:
  12: Display("Jeff"); 
  13: Display(123); 
  14: Display<String>("Aidan"); 

 

The compiler always looks for an exact match when calling methods. So the first call will go directly to the Display()-method that takes a string as an argument. And the third call will go to the generic overload of the Display()-method. The nice thing here is the second call. There is no specific overload of the Display()-method that takes an integer as a parameter. So, the compiler will settle for the generic match. It can define the type of “123” (which is Int32), so it can call the generic overloaded version of the Display()-method and gives the following output (I’ve added some extra text to point out what method is being called):

 

clip_image002

Developing Applications for the Cloud on the Microsoft Windows Azure™ Platform

By DimitriC at September 23, 2010 10:27
Filed Under: Architecture, Programming, Training, Cloud

Microsoft patterns & practices is excited to announce the release of a new guide: Developing Applications for the Cloud on the Microsoft Windows Azure™ Platform

 

The cloud platform provides you with access to capacity on demand, fault tolerance, distributed computing, data centers located around the globe, and the capability to integrate with other platforms. Someone else is responsible for managing and maintaining the entire infrastructure, and you only pay for the resources that you use in each billing period. You can focus on using your core domain expertise to build and then deploy your application to the data center or data centers closest to the people who use it. You can then monitor your applications, and scale up or scale back as and when the capacity is required. - Source MSDN

Links:

- Code Samples
- Community