Tag Archives: C# .Net

Technology brotherhoods


I often hear people talking about which technology is better between C / C++ / C# .Net / java. Most of the time, it’s more a political/brotherhood/community thing (like football, even thought frenchies like me aren’t so proud of their team now) than a technical talk.
I find it absurd. Computer science is about efficiency and making more money. You can take into account the pleasure you have to work on a technology (as you will be more likely to be more efficient with it), but it should still remain about efficiency.

The following video is about java & C# .Net. I’ve done quite a lot of C# .Net, Java and C, and some ObjectiveC (while developing iPhone applications) and a little bit of C++. The only thing I feel is that Sun with java had the good ideas, Microsoft with .Net took them and finished the work. Still, I often code in java, mostly for the TC65 chip, it’s quite comfortable. But for instance, it was longer to implement the M2MP protocol on the TC65 chip than the C# .net server. Mostly because of the unsigned types I had to “emulate” and the lack of generics (which are not available on the TC65’s JVM).

By the way, I’m running .Net apps on Linux everyday using Mono.

Here is the best example of what I’m talking about :

For all these lame people who don’t have an HTML5 compatible browser, you can go to the original video. The reason I downloaded it here in my blog is that you are forced to register to YouTube to watch it.

Recycling .net objects to improve performances

C# .Net allocation and freeing system is quite efficient but when you need to create a huge number of objects, it’s just not fast enough. So what you can do is try to recycle each object to avoid to recreate them. You will then just need to set their property.

In my tests, this class reduced the allocation time from 12 to 15 times:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public sealed class Heap<T> where T:class, new() {
	private readonly Stack<T> _stack = new Stack<T>();
 
	private int _count;
 
	public T Allocate() {
                if ( _count == 0 ) {
                   return new T();
                } else {
                  --_count;
                  return _stack.Pop();
                }
	}
 
	public void Free( T obj ) {
		++_count;
		_stack.Push( obj );
	}
}

You might think that this process is really painful as you have to manually free every single objects you use. But in fact you just have to recycle most of the objects. If you forget some, that’s not really important (they will just get garbage collected).

Google PowerMeter and sample C# .Net API usage

Update 2001-06-25
A lot of people still contact me about this project. I received this mail today, just in case you’re getting interested by the project, you should know that it will die pretty soon:

Dear PowerMeter User,

We first launched Google PowerMeter as a Google.org project to raise awareness about the importance of giving people access to their energy information. Since our launch, there’s been more attention brought to this issue, and we’re excited that PowerMeter has helped demonstrate the importance of access to energy data. However, our efforts have not scaled as quickly as we would have liked, so we have decided to retire PowerMeter.

You will continue to have access to the product until September 16, 2011, after which time you will no longer be able to access your PowerMeter account. We know that having access to your energy information has helped you save energy and money. There are many options available for you from our device and utility partners. Please visit this page to learn more: http://www.google.com/support/powermeter/bin/answer.py?hl=en&answer=1342532

We also understand that having your historical energy data is important to you. We’ve made it easy for you to download your data. To export your PowerMeter data to a CSV (Comma Separated Values) file, log in to your account and go to “Account Settings.” More information can be found here: http://www.google.com/support/powermeter/bin/answer.py?hl=en&answer=164264

We appreciate your understanding and hope that you’ve enjoyed using Google PowerMeter. If you have questions about this announcement, please visit our FAQ pages at http://www.google.com/powermeter/about/faqs.html

Thank you,
Google PowerMeter team

© 2011 Google Inc. 1600 Amphitheatre Parkway, Mountain View, CA 94043

You’ve received this mandatory service announcement email to update you about important changes to your Google PowerMeter account.

Google PowerMeter offers you to collect your home’s / enterprise’s / specific equipment’s power usage and have some basic analysis on it.

There’s also a Google PowerMeter API so that everyone can build devices able to report their consumption and applications.

I would say one cheap and evolutive way to implement this API would be to use a Z-Wave power meter and have a Z-Wave central controller sent the data to Google servers. It could quickly get interesting because this could make you know the exact consumption of all your lights by calculating the result of the light-on/light-off order on individual lights. And this could even lead to define some max energy consumption scenarios so that you don’t allow more than X watts for all the lights of your house (this is just a idea, I would never put this in my home).

I know this isn’t the next BIG thing. Because everyone knows it’s all about the social right-now. But still, I think this could be the most green project of all time. Because it clearly shows people (or enterprises) how they consume energy and gives the useful analysis to find solutions. And for once it doesn’t try to make you feel guilty about not being green enough, it just brings facts.

By the way, you can have a negative energy consumption (power meter counting backward) in Google PowerMeter. I don’t think this is a bug, it must be for people selling their energy for their solar or wind energy producer equipments. But unfortunately you set the estimated cost of energy but you can’t set its estimated revenue price.

Sample API call

Here is a sample Google PowerMeter API call in C# .Net :
I just changed a little bit of the authentication parameters so that you can’t actually upload data on my account.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
using System;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;
 
/* Equipment was activated with this URL :
 * https://www.google.com/powermeter/device/activate?mfg=WebIngenia&model=TestEquipment1&did=100102030405&cvars=1&dvars=0&rurl=http://test.webingenia.com/powerMeter&snonce=123
 *
 * The resulting request was (available here : http://test.webingenia.com/read/powerMeter#id2473 ) :
 * $_POST = array(
 *		[snonce] => 123
 *		[hash] => _____6c2562aeb7bab4e24afc7beeb18c701c04ba,____8c9f62fa8a137eba7fa35b5f58802fca2e56,____f4db13304c49d36fb81b20cabbe147f8ce34
 *		[token] => ________FhCtzebg_P____8BGMWjtUs
 *		[path] => /user/____4578579014915368/____4578579014915368/variable/WebIngenia.TestEquipment1.100102030405
 * )
 *
 */
 
namespace test {
	class Program {
 
		private static readonly Random _random = new Random();
 
		public const String DeviceHash = // Useless
			"____bf8262aeb7bab4e24afc7beeb18c701c04ba,____8c9f62fa8a137eba7fa35b5f58802fca2e56,____f4db13304c49d36fb81b20cabbe147f8ce34";
 
		public const String DeviceToken = // Needed for authentication
			"________FhCtzebg_P____8BGMWjtUs";
 
		public const String DevicePath = // URL of the device
			"/user/____4578579014915368/_____4578579014915368/variable/WebIngenia.TestEquipment1.100102030405";
 
		public const String DeviceVar = "c1";
 
		public const String FeedUrl = // URL of the Google PowerMeter API
			"https://www.google.com/powermeter/feeds";
 
		public const String EventUrl = // URL where to send the data
			FeedUrl + "/event";
 
		public const int Period = 5000; // 5 to 10 seconds
 
 
		static double MeterValue {
			get {
				return Settings.Default.MeterValue;
			}
			set {
				Settings.Default.MeterValue = value;
				Settings.Default.Save();
			}
		}
 
		static void Send() {
 
			// We increment the counter (by 0 to 1 kWh)
			MeterValue += _random.NextDouble();
 
			Console.WriteLine( "MeterValue : {0}", MeterValue );
 
			// This is what we are going to send
			var strContent = String.Format(
			@"
<feed xmlns=""http://www.w3.org/2005/Atom"" xmlns:meter=""http://schemas.google.com/meter/2008"">
	<entry>
      <category scheme=""http://schemas.google.com/g/2005#kind"" term=""http://schemas.google.com/meter/2008#instMeasurement"" />
      <meter:subject>{0}</meter:subject>
      <meter:occurTime meter:uncertainty=""1.0"">{1}</meter:occurTime>
      <meter:quantity meter:uncertainty=""0.001"" meter:unit=""kW h"">{2}</meter:quantity>
    </entry>
</feed>",
				FeedUrl + DevicePath + "." + DeviceVar,						// Device URL
				DateTime.UtcNow.ToString( "yyyy-MM-dd'T'HH:mm:ss.fffK" ),	// Current UTC date
				MeterValue.ToString( CultureInfo.InvariantCulture )			// Meter value
			);
 
			// We convert it into raw content
			var content = Encoding.UTF8.GetBytes( strContent );
 
			// We create the POST request
			var req = WebRequest.Create( EventUrl );
			req.Headers.Add( "Authorization", "AuthSub token=\"" + DeviceToken + "\"" );
			req.Method = "POST";
			req.ContentLength = content.Length;
			req.ContentType = "application/atom+xml";
 
			try {
				// Opening the request stream means starting the request
				Console.Write( "Requesting..." );
				using ( var requestStream = req.GetRequestStream() ) {
 
					// We send the content
					requestStream.Write( content, 0, content.Length );
 
					// And we end the request by getting the response
					using ( var streamReader = new StreamReader( req.GetResponse().GetResponseStream() ) ) {
						Console.WriteLine( "Result : " + streamReader.ReadToEnd() );
					}
				}
			}
			catch ( WebException e ) { // If a webException occurs (should be 400)
				// We display the error
				var response = e.Response as HttpWebResponse;
				if ( response == null ) // This is not the exception that we want
					throw;
				using ( response ) {
					using ( var responseStream = response.GetResponseStream() ) {
						Console.WriteLine(
							"Error {0} : {1} ",
							response.StatusCode,
							new StreamReader( responseStream ).ReadToEnd()
						);
					}
				}
			}
		}
 
		static void Main() {
			while ( true ) {
				try {
					Send();
				}
				catch ( Exception ex ) {
					Console.WriteLine( "Exception : " + ex );
				}
				Thread.Sleep( Period + _random.Next( Period ) );
			}
		}
 
		// This code was generated by Visual Studio (but I prefer to put it here rather than having to publish the VS project)
		#region Auto-generated
		[System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
		[System.CodeDom.Compiler.GeneratedCodeAttribute( "Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "9.0.0.0" )]
		internal sealed class Settings:System.Configuration.ApplicationSettingsBase {
 
			private static Settings defaultInstance = ( (Settings) ( Synchronized( new Settings() ) ) );
 
			public static Settings Default {
				get {
					return defaultInstance;
				}
			}
 
			[System.Configuration.UserScopedSettingAttribute()]
			[System.Diagnostics.DebuggerNonUserCodeAttribute()]
			[System.Configuration.DefaultSettingValueAttribute( "3000" )]
			public double MeterValue {
				get {
					return ( (double) ( this[ "MeterValue" ] ) );
				}
				set {
					this[ "MeterValue" ] = value;
				}
			}
		}
		#endregion
	}
}

I didn’t let it running too much time but still you can see that it works :

Stupid C++ vs C# performance comparison

I found out that there is real test than the little one i did here. In fact the main interest of the post is this spreadsheet :

I recently did a simple and stupid comparison test between C++ (g++) and C# .Net (mono).

My point here is that C# can actually be considered as a very fast language. It allows automatic hardware-specific optimization. The only real drawback you have in the .Net framework is the garbage collector. It prevents the C# .Net it from being a realtime language/framework. But does it really matter for you ?

The purpose of the following test is to show that C++ isn’t faster than C# “as is”. I KNOW C# can not be faster than C++ because C# can do few hardware specific optimizations when you can do all of them in C++, because all the systems calls have to be done in C/C++ and because there’s no such thing like Template and forced inlining in C#.

But if you’re searching for arguments to choose C# .Net over native C++, you should also consider these :

SO ! Here is the test…

I wrote these two sample programs :

One in C++ :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
using namespace std;
 
long stupidThing( long nb ) {
	long out = 1;
	while( nb > 0 )
		out *= nb--;
 
 
	return out;
}
 
int main() {
 
	long total = 0;
 
	for( int i = 0; i < 1000000; ++i )
		for( long l = 0; l < 100; ++l )
			total += stupidThing( l );
 
	cout << "Total : " << total << endl;
 
	return 0;
}

One in C# :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
using System;
 
namespace test {
        class Program {
                static long stupidThing( long nb ) {
                        long ret = 1;
                        while ( nb > 0 )
                                ret *= nb--;
                        return ret;
                }
 
                static void Main( string[] args ) {
 
                        long total = 0;
 
                        for ( int i = 0; i < 1000000; ++i )
                                for ( long l = 0; l < 100; ++l )
                                        total += stupidThing( l );
                        Console.WriteLine( "Total : {0}", total );
                }
        }
}

First of all, I open a shell in real-time priority, because I don’t want my other processses to mess with my tests :

1
# rtprio 99 bash

Then I compile the two programs :

1
2
# gmcs test.cs
# g++ -O4 test.cpp -o test

And then I launch my test :

On a 64 bits host :

1
Kernel : 2.6.9-023stab051.3-smp #1 SMP Wed Nov 4 18:36:34 MSK 2009 x86_64 x86_64 x86_64 GNU/Linux
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# time ./test ; time ./test ; time ./test ; time mono test.exe ; time mono test.exe ; time mono test.exe
Total : -6192109806162068864
 
real    0m12.433s
user    0m12.394s
sys     0m0.049s
Total : -6192109806162068864
 
real    0m12.415s
user    0m12.411s
sys     0m0.014s
Total : -6192109806162068864
 
real    0m12.430s
user    0m12.411s
sys     0m0.026s
Total : -6192109806162068864
 
real    0m10.311s
user    0m10.287s
sys     0m0.029s
Total : -6192109806162068864
 
real    0m10.254s
user    0m10.247s
sys     0m0.011s
Total : -6192109806162068864
 
real    0m10.250s
user    0m10.255s
sys     0m0.012s

C# clearly beats C++ here. Well

On a 32 bits host :

1
Kernel : 2.6.30-2-686 #1 SMP Fri Dec 4 00:53:20 UTC 2009 i686 GNU/Linux
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# time ./test ; time ./test ; time ./test ; time mono test.exe ; time mono test.exe ; time mono test.exe
Total : 100461056
 
real    1m10.927s
user    1m7.376s
sys     0m0.056s
Total : 100461056
 
real    1m12.590s
user    1m8.976s
sys     0m0.020s
Total : 100461056
 
real    1m13.279s
user    1m9.532s
sys     0m0.056s
Total : -6192109806162068864
 
real    2m22.492s
user    2m15.260s
sys     0m0.136s
Total : -6192109806162068864
 
real    2m23.002s
user    2m15.760s
sys     0m0.104s
Total : -6192109806162068864
 
real    2m25.102s
user    2m17.709s
sys     0m0.144s

C++ beats C# here, but in 32 bits C++ use other types whereas C# use the same. In C# long is always 64 bits, in C++ it can be 64 bits or 32 bits (depending on the current architecture).

D language

This is just a very short post about this language I recently discovered : the D language. As described on its little website : “D is a systems programming language. Its focus is on combining the power and high performance of C and C++ with the programmer productivity of modern languages like Ruby and Python. Special attention is given to the needs of quality assurance, documentation, management, portability and reliability.”.

It has most of the features of the java and the C# (best language ever), but it is fully compiled (no JVM or JIT stuff).

You should have a quick loot of its features on the Digital mars website (they’re the ones who created it).

I wonder if this language really has a future. C# (with the .Net framework) compiles and runs on every platform (thanks to mono), even on the iPhone, so it only remove the burden of the libraries required to run .net apps.
So, will it really beats its performance ? Because in C# is very fast (my next post will bring a stupid C++/C# performance comparison), and in C# avoiding time or memory consuming mistakes or multi-threading our code is very easy.

SPSecurity.RunWithElevatedPrivileges

If like me you’re wondering what exactly does SPSecurity.RunWithElevatedPrivileges, this is what I understand of it :

1
2
3
4
5
SPSecurity.RunWithElevatedPrivileges( () => {
    using( var newSite = new SPSite( site.Url ) ) {
        // your stuff
    }
});

Is equivalent to :

1
2
3
using( var newSite = new SPSite( site.Url, site.SystemAccount.Token ) ) {
    // your stuff
}

So if this is just to open an elevated privilege SPSite, it will be equivalent. But if you do some more complex things, as soon as you load a new SPSite it will open it with the original UserToken. And you lose…

C# .Net : How works automatic assembly versioning

When you choose to automatically generate a new version of your assembly at compilation, you have to set in the AssemblyInfo.cs file, this line :

1
2
3
4
5
6
7
8
9
10
// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version 
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Build and Revision Numbers 
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.*")]

But what do these automatically generated numbers mean ? Well, chances are you don’t care. But one day after using this features for years I decided that I would.

  • The build number is the number of days since 01/01/2000
  • The revision number if the number of 2 seconds periods since 00:00 of this day

So… To get the compilation date of an assembly from its version, you would have to do :

1
2
var version = Assembly.GetExecutingAssembly().GetName().Version;
var date = new DateTime( 2000, 01, 01 ).AddDays( version.Build ).AddSeconds( version.Revision * 2 );

This feature is great if your need some atomic versionning of a particular library for instance. Each program using your library has its own version and you don’t risk to break working feature in future release of your library. And if you want to force the use of a newer version of a library within a particular application, you can use some assembly redirection.
But you should also note that if you deploy your assembly in the GAC (like it’s required to do with Sharepoint), you will have tons of “garbage” versions of your assembly. And there’s not “easy fix” for that.

Loading plugins assemblies in .Net

(first post of the year)

This might seem like a quite complex thing to do, but it’s in fact very simple. Thank you .Net for being so well built.

Note : With .Net 3.5, there is a much more advanced method called Add-In. But it’s also much more complex. You should use it on long-term projects with some evolutions of the plugins API (and no possibility to change the plugins). I’ve used it for a project and that really made us lose a lot of time.

So here is the code for a simple plugins class loading system :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public List<Type> GetPlugins<T>( string folder ) {
	var files = Directory.GetFiles( folder, "*.dll" );
	var tList = new List<Type>();
	foreach ( string file in files ) {
		try {
			var assembly = Assembly.LoadFile( file );
			foreach ( Type type in assembly.GetTypes() ) {
				if ( !type.IsClass || type.IsNotPublic )
					continue;
				var interfaces = type.GetInterfaces();
				if ( ( (IList) interfaces ).Contains( typeof( T ) ) )
					tList.Add( type );
			}
		}
		catch ( Exception ex ) {
			Logger.LogException( ex );
		}
	}
	return tList;
}
 
public List<T> InstanciatePlugins<T>( List<Type> types, object[] args ) where T:class {
	var list = new List<T>();
 
	foreach ( var t in types )
		if ( ( t.GetInterfaces() as IList ).Contains( typeof( T ) ) )
			list.Add( Activator.CreateInstance( t, args ) as T );
 
	return list;
}

Our project can be organized like this :
Project.Project : The application that will load plugins
Project.Common.Plugins : The common types used by the core and the plugins
Project.Plugin.Test1 : One stupid test plugin

In Project.Common.Plugins, we will declare an interface :

1
2
3
4
5
6
namespace Project.Common.Plugins {
	public interface IPlugin {
		String Name { get; }
		void DoSomeStuff();
	}
}

In Project.Plugin.Test1, we will declare a class :

1
2
3
4
5
6
7
8
9
namespace Project.Plugin.Test1 {
	public class PluginTest1 {
		public String Name { get { return "PluginTest1"; } }
		public void DoSomeStuff() {
			for( int i = 0; i < 100; i++ )
				Console.WriteLine("I only count ({0})", i );
		}
	}
}

This assembly has to be generated in a “plugins” directory.

Then, in your project, you will just have to use the methods given in the beginning and do something like that :

1
2
3
4
5
6
var types = GetPlugins<IPlugin>( "plugins" );
var pluginInstances = InstanciatePlugins( types, null );
 
Console.WriteLine("Plugins are :");
foreach( var pi in pluginInstances )
	Console.WriteLine("* {0}", pi.Name );

If you’re worried that you’re stuck with these created objects, you should take a look on the AppDomain (I think I will talk about them pretty soon). This allows to load .Net assemblies and types and then unload them when ever you want. But as it can be easily adapted to some existing code, you should start without it and then add it when you feel your application could benefit from it.

NDepend

Patrick Smacchia gave me a professional license of NDepend v2.12 so that I could write some stuff about it if I liked it. As it was a gift (yes it is), I decided to force myself to look into this software. And after having looked much of its functionalities, I kind of like it. It’s not THE ultimate tool you have to use, but it’s a little bit like the other (resharper, reflector, etc.), it gives you a better insight of what you have in hand.

It’s a little bit like Resharper, it helps you see what you might have done wrong. Except Resharper tells it when you’re editing the code and NDepend helps you make a full review of the code.

Everything in this software goes around the Code Query Language (CQL). I thought this was some sort of commercial concept to sell more but it turns out that we can do a lot of things with it. It seems like a sensible idea, it’s SQL for the code. And the CQL textbox supports for auto-completion makes the CQL writing process pretty easy.

Don’t make it your judgment tool
I guess the most risky think to do would be to give NDepend to dumb people (like code quality reviewers that don’t understand much of what they do). They would end up getting on everybody’s nevers. Because I don’t think that all the code creating query warnings could be changed. I’ve taken the simple stripped down method example of the StreamRipper app :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
private static Boolean ParseArgs( String[] args, Parameters parameters ) {
	try {
		for ( int i = 0; i < args.Length; i++ ) {
			switch ( args[ i ] ) {
				case "--url":
				case "-u":
					parameters.Urls.Add( args[ ++i ] );
					break;
 
				case "--user-agent":
				case "-a":
					parameters.UserAgent = args[ ++i ];
					break;
 
				case "--reconnect-attempts":
				case "-r":
					parameters.MaxReconnectionTries = int.Parse( args[ ++i ] );
					break;
			}
		}
		return true;
	}
	catch ( Exception ) {
		Console.Error.WriteLine( "Arguments error ! " );
		return false;
	}
}

This code will create a cyclomatic complexity warning (as it would in Resharper 5.0 [I should talk about this someday] with the cyclomatic complexity addin). So, for me, it’s clear you have to accept to have a lot of warnings. It’s not like resharper where you can solve all the warnings by accepting every little things he tells you to do (sometimes I’m resharper’s slave but I like it).

BUT, if you really want to make it your judgment call tool, you should really stick to this diagram :

You can see that in this project some of the projets are in the zone of pain and the zone of uselessness. Don’t worry. In the zone of uselessness we have the WCF contracts. It’s quite normal they are totally abstract. And close to the zone of pain, we have low level libraries. So, nothing to worry about.

If you WANT a quick and dirty rule : If your business logic core code is in one of these two red zones, you have a problem.

What I think it does well
I think it gives you a quick view of the software you’re working on : What are the main projects, classes and methods. What quality of work you should expect from it. The graphical view isn’t pretty but it gives you a good simplified view :

And anytime you have a doubt, you just double-click on the method and it opens it in Visual Studio.

You have the dependency graphical view :

It doesn’t look very useful like this. But within Visual NDepend, it displays the parent and child assemblies when you move your mouse over a project :

Evolution of your project
NDepend also saves the results of all previous analysis and allows you to show the evolution of your product. You can see easily what methods have been modified / added / deleted from one analysis to an other. Each analysis you do is saved and can be compared to any other later. This can be done on simple .Net assembly. This will allow you to see what has been changed between two version of an assembly. And with the help of reflector, you can see precisely what has been fixed/improved.

You can see a pretty good example by Patrick Smacchia : Comparison of .Net Bêta 1 and 2 with NDepend.

My thoughts
I think it gives you a quick and simplified view of the organization and size of a project. It’s great .Net tool, I would recommend to any company having big .Net projects. But you shouldn’t spend too much time on trying to comply with all its default CQL query checks as they are a little bit constrictive. If you do, you might want to increase the threshold values. And please take extra care before making judgment calls (it might be tempting).

.Net, Flex and WebORB.Net

I’ve been working on a project where we had to use Flex on a .Net environment and it had to be realtime. I was a little worried at first that it could be tricky to set up. But with WebORB.Net it’s pretty easy. We used the integrated RTMP (Real Time Messaging Protocol) messaging server. It’s almost like using WCF. The most important differences are that, by default, objects are transmitted as Hashtable and calls can’t be synchronous. We can bind the object to right .Net object within the WebOrb management console but we decided to do it ourself using reflection (because we don’t like to depend too much on the management console).

RTMP
The result is pretty impressive as it makes a really powerful real-time management system. And it’s freaking fast. Like WCF, it can handle concurrent calls. It’s in fact easier because everything is asynchronous but still, it does manage that. These calls are received on parallel threads.

The only problem with WebORB.Net is that you don’t have too much examples in the documentation. Our biggest problem was that we didn’t even knew how to detect what was the current calling connection on a method. This is pretty easy but you can’t exactly guess it. This is a dummy sample to show you how it’s done :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
public class FlexConnectionsServer:ApplicationAdapter {
	private int _connectionIdCounter = 0;
	private Dictionary<IConnection,int> _connectionsToId = new Dictionary<IConnection,int>();
 
	// Returns the CURRENT connection (must be used from a method called by the flex client)
	private IConnection CurrentConnection { get { return ConnectionHub.getConnectionLocal(); } }
	private int CurrentID { get { return _connectionsToId[ CurrentConnection ]; } }
 
	// When the RTMP service is loaded, we start the time dispatcher thread
	public override bool appStart( IScope app ) {
		new Thread( Thread_TimeDispatcher ).Start();
	}
 
	// This method is called when a client connects
	public override bool appConnect( IConnection conn, object[] parms ) {
		lock ( _connectionsToId ) {
			_connectionsToId.Add( conn, _connectionIdCounter++ );
		}
 
		return true;
	}
 
	// This method is called when a client disconnects
	public override void appDisconnect( IConnection conn ) {
		lock ( _connectionsToId ) {
			_connectionsToId.Remove( conn );
		}
	}
 
	// This is a sample method call
	public String GetMyName() {
		return String.Format( "Client{0}", CurrentId );
	}
 
	// This thread dispatches the current time to every client
	private void Thread_TimeDispatcher() {
		while( true ) {
			var t = DateTime.UtcNow;
			SendCommand( "CurrentTime", new Object[] { t } );
			Thread.Sleep( 1000 );
		}
	}
 
	// Call a remote method on each client connection
	private void SendCommand( String command, Object[] params ) {
		lock ( _connectionsToId ) {
			foreach( var kvp in _connectionsToId )
				( kvp.Key as IServiceCapableConnection ).Invoke( command, params );
		}
	}
}

It’s a little bit like using WCF in Single instance mode.

IIS 7.0 Setup
There was something really weird that happened with my IIS 7.0 on my Windows 7 x64. Using the RTMP connection, I frequently had null return values on .Net method calls. We firstly find a quick way to solve it : Recall each time we get a null value. It’s really dirty, but It worked as a very temporary solution.
Then, when debugging on the IIS process, I noticed a lot of NullReferenceException exceptions displayed on the debugger console. They were about the WebORB “LicenseManager” class, and I had as much exceptions as I had null values on the Flex client. I tried a lot of things that didn’t do anything. And then, I changed the “Managemd pipeline mode” of the Application Pool from “Integrated” to “Classic”, and the problem was solved. The really weird stuff here is that WebORB recommends to use the “Integrated” mode.

MidnightCoders support
We asked MidnightCoders to send us a community edition license, and they instantly answered. We got our license within the 48 hours after our first mail (I was the one slowing it down).

Quick note on the project
To give you a better view of the project I’m talking about :
GPRS Equipment <--(M2MP protocol)–> [Generic M2M Server] <--(WCF)--> [Business logic software] <--(WCF)--> [Flex connections server] <--(RTMP)--> Flex
We’ve got a little equipment (TC65 based as you can guess) that connects to a generic server using our own (real-time and bandwidth optimized) protocol. A business logic software connects to this server using a WCF service. And then we have the WebORB.Net / IIS that connects to this business logic software.

WCF helps make very interesting .Net applications because it simplifies all the communication but can also create deadlocks you might not have seen. Take this example : You have a lock on the WCF Server on the clients list object, you make a call to the WCF client and this client makes a call to the WCF Server that also requires a lock. If you were doing all this client/server calls on the same process this wouldn’t be a problem. But as you use WCF client-to-server and server-to-client calls are made on differents threads. You create a deadlock (unless you set the OperationContract attribute to IsOneWay and/or you fix the deadlock source).

If you’re doing real-time applications, I would recommend to define all the frequently used methods with the “IsOneWay=true” option.

06/11/2009 Update : I added a sample server-to-client code because some people were interested by it.