KickStart – C# Custom Configuration

This post will provide an example and explanation of how to create custom configuration for C# applications. I will discuss ConfigurationSections, ConfigurationElements, ConfigurationElementCollection. Also I will discuss how to nest these items together. My plan is to take very small steps; implementing each part of the configuration individually.

By the end of the post we will be able to navigate a custom configuration similar to the following config file:


  • Good understanding of C#
  • Good understanding Visual Studio – I’m will be using VS 2012
  • .NET 3.5 and higher
  • Basic understanding of configuration files

The application we are going to create is quite contrived. The school settings that we will store in the config file would usually be stored in a database, but I want to provide a domain that most people understand.

Our Domain

A School has
A Name
A Address
Zero or More Courses
A Course has
A Title
An Optional Instructor
Zero or More Students
A Student has
A StudentId

We are going to create a Windows Console application. All it’s going to do is display values from the config file. When we are completed with the application it will display something similar to this:

Continue reading “KickStart – C# Custom Configuration”

Understanding AngularJS – Simple Example

I did a similar post as this post for Backbone.js Understanding Backbone.js – Simple Example. Based on readers’ comments the backbone.js post seemed to assist many people. My goal with this post is to help others understand the core parts of AngularJS and how they work together.

The AngularJS application that we are building will display a list of movies and will have the ability to add movies. We could create this application with very minimum code, but extensibility and maintainability will be limited. My primary objective is to show how to structure an AngularJS application that provides a base of knowledge to create other AngularJS applications extensible and maintainable.

My target audience will have some knowledge about AngularJS, but are having a difficult time implementing all but the most basic applications. By simple, I mean you should only have to focus on AngularJS. We will not be using jQuery, Twitter Bootstrap, or other 3rd party libraries.

We could create this application with just a controller and a view. But in this post I will describe the following core AngularJS features:

  • Routes
  • Modules
  • Views
  • Controllers
  • Services

Above I mentioned I will keep this post simple, but we do need a web server. The AngularJS Theater application will load views and data (json files) from the server. I would like to do these examples by access “file:///E:/TempProjects/Theater/index.html#/” on local computer, but most browsers cannot access these files on local computer do to Cross Origin issues. Here a StackOverflow question and answer that describes this issue: Cross origin requests are only supported for HTTP but it’s not cross-domain. So we need a web server. Any web server will do, such as IIS, Node.js and Express or other server. In this example I will be using Node.js and Express. You will not need to know anything about Node.js; all that is need is for you to install Node.js and to execute a script that I will provide. I will step you through the complete process to get Node.js and Express up and running.

Google Chome will be the browser I use, but any current browser should work fine. The reason I pick Chome is for its development tools. I will be developing in JetBrains WebStorm IDE, but any IDE or text editor should be fine.

This post will be based on a contrived idea of displaying a list of movies at a theater. There is nothing fancy here.

The complete solution can be downloaded from here:
Source – Understand-AngularJS-Simple Example(Theater)

Based on comments from Hasan this example works with AngularJS 1.1.5. It does not work with AngularJS 1.2.3.

Continue reading “Understanding AngularJS – Simple Example”

Unexpected results with Lambdas and Creating New Threads in C#

Today I was creating a simple application that needed to read from a queue and send XML to a web service.  It seemed to me to be a perfect opportunity to create a multi-threaded application.   Since I needed to send multiple properties to a method, I would use the Thread class and pass in a lambda expression.   Everything seem to be working fine, but I saw some strange things going on;  duplicate data was being sent to web service, even though the queue did not include duplicate data.  After a bit of debugging, I noticed that my call with the Lambda expression was passing the same data.  I did a little research on this issue and found this document, Closing over the loop variable considered harmful.   There’s a lot of technical info at this link, so I thought I would create a more simple example that would demonstrate this issue.

In this example I create a list of numbers and display these numbers to the console.  There are two individual foreach statements that loops through the numbers.   The first foreach does nothing special; it just calls DoWork.  All DoWork does is accepts an int and displays the number in the console.  Also DoWork has a sleep method to simulate a long running process.

The second foreach also calls DoWork, but calls DoWork on a separate thread.  The thread that is created accepts a Lambda, which points to DoWork.  It seems everything should work fine, but when you look at the results for the second foreach the data does not look correct.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace Lambda_Threading
    class Program
        static void Main(string[] args)
            List numbers = GetData();

            foreach (int number in numbers)

            foreach (int number in numbers)
                Thread thread = new Thread(() => DoWork(number));


        public static void DoWork(int number)
            Random rand = new Random();
            Thread.Sleep(rand.Next(200, 500)); //Simulate Work
            Console.Write(number + ", ");

        public static List GetData()
            List numbers = new List();

            for (int i = 0; i < 10; i++)

            return numbers;

As you can see the results of the second foreach is not correct. The same number is displayed multiple time.  For example 9 is displayed three times and the numbers 0, 1, 2, 5, and 7 is not displayed at all.  The numbers are not in order because of the random sleep time in the DoWork method.


To solve this problem, all that is needed is a temp variable to store the number from the for loop.

foreach (int number in numbers)
    int tempNumber = number;
    Thread thread = new Thread(() => DoWork(tempNumber));

Now the results are what I was expecting.  The second foreach includes each number once and there are no duplicate numbers.  Again, the numbers are not in order because of the random sleep time in the DoWork method.  Even if you remove the sleep, the numbers still may not be in order.



Simple Example – AOP – Policy Injection with Unity

This is just a simple example explaining the processes/patterns to implement them using Unity 2.0, Dependency Inject, Inversion of Control (Ioc), and Aspect Oriented Programming (AoP). One of my primary goals is to not over complicate these examples. The examples should show how to do one thing and one thing only, but could possibly show how to implement these process/patterns in multiple way.

In this entry I will create a very simple application that shows how to do dependency injection, Interception and Policy Injection using Unity 2.0.

I’m using Unity 2.0 which is part of Enterprise Framework 5.0, and have created a very simple example application to test implementing AOP through Unity Interception. I’ve read a few articles on the web of how to use Unity with Interception and Policy Injection, and believe the articles from Dino Espisto were very benefical in help me figure this stuff out.
MSDN – Aspect-Oriented Programming, Interception and Unity 2.0
MSDN – Interceptors in Unity
MSDN – Policy Injection in Unity

If you are not aware of AOP, one of the primis is that Cross Cutting functionality, such as Loggin, should not be included in your domain classes.  My example contains a very simple console application that inlcudes using Interception that is configured through the Fluent API and a Configuration file.  The example also shows how to do Policy Injection and also configured using Fluent API and Configuration file.

For a contrived rule, emails should not be sent where the email address ends with “”.  I have a class called EmailSerivce.  The EmailService is a fake, it doesn’t do anything other then sleep and print a message to the console.   I do not want to add any code to the EmailSerivce class that validates email; this should be handel by Unity Policy Injection.
Continue reading “Simple Example – AOP – Policy Injection with Unity”

Regular Expression Negative Lookahead

I have a process that creates XML and inserts data within a element.  Some of the data that is inserted includes "&"s.  Since "&" can not be inserted into the XML without causing problems, I need a process to escape "&", but I do not want "&" escaped for the following, since they have already escaped.
&amp;, &gt;, &lt;, &apos;, &quot;,
This is pretty easy process with a while and indexOf, but quite slow.  I believe a RegEx could provide the same functionality, but be more efficient.   My solution uses the following negative lookahead regular expression. 
Regular-Expressions.Info (Lookahead and Lookbehind Zero-Width Assertions)
!!(This did not seem to work, but it did point me in the right direction)Regex to match against something that is not a specific substring (
example of not working (&([^(&amp;)(&gt;)(&lt;)(&apos;)(&quot;)])) it was close but not perfect



Building Proof of Concepts with XML test Data

There are many times where I want to create a Proof of Concept (POC) that uses a data table.  There are situations when I build these POC that I don’t want to connect to to Database,but still need a datatable.  There are times where I don’t want to create the plumb, or I want to create example that are not specific to the project I’m working, just something more generic. So to get around this problem of connecting to DB, I decided to use XML for the source data.
Today I had some problems with a 3rd party component. I didn’t want to post my companies code on the web, so I create a POC and used XML as the data.  I loaded the XML in a Dataset, which allowed me to the data through a DataTable.
I couldn’t get the POC working without the first line of the xml that follows
xmlData.AppendLine(""<?xml version=’1.0′ standalone=’yes’?>");
xmlData.AppendLine(" <ValidationExpression>");
xmlData.AppendLine("  <ID=’101′ Checked=’true’ Name=’Email’ ValidationSeverityID=’201′  />");
xmlData.AppendLine("  <ID=’102′ Checked=’false’ Name=’Phone Number’ />");
xmlData.AppendLine("  <ID=’103′ Checked=’false’ Name=’Social Security’ />");
xmlData.AppendLine("  <ID=’104′ Checked=’false’ Name=’Date’ />");
xmlData.AppendLine("  <ID=’105′ Checked=’false’ Name=’US Zip + 4′ />");
xmlData.AppendLine("  <ID=’106′ Checked=’false’ Name=’US Zip (5 Only)’ />");
xmlData.AppendLine("  <ID=’107′ Checked=’true’ Name=’Date’  ValidationSeverityID=’203’/>");
xmlData.AppendLine(" </ValidationExpression>");
xmlData.AppendLine(" <ValidationSeverity>");
xmlData.AppendLine("  <ID=’201′ Name=’Error’ />");
xmlData.AppendLine("  <ID=’202′ Name=’Warning’ />");
xmlData.AppendLine("  <ID=’203′ Name=’Info’ />");
xmlData.AppendLine(" </ValidationSeverity>");
System.IO.StringReader xmlSR = new System.IO.StringReader(xmlData);
This create 4 tables in the Data Set.
MSDN – Loading a DataSet from XML (ADO.NET)

ASP.NET AJAX WebServices and ScriptServices

I’ve been working with ASP.NET AJAX for the past week and the following resources allowed me to get up to speed pretty fast.  The following two books that I list are pretty good.   Both of the them cover some different information.  I believe the Professional ASP.NET 2.0 AJAX is a little easier to read and the examples are much better. 
Video – How Do I: Use an ASP.NET AJAX ScriptManagerProxy?
Video – How Do I: ASP.NET AJAX Enable an Existing Web Service?
Video – How Do I: Make Client-Side Network Callbacks with ASP.NET AJAX?
Video – How Do I: Choose Between Methods of AJAX Page Updates?
MSDN Article – Using ASP.NET Session State in a Web Service
Book – Introducing Microsoft ASP.NET AJAX (Dino Esposito)
Book – Professional ASP.NET 2.0 AJAX 

Advanced Regular Expression – Groups Name Capture LookAround

Zip Code Regular Expression
I’ve been doing alot of regular expression lately and need some place to put my resources.  Below are some very good links for regular Expressions.
How to validate a valid GUID Value in C#
Password Regex

Python Library Reference


Groups, Name Capture, LookAround, Readability and Maintainability, and Delegates

One of the better website pertaining to Regular Expression
Very Simple example of Named Groups, Backreferences, and Regex.Replace
MSDN Article on Backreferences
Regular Expression Replace in SQL 2005 (via the CLR)
SQL Server 2005 Regular Expressions Make Pattern Matching And Data Extraction Easier
A T-SQL Regular Expression Library for SQL Server 2005
Regular Expression Cheat Sheat