Posts Tagged ‘dotNet’

Serialization in .Net 3.5 SP1

Saturday, November 22nd, 2008

In .Net 3.5 SP1 it is now possible to serialize any object that has a default constructor without decorating it with [DataContract] or [Serializable].

Developers have these choices now when serializing objects:

  • Implicit serialization – requires public default constructor and only serialize public read/write fields
  • Use the [Serializable] attribute
  • Use [DataContract] and [DataMember] attributes
  • Implement the ISerializable interface

I must say, that I’m not keen on this new feature. I prefer explicit serialization to implicit serialization. I predict that implicit serialization of entire object graphs will cause performance problems for many .Net developers in the years to come. This could also be a good thing as I am a consultant  ;-)

Aaron Skonnard has a more detailed blog post about the new serialization features in .Net 3.5 SP1.

.Net debugger visualizers

Sunday, October 12th, 2008

The .Net framework 2.0 gave some great tools for debugging – they are a great help when writing code.

Some of these features are the DebuggerDisplay and DebuggerStepThrough attributes. I seldom use any of them, as I prefer to just overriding the ToString method instead of using the DebuggerDisplay attribute. This makes it easy to instrument the code too, as I can reuse the ToString method implementation for tracing.

Another feature is the ability to develop custom debugger visualizers. They enable smart developers to build their own. I find some really useful, especially the WCF visualizer. But there a many – check out this list of custom .Net debugger visualizers.

These small enhancements make it so easy to get an overview of the current state, instead of inspecting properties.

Microsoft releasing the .Net framework source code

Thursday, October 4th, 2007

But only for sneak peaking.

Read more on Scott Guthrie’s blog.

Constrained-based assert model

Tuesday, June 12th, 2007

The latest version of NUnit Framework (version 2.4 and forward) comes with a new constrained-based assert model, which allows you to write complex assertions relatively easy with a new syntax. The old classical syntax for assertions with static methods still works and according to the NUnit blog there are no plans to deprecate the classical assertion syntax.

Assert.AreEqual(5, 5.0);

Assert.AreSame(person, person);

Assert.Greater(7, 5);

Assert.IsInstanceOfType(typeof(ArrayList), new ArrayList());

Assert.IsAssignableFrom(typeof(ICollection), new List());

StringAssert.StartsWith("Anders", "And");

CollectionAssert.AreEquivalent(col1, col2);

FileAssert.AreEqual(stream1, stream2);

The new constrained-based assert model uses a single method on the Assert class for all assertions:

Assert.That("Anders", new EqualConstraint("Anders"));

The second parameter is the type of assertions – here an equal constraint that works on all types of data – primitives, collections, streams etc.

NUnit comes with a number of constraints covering most scenarios, but also allows you to extend the model by developing custom constraint by realizing the IConstraint interface.

public interface IConstraint
{
    bool Matches(object actual);
    void WriteMessageTo(MessageWriter writer);
    void WriteDescriptionTo(MessageWriter writer);
    void WriteActualValueTo(MessageWriter writer);
}

If the syntax of constrained-based assert model seams a bit to complex and not very reader friendly, the NUnit team has implemented a range of syntax helper classes like so:

Assert.That("Anders", Is.EqualTo("Anders"));
Assert.That("Anders", Is.Not.EqualTo("Anja"));
Assert.That("Hello World!", Text.StartsWith("HELLO").IgnoreCase);
Assert.That("make me happy", Text.Contains("make"));

Assert.That(person, Is.SameAs(person));
Assert.That(null, Is.Null);
Assert.That(new object(), Is.Not.Null);
Assert.That("", Is.Empty);

Assert.That(new ArrayList(), Is.Empty);
Assert.That(myCol, Is.Unique);

Assert.That(7, Is.GreaterThan(5));
Assert.That(2.0d + 2.0d, Is.EqualTo(4.0d).Within(.000005d));

Assert.That(myPerson, Is.InstanceOfType(typeof(Person)));
Assert.That(new EqualConstraint(), Is.AssignableFrom(typeof(IConstraint)));

Assert.That(new int[] { 4, 5, 6 }, Is.All.GreaterThan(0));
Assert.That(new string[] { "abc", "bac", "cab" }, Has.All.Length(3));
Assert.That(new int[] { 4, 5 }, Is.SubsetOf(new int[] { 4, 5, 6 }));

The change of syntax separates NUnit from other unit test frameworks and therefore separates from the common approach of creating unit tests.

I like the new syntax – It is intuitive and easy to comprehend. All change is not, but it is simple rules of evolution. The notion of constraints is also found in NMock.

Strings in .Net

Wednesday, April 11th, 2007

Strings in .Net are immutable reference types, but can be confusing because they sometimes have similar characteristics as value types.

Below is a code sample that shows the value type characteristics of string.

string s1 = "Anders";
string s2 = "Anders";

Console.WriteLine("s1 and s2 are equal : {0}", s1 == s2);

Output:
s1 and s2 are equal : True

For regular reference types this would have been an object reference compare, but the == operator is overloaded to execute the same logic as the String.Equals method.

Continuing the example by implicit cast each string to an object:

object o1 = s1;
object o2 = s2;

Console.WriteLine("o1 and o2 are equal : {0}", o1 == o2);

Output:
o1 and o2 are equal : True

These two strings are equal due to the CLR optimization called interning. Interning works by having an internal pool of unique literal strings. If the same literal string is assigned to multiple variables the runtime retrieves the reference to the literal string in the internal pool and assigns it to each variable.

Console.WriteLine("s1 and s2 are same : {0}", object.ReferenceEquals(s1, s2));
Console.WriteLine("o1 and o2 are same : {0}", object.ReferenceEquals(o1, o2));

Output:
s1 and s2 are same : True
o1 and o2 are same : True

The Object.ReferenceEquals determines whether the specified object instances are the same instance.

When comparing the strings or objects all of them are the same instance! This is again due to interning. All of the variables reference to the same object.

Let us rewrite the code and try something a little bit different:

string s1 = "Anders";
string s2 = new StringBuilder("Anders").ToString();

object o1 = s1;
object o2 = s2;

Console.WriteLine("s1 and s2 are equal : {0}", s1 == s2);
Console.WriteLine("o1 and o2 are equal : {0}", o1 == o2);
Console.WriteLine("s1 and s2 are same : {0}", object.ReferenceEquals(s1, s2));
Console.WriteLine("o1 and o2 are same : {0}", object.ReferenceEquals(o1, o2));

Output:
s1 and s2 are equal : True
o1 and o2 are equal : False
s1 and s2 are same : False
o1 and o2 are same : False

The above code is almost identical to the previous code except that s2 is initialized with a StringBuilder. Will this return the same result? No, because interning only occur when an assembly gets loaded or the String.Intern method is called.

The first string compare is true because of the operator overloading discussed earlier, but all the other compares are false. Even the o1 and o2 compare, because the runtime is unaware of the object types at the time of the comparison and can therefore not use the overload operator.

If you want to know more about strings, interning or internationalization issues with strings – read on.

Garbage Collection Flavors

Tuesday, April 3rd, 2007

Why should you care about Garbage Collection? Well, it may very well improve performance for your applications.

The .Net framework garbage collector can operate in different modes depending on platform and requirements. There are three modes available for .Net framework version 2.0 and 3.0. Each of these modes is tailored for specific situations.

Concurrent Workstation Garbage Collection

This mode is optimized for interactivity by frequent short garbage collects. Each collect is split up into smaller pieces and are interleaved with the managed applications threads. This improves responsiveness at the cost of CPU cycles. This is ideal for interactive desktop applications where freezing application is an annoyance for the users and ideal CPU time is abundant when waiting for user input. Concurrent workstation mode improves the usability with perceived performance.

Note that interactive GC only applies for Gen2 (full heap) collects because Gen0 and Gen1 collects are in nature very fast.

Non-concurrent Workstation Garbage Collection

Non-concurrent workstation mode works by suspending managed application threads when a GC is initiated. It provides better throughput but might appear as application hiccups where everything freezes for the users.

Server Garbage Collection

In server mode a managed heap and a dedicated garbage collector thread is created for each CPU. This means the each CPU allocates memory in its own heap therefore results in lock-free allocation. When a collect is initiated all the managed application threads are suspended and all the GC threads collect in parallel.
Another thing to note is that the size of the managed heap segments is larger in server mode than workstation mode. A segment is the unit of which the memory is allocated on the managed heap.

It is possible to choose the type of GC for a managed application in the configuration file. Under the <Runtime> element add one of the below three settings and depending on the number of CPU, the garbage collector will run in the configured mode.Garbage Collection type settings

Running a standalone managed application the GC mode is by default concurrent workstation. Managed application hosts like ASP.Net and SQLCLR run with Server GC by default.

If you want to know more about how the GC works, read the blog entries “Using GC Efficiently”
by Maoni.

Great conference

Wednesday, March 14th, 2007

The Miracle SQL Server Open World conference was a great success. There were lots of informative sessions and great networking. I spoke to a lot of interesting people from all over the world including Microsoft SQL Server guys from Redmond and one as far away as from Brisbane, Australia. Bear in mind that this conference is held in the countryside, far away from anything, two hours drive from Copenhagen, Denmark.

I promised the attendances’ at my session “Transactions with Windows Communication Foundation” to post a guide to setup the Distributed Transaction Coordinator (DTC) for WCF. I have posted two guides:

Hope to see all of these interesting people again at next year’s Miracle SQL Server Open World conference.

Configuring the DTC for WCF with WS-AtomicTransaction

Monday, March 12th, 2007

If interoperability with other platforms is a requirement WS-Atomic Transaction must be used. It requires all the steps for DTC setup in previous blog entry Configuring the DTC for WCF for OleTx, but also a couple of additional ones.

If running Windows XP or Windows Server 2003 a hotfix is required as detailed in the .Net framework 3.0 release notes. The hotfix can be downloaded from here.

WS-Atomic Transaction requires a certificate to establishing Mutual Trust between the parties in a transaction. If a certificate issued by a trusted 3rd party is not available, it is possible to issue one for test purposes by running the below statement in the Visual Studio 2005 Command Prompt. It generates and installs a certificate in the LocalMachine\MY store.

MakeCert -sr LocalMachine -pe -n “CN=mytestcertificate.com” -ss My -sky exchange -sp “Microsoft RSA SChannel Cryptographic Provider” -sy 12

To enable a graphical interface for the WS-AtomicTransaction Configuration Utility (wsatConfig.exe) register the WsatUI.dll by running the following command in the Visual Studio 2005 Command Prompt

regasm /codebase %PROGRAMFILES%\Microsoft SDKs\Windows\v6.0\Bin\WsatUI.dll

Now open the DTC configuration again by the following steps:

  • Administrative Tools | Component Services | Computer | My Computer.
  • Right-click on My Computer and chose Properties – notice a WS-AT tab is now available
    – select it.
  • Check Enable WS-Atomic Transaction network support
  • Select the certificate under Endpoint certificate

WS-AtomicTrnasaction configuration

Now everything is ready to make use of WS-Atomic Transaction in WCF as long as the client and service are on the same machine.

If the client and service are located on different machines, each machine needs a certificate and any machine participating in a transaction must be explicitly authorized by establishing trust with the counterpart’s certificate.

Establishing trust and authorizing trust. These steps have to be performed on all parties.

  • Export the public key
  • Add the public key certificate to the counterpart’s LocalMachine\MY and LocalMachine\ROOT
    stores.
  • Authorize the counterpart’s certificate in the WS-AT tab.

It seems like a daunting task, but it is worth it. I can’t figure out how I ever got by with old-style ASMX web services without transactional support.

Configuring the DTC for WCF with OleTx

Monday, March 12th, 2007

When a transaction propagates from one process to another, the DTC (Distributed Transaction Manager) must be utilized, because to two or more independent parties are involved in the transaction.

Beforehand the WCF service must be prepared:

  • Decorate the service contract (interface) with the attribute TransactionFlow and specify
    if it is mandatory or allowed.
  • Specify on the service type (implementation) OperationBehavior attribute that a TransactionScope
    is required.
  • Enable transaction propagation on the binding via the transactionFlow element in the
    configuration file for both service and client.

If the service and client are ready and an attempt to propagate a transaction is executed the following TransactionManagerCommunicationException is thrown:

System.Transactions.TransactionManagerCommunicationException was unhandled by user code Message=”Network access for Distributed Transaction Manager (MSDTC) has been disabled. Please enable DTC for network access in the security configuration for MSDTC using the Component Services Administrative tool.”

That is because the DTC does not allow inbound of outbound network transactions, by default.

Configure the client DTC to allow outbound network transactions and the service DTC to have inbound network transactions. If both client and service are running on same machine, enable both inbound and outbound network transactions.

To enable inbound or outbound network transaction navigate to

  • Administrative Tools | Component Services | Computer | My Computer.
  • Right-click on My Computer and chose Properties | MSDTC tab | Security Configuration.
  • Check Network DTC Access and under Transaction Communication Manager check Allow Inbound, Allow Outbound or both.

Now transaction propagation via OLE Transactions (OleTx) is possible. These are all the bindings that operate in a homogeneous Windows environment.

Favor structured exception handling

Wednesday, February 21st, 2007

I was surprised this last week, when a discussion about error handling, whether or not to use structured exceptions in .Net, surfaced at a customer where I am helping them to complete a project. I will not name the company, but it is a Danish division of a large American IT corporation with around 80.000 employees.

The discussion was between one of their architects, a couple of others and me. The company where accustomed to used return codes and the architect argued in favor of return codes. I didn’t think in this day and age that organizations still use return codes with languages that have build-in support for structured exception handling.

An exception is an event that occurs during the execution of a program, designed to handle the occurrence of some exceptional condition which changes the normal flow of execution. Exceptions travel out of band and propagate through the call stack until an exception handler catches the exception. Structured exceptions use the Try…Catch…Finally syntax.
Below is a make believe example of a simple system calling two methods:

static void Main(string[] args)
{
  Order myOrder = new Order();
  decimal yield;

  try
  {
    yield = CalculateYield(myOrder);
    UpdateStatus(myOrder);
  }
  catch (Exception ex)
  {
  //** Exception handling **//
  }
}

public static decimal CalculateYield(Order order)
{
  // calculate yield
  return decimal.MaxValue;
}

public static void UpdateStatus(Order order)
{
  // update status
}

If an exception is thrown in the method CalculateYield the flow is short-circuited and the method UpdateStatus is never called. With return codes the developer has to manually check if the method failed and manually propagate the return code up the stack.

Return codes imposes on method signature by requiring the return type to be a return code and potentially use a parameter as return type. This clutters the method signature and does not make the method functionality apparent. Notice the confusing method signature of CalculateYield in the following code:

static void Main(string[] args)
{
  Order myOrder = new Order();
  decimal yield = 0;
  int returnCode = 0;

  returnCode = CalculateYield(myOrder, yield);

  if (returnCode < = 0)
  {
    returnCode = UpdateStatus(myOrder);
  }
  else
  {
    //** Error handling **//
  }

  if (returnCode > 0)
  {
    //** Error handling **//
  }
}

public static int CalculateYield(Order order, decimal yield)
{
  // calculate yield
  return -1; // return code
}

public static int UpdateStatus(Order order)
{
  // update status
  return 0; // return code
}

Return codes are inferior to exceptions. Exceptions are instances of a class and can therefore carry detailed information – not like integer return codes! It is non-reputable that return codes are no good.

The return code advocate might bring up an issue like performance due to the fact that throwing an exception results in a stack walk to create the stack trace.

When to throw exceptions?

Do not throw exceptions in the normal flow of execution. If it is expected that an action might fail like a login, use the Tester-Doer Pattern (e.g. Collection.Contains) or Try-Parse Pattern (e.g. Double.TryParse).

When to catch exceptions?

Catch only an exception if detailed information about the exception can be added, the exception is handled or some sort of compensation action is required. If the flow of execution can not continue, rethrow the exception so an exception can be handled further up the stack, e.g. inform the user.

catch (ArgumentException ex)
{
  // some clean up or logging
  throw ex;
}

When rethrowing exceptions, it is important to do it the right way. By using the above pattern regarding throwing and not throwing ex, the stack walk is not performed twice, making the rethrow virtually free.

If you want to know more read the book Framework Design Guidelines. It is recommended and easily read. You can also look at the blog entry Exception Throwing by Krzysztof Cwalina – one of the authors of the Framework Design Guidelines book. There is also a small summery at Design Guidelines for Exceptions on MSDN.

On a side note: the company mentioned was as one of the first I Denmark to adopt the .Net framework – in 2000 where beta 1 was released they build their first project on the .Net framework. Go figure!