Entity Framework Code First and WCF Data Services

Entity Framework combined with WCF Data Services provides you a fast approach to present your data. In combination with Entity Framework Code first it allows you to create simple applications, which shows a quick result and are also easy to maintain (also great for quick samples and mocks, because EF Code First generates the database for you). EF code first is part of part of EF CTP and will be added to the .NET Framework in a future version. The CTP can be downloaded here!

Entity Framework Code First allows you to create your model without any designer or XML. The tables will be mapped automatically to your custom classes if the class have the similar name than the table and the fields have the similar name than the columns. The real great thing is, when your database doesn’t exist, EF will create it for you on the fly, just like magic! This is great if you create some mocks or samples.

public class ServerInfo
{
    public int ID { get; set; }
    public DateTime Startup { get; set; }
}

public class ServerContext: DbContext { public DbSet ServerInfos{get; set;} }
static void Main(string[] args) { ServerContext conn = new ServerContext(); conn.ServerInfos.Add(new ServerInfo() { Startup = DateTime.Now }); conn.SaveChanges(); }

That’s all code you need. Now you can with it like all other Entity Framework Context and Entities. But back to our goal, to create a WCF Data Services combined with Entity Framework Code First (which isn’t that far away now). Simply create a ASP.NET web application add the two class ServerContext and ServerInfo to the project. Additionally add a WCF Data Service, which we will call ServerInfoService.

[ServiceBehavior(IncludeExceptionDetailInFaults = true)]
public class ServerInfoService : DataService<ServerContext>
{
public static void InitializeService(DataServiceConfiguration config)
{
ServerContext conn = new ServerContext();
conn.ServerInfos.Add(new ServerInfo() { Startup = DateTime.Now });
conn.SaveChanges();

config.SetEntitySetAccessRule("*", EntitySetRights.All);
}
}

The ServerBehaviour is only added to see the error if you text your application. Every time the service is started, a new record to the database is added with the startup time. Now you can hit F5, select the ServerInfoService.svc and you should see a result in form a XML. Now we need a client project. Create a console application and add the service with “add service reference” (call the service reference also ServerInfoService).

static void Main(string[] args)
{
var uri = new Uri("http://localhost:7640/ServerInfoService.svc");

var context = new ServerInfoService.ServerContext(uri); foreach(var values in context.ServerInfos) { Console.WriteLine(values.Startup); } Console.ReadLine(); }

Copy the code into your Program.cs file and replace the port number with port number of your services. It iterates over all ServerInfo objects which are loaded from your database and print the startup time to the console.

Just great how fast and easy you are able to present some data which is stored in your database. Anyhow the combination of EF and WCF Data Services allows to create correctly layered applications without any additional effort.

Download the source code

C# reference types are passed by value!


How many times I read: “In C# reference types are passed by reference, primitive types by value”? The essential point is that reference types has nothing to do with passing by reference!

But let us start with some basics. There are two types of objects, the value types (structs) where the variable is the object and the reference types which only points to the object. When you pass in a variable to a method, its value gets copied to the method by default. For values types, that means the object itself gets copied. For reference types, that means only the thing that points at the object gets copied!

It is a little bit confusing, because only the reference to the object is copied, not the entire structure. It is a way to save performance, otherwise as larger as the reference type would be as more performance it would cost. This strategy is also know as call by sharing (which makes it a less confusing than calling it also call by value with reference types). So in a call by value scenario, if the data of a reference type is changed inside the method, the caller variable is also affected. If you change a the value of a value type, which is passed to a method, it will not affect the caller variable.

public void Sample()
{
Point point = new Point(20, 30);
Person person = new Person() { Name = "Meier" };

CallByValue(point, person);

Console.WriteLine("Point X: {0}", point.X);
Console.WriteLine("Name: {0}", person.Name);
}

public void CallByValue(Point point, Person person)
{
point.X = 10;
person.Name = "Müller";
}

The ref keyword indicates in C# a call by reference. When pass a value type by reference to a method, the changes to the value which are done in the method scope, will also affect the variable in the code of the caller. But what happens if you pass reference type to a method by ref?

public void Sample()
{
Point point = new Point(20, 30);
Person person = new Person() { Name = "Meier" };

CallByValue(ref point, ref person);

Console.WriteLine("Point X: {0}", point.X);
Console.WriteLine("Name: {0}", person.Name);
}

public void CallByValue(ref Point point, ref Person person)
{
point.X = 10;
person = new Person() { Name = "Müller" };
}

It allows to change the instance which the variable points to. So you can assign a new object to the variable and also the caller variable will point to the new object. By the way the behaviour in VB.NET is similar to the behaviour of C#, the only difference is that in VB.NET you always have to define if you want to pass a value by value or reference.

List.ForEach or foreach, it doesn’t matter…or does it?

In C# you have various possibilities to iterate over a list like for loop, foreach loop or with LINQ. When you use a List(T) type you have even one more, the ForEach method. But this method doesn’t show always the same behaviour than a normal foreach loop.

The ForEach method of the List<T> (not IList<T>) executes an operation for every object which is stored in the list. Normally it contains code to either read or modify every object which is in the list or to do something with list itself for every object.

Modify the object itself

The following sample with a ForEach method loops over all stored Points in the collection. It substracts 10 from the x coordinate of the point. At the end the Points will be printed to the console.

List<Point> points = new List<Point>()
{
new Point(14, 10),
new Point(19, 10)
};

items.ForEach(point => point.X = point.X - 10);

foreach (Point point in points)
{
Console.WriteLine(point);
}

The output in the console is in this case {X=14, Y=10} and {X=19, Y=10}. I expected that X is 4 and 9, so what’s wrong? If you put the same logic into a normal foreach statement the compiler throws the following error: “Cannot modify members of ‘point’ because it is a ‘foreach iteration variable’”. If we define our own type, the code does what it should do! 

public class MyPoint
{
public MyPoint(int x, int y){ X = x; Y = y; }
public int X{ get; set; }
public int Y{ get; set; }
}

List<MyPoint> points = new List<MyPoint>()
{
new MyPoint(14, 10),
new MyPoint(19, 10)
};

items.ForEach(point => point.X = point.X - 10);

foreach (MyPoint point in points)
{
Console.WriteLine(point);
}

The difference is, that Point is a value type, a struct, and MyPoint is a reference type. So in the case where Point is used, a copy of the object is passed to the method, not the object itself. So if the action, which is passed into the ForEach method, changes the copy, but it won’t affect the original object.

Modify the collection

When you use a normal foreach statement, you can’t add or remove items while iterating over the collection. But with List.ForEach you can, so the following code can be executed without any errors. Which result do you expect?

public class Integer
{
public int Value { get; set; }
public Integer(int value) { Value = value; }
}

public void Sample()
{
List<Integer> items = new List<Integer>()
{
new Integer(14),
new Integer(0),
new Integer(19)
};

items.ForEach(item =>
{
if (item.Value == 0)
{
items.Remove(item);
}
item.Value = item.Value - 10;
});

foreach (Integer item in items)
{
Console.WriteLine(item.Value);
}
}

The result which is shown in the console is 4 and 19. So this is a good example that not all what you can do, you also should do! The result should be 4 and 9! It seems that internally a for loop is is used, which iterates backward over the collection. 

Conclusion

So List<T>.ForEach allows several things which is blocked in a foreach loop. These things aren’t allowed for a good reason. So if you want to store objects of value types, like int, long, double, bool or even string,  in a generic List, you shouldn’t use the ForEach method if you want to avoid problems. A good solution is use a for loop and access the data over the indexer of the collection. Also removing items in the ForEach method is a thing which should be avoided also when it is possible. 

Static constructor in C#

Did you ever implement a singleton in c#? For those who don’t know what a singleton is, it is a class which can only have one instance, more on Wikipedia. The preferred implementation of a singleton in c# is the following.

public sealed class Singleton
{
   //single instance
   private static readonly Singleton instance = new Singleton();
   
   //private constructor
   private Singleton(){}

   public static Singleton Instance
   {
      get 
      {
         return instance; 
      }
   }
}

But what would you do if you want to execute some custom code before the instance of the singleton is initialized? You can use the classic singleton code which isn’t really different than in other programming languages.

public sealed class ClassicSingleton
{
    //single instance
    private static ClassicSingleton instance;
    private static object syncRoot = new Object();

    //private constructor
    private ClassicSingleton() { }

    public static ClassicSingleton Instance
    {
        get
        {
            if (instance == null)
            {
                lock (syncRoot)
                {
                    if (instance == null)
                    {
                        //custom code
                        instance = new ClassicSingleton();
                    }
                }
            }

            return instance;
        }
    }
}

You have to set the constructor private. A static field of the type of the class holds the single instance. Another static method is the single point of access to get an object of the class. Internally it has to lock the access to the static object to be sure that really only one object will be created. An implementation with a static constructor is easier to handle and also much clearer.

public sealed class Singleton
{
    //single instance
    private static Singleton instance;

    //private constructor
    private Singleton() { }

    static Singleton()
    {
        //custom code
        instance = new Singleton();
    }

    public static Singleton Instance
    {
        get
        {
            return instance;
        }
    }
}


In this sample a static constructor is added which initializes the instance of the Singleton class. It will only be called one time, before one of the static methods of the class are called. So the Instance method doesn’t have to do this anymore. This results in a much cleaner code, a singleton with no lock or if statement! But also in other cases, when you have static fields in your class, it helps you to avoid the lock and the if statements.

Run console application from a .net application

The base class library of the .NET framework doesn’t provide a mechanism to execute a console application or something in the command prompt out of the box. The execution of a tool which only has textual output isn’t a challenge at all, but if want to interact with it (read the output and react on it) it becomes more complicated.

Technical Basics

With the Process class you can start any application. The ProcessStartInfo gives you the ability to configure it more deeply. UseShellExecute of the ProcessStartInfo class must be set to true if you want to redirect the standard input, output and errors. So internally it uses the operating system shell to start the process. When the properties RedirectStandardInput, RedirectStandardOutput and RedirectStandardError are set to false, you can use the Process class to get a initialized StreamWriter from the StandardInput property and a initialized StreamReader from the StandardOutput and the StandardError property. The writer and readers allow you to interact with the console application. The CreateNoWindow defines that no window should be created for the called application. When you run your application and UseShellExecute is set to true, also no window will be created.

Command Prompt

The command prompt or cmd is a command line interpreter which allows you to execute and interact with applications that have a textual user interface or no interface (only arguments which are passed in at startup).

public static string RunCmd(params string[] commands)
{
    string returnvalue = string.Empty;

    ProcessStartInfo info = new ProcessStartInfo("cmd");
    info.UseShellExecute = false; 
    info.RedirectStandardInput = true;
    info.RedirectStandardOutput = true;
    info.CreateNoWindow = true;

    using (Process process = Process.Start(info))
    {
        StreamWriter sw = process.StandardInput;
        StreamReader sr = process.StandardOutput;

        foreach (string command in commands)
        {
            sw.WriteLine(command);
        }

        sw.Close();
        returnvalue = sr.ReadToEnd();
    }

    return returnvalue;
}

When you call RunCmd(…), you can pass in multiple commands and you will receive the result which is normally shown in the command prompt. You can’t interact with the command prompt multiple times in the same process, like write command, receive result, write command and so on. The StreamWriter must be closed, without that, the StreamReader will not return any result. If you have to react to the output of a command, you have to call the method multiple times with your commands. The following sample calls nslookup two times. The return value is also shown below.

RunCmd("nslookup www.google.com", "nslookup www.microsoft.com");
Microsoft Windows [Version 6.1.7600]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.

C:\Sample\bin\Debug>nslookup www.google.com
Server: xxx.sample.com
Address: 200.001.001.161

Name: www.l.google.com
Addresses: 74.125.43.99
74.125.43.103
74.125.43.104
74.125.43.105
74.125.43.106
74.125.43.147
Aliases: www.google.com


C:\Sample\bin\Debug>nslookup www.microsoft.com
Server: xxx.sample.com
Address: 200.001.001.161

Name: lb1.www.ms.akadns.net
Addresses: 64.4.31.252
207.46.19.190
207.46.19.254
Aliases: www.microsoft.com
toggle.www.ms.akadns.net
g.www.ms.akadns.net

C:\Sample\bin\Debug>

Console Applications

You can also execute console applications without using command prompt. It allows you to get only the return message from the application without the crap you receive from the command prompt. The sample shows a implementation for console applications which only has startup parameters.

public static string Run(string fileName, string args)
{
    string returnvalue = string.Empty;

    ProcessStartInfo info = new ProcessStartInfo(fileName);
    info.UseShellExecute = false; 
    info.Arguments = args;
    info.RedirectStandardInput = true;
    info.RedirectStandardOutput = true;
    info.CreateNoWindow = true;

    using (Process process = Process.Start(info))
    {
        StreamReader sr = process.StandardOutput;
        returnvalue = sr.ReadToEnd();
    }

    return returnvalue; 
}


CommandLine helper class (2.71 kb)
CommandLine sample solution (24.42 kb)