A site devoted to discussing techniques that promote quality and ethical practices in software development.

Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Tuesday, May 21, 2013

XmlSerialization - why two runtime behaviour for class with read-only properties?

Following on from the previous blog post, and just to recap, there are at least two ways to write a class with read only property.

The old way is:

    [ Serializable ]
    public class PersonReadOnly {
        String m_Name;
        Int32 m_Age;
        public String Name {
            get{ return m_Name; }
        }
        public Int32 Age { 
            get{ return m_Age; }
        }

        public PersonReadOnly() {
        }

        public PersonReadOnly (String name, Int32 age) {
            this.m_Name = name;
            this.m_Age = age;
        }
    }

and the other way is to use private setter like this:

    [ Serializable ]
    public class PersonReadOnly1 {
        String m_Name;
        Int32 m_Age;

        public String Name {
            get{ return m_Name; }
            private set { m_Name = value; }
        }
        public Int32 Age { 
            get{ return m_Age; }
            private set { m_Age = value; }
        }

        public PersonReadOnly1() {
        }

        public PersonReadOnly1 (String name, Int32 age) {
            this.Name = name;
            this.Age = age;
        }
    }


These two classes functionally are the same. However, the XmlSerializer exhibits very different behaviour depending on how you write the class. This to me seem rather odd.

In the case of PersonReadOnly, there is no runtime exception, except that the state of the class, namely Name and Age, are not serialized as in agreement with the specification. So when the stream is deserialized, the values of Name and Age are that of the null and 0, respectively. Fair enough!

But when one writes the class as in the style promoted in PersonReadOnly1, the runtime behaviour is radically different. XmlSerializer throws the following InvalidOperationException, which is caused by the exception in sgen.exe,
System.InvalidOperationException: Unable to generate a temporary class (result=1).
error CS0200: Property or indexer 'TestSerialization.PersonReadOnly1.Name' cannot be assigned to -- it is read only
error CS0200: Property or indexer 'TestSerialization.PersonReadOnly1.Age' cannot be assigned to -- it is read only

   at System.Xml.Serialization.Compiler.Compile(Assembly parent, String ns, XmlSerializerCompilerParameters xmlParameters, Evidence evidence)
   at System.Xml.Serialization.TempAssembly.GenerateAssembly(XmlMapping[] xmlMappings, Type[] types, String defaultNamespace, Evidence evidence, XmlSerializerCompilerParameters parameters, Assembly assembly, Hashtable assemblies)
   at System.Xml.Serialization.XmlSerializer.GenerateTempAssembly(XmlMapping xmlMapping, Type type, String defaultNamespace)
   at System.Xml.Serialization.XmlSerializer..ctor(Type type, String defaultNamespace)
   at System.Xml.Serialization.XmlSerializer..ctor(Type type)
   at TestSerialization.TestXmlSerialization.SerializeClassWithNonPublicSetter_PersonReadOnly1() in E:\Projects\SerializationDemo2\TestSerialization\TestXmlSerialization.cs:line 74


The question is: should CLR exhibit the same runtime behaviour regardless of how the class is constructed?

Sunday, November 11, 2012

Slaying AVG2012's False Positive identification of my program as Luhe.Fiha.B

After I upgraded to AVG2012 some times ago, it has been causing me grieves when it picks on my C# program as one infected with Luhe.Fiha.B virus/trojan.

It is a simple program to perform date calculations and nothing sophisticated.

I requested the source out from the repository and rebuilt it from ground up. Still, AVG continued to pick on me. I am convinced that I am right and AVG is wrong. So finally, I come to a head to prove AVG is deadly wrong and dumb - a view I have held for a long long time for Anti-Virus programs, not just AVG.

Finally I have managed to prove beyond doubt AVG2012 is just another one of those dumb scanners lacking any form of intelligence.

Their false negative is caused by 2 BMP images in the application's icon list which are not even used. Once I removed these two 'offending' icons from the image list, AVG fails to raise the red flag.

If you have a similar experience, try to remove artifacts from your .Net projects. If AVG is interested to get hold of this ico file I can e-mail you. Just contact me.

However, by itself, AVG fails to identify it as Lihu.Fiha.B infected even when I ask AVG to scan it. It has to be used as the application ico in the C# project file for it to trigger the rage of AVG.

Friday, October 5, 2012

Microsoft's System.Xml.Serialization.XmlSerializer generates uncompilable code for some xs:double default values

Consider the following valid schema:
<xs:schema id="MyDemoSchema"
    targetNamespace="http://tempuri.org/MyDemoSchema.xsd"
    elementFormDefault="qualified"
    xmlns="http://tempuri.org/MyDemoSchema.xsd"
    xmlns:mstns="http://tempuri.org/MyDemoSchema.xsd"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
>
  <xs:complexType name="Foo">
    <xs:sequence>
      <xs:element name="Name" type="xs:string" minOccurs="0" maxOccurs="1" />
      <xs:element name="SomeNumber" type="xs:double" 
                  minOccurs="0" maxOccurs="1" 
                  default="NaN" />
    </xs:sequence>
  </xs:complexType>

  <xs:element name="Foo" type="Foo" />
</xs:schema>

The minute you execute the following piece of code:
Foo f = new Foo();
XmlSerializer ser = new XmlSerializer( typeof(Foo) ); // ---- Error CS0103 ---

will generate a CS0103 compilation error. This is caused by the CLR runtime in which it will at that moment generates a temporary serialization assembly that actually performs the serialization and deserialization process.

It is the code generation process that fails to handle W3C acceptable xs:double values such as NaN, INF and -INF producing uncompilable code.

In brief, but will provide a more detail expose below, is that it generates code like this:
   if( x != NaN ) { < --- causes CS0103
     // do something 
   }

Which naturally does not compile and it generates the same error message as when the XmlSerializer is instantiated. You can't even use the logical operator to test if the value of System.Double is Double.NaN.

This is the exact code fragment of the generated code causing the CS0103:
if (((global::System.Double)o.@SomeNumber) != NaN) {
    WriteElementStringRaw(@"SomeNumber", @"http://tempuri.org/MyDemoSchema.xsd", 
    System.Xml.XmlConvert.ToString((global::System.Double)((global::System.Double)o.@SomeNumber)));
}

There is no way this line can compile. It has to be corrected like this:
if ( !System.Double.IsNaN ((global::System.Double)o.@SomeNumber)  ) {
    WriteElementStringRaw(@"SomeNumber", @"http://tempuri.org/MyDemoSchema.xsd", 
    System.Xml.XmlConvert.ToString((global::System.Double)((global::System.Double)o.@SomeNumber)));
}

Detail Discussion and work around

To see how this manifested into a runtime error, you can use sgen.exe together with the /keep switch to look at what happen. The catch-22 is that if your schema's default value is NaN, sgen.exe will fail to generate the serialization dll because the generation process generates the above mentioned uncompilable code and you can't see the generated code.

So in order to see what is happening, you replace the default value with a double that you can recognised. In my experiment, I used -5.55.

Once your schema is modified, xsd.exe is used to generate C# classes that are bundled into an assembly, you can then use sgen.exe with the /keep switch to generate the serialization dll together with the source file. It also generates a file with the extension .cmdline which is essentially the response file for CSC.

Using our default value as search string, you can quickly locate the potentially offending piece of code. Below are the steps to prove that code generated by the serialization process is faulty and how to rectify it.

Now correct the line where it checks for -5.55 to using System.Double.IsNaN() as shown above.

The next step is to rebuild the serialization dll and to do that you need to modify the schema to change the default value back to NaN.

Then you use XSD to generate the class and rebuild your assembly.

Next you modify the cmdline file as follows:
  • remove the setting where it references System.Xml.dll to avoid duplicate reference compilation error. 
  • remove the /D: _DYNAMIC_XMLSERIALIZER_COMPILATION 
  • to aid experimentation change the /debug- to /debug.
Check the response file for the location of the CS file. You should execute this response file in that directory. For example if the source file is like this "OutTestDir\5fm3rmet.0.cs", you should run your CSC from the parent directory of "OutTestDir".

Next is to compile and generate the serialization dll which by now should have the offending line corrected using Double.IsNaN().

Next you modify the project for the dll that once called XmlSerializer constructor by
  • adding a reference to the serialization dll. 
  • then replace following piece of code where you instantiate an instance of XmlSerializer:
Foo f = new Foo();
StringBuilder buffer = new StringBuilder();
using( XmlWriter writer = XmlWriter.Create( buffer, null ) )
{
   XmlSerializer ser = new XmlSerializer( typeof(Foo) ); // <-- to be replaced
   ser.Serialize( writer, f );
}

With this:
Foo f = new Foo();
StringBuilder buffer = new StringBuilder();
using( XmlWriter writer = XmlWriter.Create( buffer, null ) )
{
   Microsoft.Xml.Serialization.GeneratedAssembly.FooSerializer ser = 
       new Microsoft.Xml.Serialization.GeneratedAssembly.FooSerializer();
   // XmlSerializer ser = new XmlSerializer( typeof(Foo) ); // <-- to be replaced
   ser.Serialize( writer, f );
}

If you have the PDB, you can easily step through the code to convince yourself that your fix indeed does work.

Let's hope Microsoft will fix this bug which is in .Net 4. May be .Net 5 has fixed this?

Tuesday, June 14, 2011

Safe way to close down a ClientBase<T> object

Recently a good friend of drew my attention to a situation I consider a bad disposable object implement and pointed me kindly to an MSDN article offering some words of advice and work around. This saved me considerable research effort. I will address the bad disposable object implementation later.

The problem is that when using the using statement to dispose a ClientBase(of T) object, the base class of WCF proxy stub, you can run into a problem where leaving the using scope the exception thrown in the Dispose() can mask out application exception that causes the execution to leave the scope in the first place. This denies the client the knowledge of the application exception.

The MSDN article explains this phenomenon very clearly and provides an excellent recommendation to handle this problem. The recommended work around places higher value on the application exception as compared to the one that is likely to happen when the Dispose(), or rather Close(), is called. The recommendation uses a multi-level of catches and then use either ClientBase(of T).Close() or its no-throw equivalent ClientBase(of T).Abort() strategically.

While the work around code presented in the article is written in a style that shows clearly how to tackle the problem, it is rather clumsy to use in real life. It expects too much from developer to know when to called Abort() and when to call Close(). Furthermore, it changes the shape of the code drastically to a somewhat awkward and unfamiliar form. It therefore leaves room for improvement and a simple class designed to meet the following objectives is described below:
  • Perform automatic closure of the ICommunicationObject using the same elegant form of the using statement.
  • Prevent the application exception, the one that is thrown inside the using statement scope, from being masked and passing it to the client unhindered.
  • If no application exception, it allows exception that can be generated during the disposable of the ICommunicationObject to pass to the client.
I want to use a pattern like this:
public void GetSomeData( .... ) {
   using( SomeHelper helper = new SomeHelper( new CalculatorClient() ) ) {
      GetData( helper.Instance() );
   }

This SomeHelper class must meet the above objectives.

Recognizing the issue at hand is how to handle the System.ServiceModel.ICommunicationObject, one of the interfaces implemented by ClientBase(of T), I construct the following disposable generic class called SafeCommunicationDisposal.

using System;
using System.ServiceModel;

namespace DisposingCommunicationObject
{
  public class SafeCommunicationDisposal<T> : IDisposable where T:ICommunicationObject
  {
    public T Instance { get; private set; }
    public bool IsSafeToClose{ get; private set; }
    public void SafeToClose() {
      this.IsSafeToClose = true;
    }
    
    public SafeCommunicationDisposal (T client) {
      this.Instance = client;
    }
    
    bool disposed;
    public void Dispose() {
      Dispose( true );
      GC.SuppressFinalize( this );
    }
    
    private void Dispose( bool disposing ) {
      if( !this.disposed ) {
        if( disposing ) {
          Close();
        }
        this.disposed = true;
      }
    }
    
    private void Close() {
      if( IsSafeToClose ) {
        Instance.Close();
      } else {
        Instance.Abort();
      }
    }
  }
}

With this class I can rewrite the naive usage of using the using statment from this:
using( CalculatorClient client = new CalculatorClient() ) {
      // use client to do work
  }
to this form which does not mask out application exception on leaving the using scope and yet closing down the communication object properly:
using( SafeCommunicationDisposal<CalculatorClient> d = 
            new SafeCommunicationDisposal<CalculatorClient> ( new CalculatorClient() ) ) {
     CalculatorClient client = d.Instance;
     // use the client to do work. If it throws exception
     // it will be passed over to the client and not masked by exception 
     // when client.Close() is executed.
     d.SafeToClose(); // This tells SafeCommunicationDisposal to use ICommunicationObject.Close()
} 

The fundamental principle is to tell SafeCommunicationDisposal what to use to close down the ICommunicationObject when execution leaves the using scope.

If it leaves by normal means, the SafeCommunicationDisposal.SafeToClose() sets a flag to tell the SafeCommunicationDisposal.Dispose() to use ICommunicationObject.Close(). If Close() throws an exception, it is then passed to the user.

If it leaves as a result of an application exception, SafeCommunicationDisposal.SafeToClose() will not be executed and SafeCommunicationDisposal.Dispose() will use ICommunicationObject.Abort(), a no-throw method to shut down the communication gracefully. This does not mask out the application exception.

If a developer forgets to call SafeCommunicationDisposal.SafeToClose(), the SafeCommunicationDisposal.Dispose() takes a more defensive route of calling the ICommunicationObject.Abort().

I believe this class can help to make the code more readable, maintainable and using a familiar using pattern to correct the  naive usage that minimize code change.  

The moral of this story is that if you are designing a disposable object, it is wise to heed the following advice "Avoid throwing an exception from within Dispose except under critical situations where the containing process has been corrupted (leaks, inconsistent shared state, etc.).". This is a well known no-no in unmanaged C++.

Wednesday, December 2, 2009

Treat String containing '\0' with care

Recently I had to decode a sequence of octets representing the UCS2 of some data and the sequence contained the C-Style string's null terminator. The sequence of octets were represented in C# as Byte[] naturally and Encoding.Unicode.GetString() was used to decode the sequence into a Unicode string.

The decoding process did not trim off the terminating '\0'. So it produced a Unicode string like this "Hello World\0".

During testing, several interesting things were discovered that could have significant impact on your code and the validity of your Unit Tests:
1) If you write out the string to console like this:
String s = "Hello World\0"; 
Console.WriteLine( "This is the Unicode String = '{0}'", s );

Your output will not contain the trailing '.

2) If you use write out several lines like this:
String s = "Hello World\0"; 
Console.WriteLine( "This is the Unicode String = '{0}'", s );
Console.WriteLine( "See anything strange?" );

It will produce a line like this:
This is the Unicode String = 'Hello WorldSee anything strange?

The Console.WriteLine() removes the ending ' and the newline.

3) Make sure you use the correct version of String.Compare() and use the correct comparison type as specified by the StringComparison enumeration:
String s0 = "Hello World"; 
String s1 = s0 + "\0";

Assert.IsFale( s0.EndsWith( "\0" ); // Just to check 
Assert.IsTrue( s1.EndsWith( "\0" ); // Just to check
Assert.IsTrue( s0.Equals( s1 )==false ); 
Assert.IsTrue( String.Compare( s1, s0 )!=0 );     // Fail but should Pass
Assert.IsTrue( String.Compare( s1, s0, false )!=0 ); // Fail but should Pass
Assert.IsTrue( String.Compare( s1, s0, StringComparison.Ordinal )!=0 );
Assert.IsTrue( String.Compare( s1, s0, 
   StringComparison.InvariantCulture )!=0 ); // Fail but should Pass

The lines in red are incorrectly processed.

Be careful when using NUnit's Assert.AreEqual(). In version 2.4.x, the AreEqual() incorrectly handles this case resulting in passing the comparison. This mistake has been fixed in ver 2.5. MSTest's AreEqual() correctly handles this case.

This illustrates the need to exercise care when comparing strings.

Monday, March 9, 2009

VB.Net can block pass by reference parameter - Is it real?

I was browsing around some MSDN materials in VB.Net and came across this puzzling claim "How to: Force an Argument to Be Passed by Value".

The obvious question that sprang to my mind was: Is this real? I know nothing in CLI that supports this kind of thing. There is also confusing statement in that reference
If a parameter is declared ByRef, Visual Basic expects to pass the corresponding argument by reference. This allows the procedure to change the value of the programming element underlying the argument in the calling code.
If the "value of the programming element" means the object reference or memory address, then that statement is true.

In .Net if the object being passed across is a reference object, no matter you pass use ByVal (in C# no qualifier needed) or ByRef (in C# with the ref qualifier), the called function can change the state of the object but only the reference or the memory address of the object can be modified if using ByRef.

So what has VB.Net invented that CLI does not support? Obviously this must be a source level construct and not IL construct. It turns out that there is really nothing new or to trumpet about.

According to the documentation, if you surround the argument, which is specified by the called function to have ByRef convention, with a bracket, you can prevent the called function from modifying the object address, like this:
 Dim a As DemoClass
Dim b As DemoClass
a = New DemoClass(10, "Jack")
b = a
Show(a, "Before")
SomeFunctions.DoSomethingA((a)) ' L1
Show(a, "After")
Debug.Print("Are the same ? " & (Object.ReferenceEquals(a, b).ToString()))

Line L1 shows the protection syntax. The Debug.Print shows object a and b are occupying the same memory location. So the (a) syntax defeats the function's parameter's convention which is specified as:
    public static class SomeFunctions {
public static void DoSomethingA( ref DemoClass a ) {
a = new DemoClass( a.Number + 100, "Bye " + a.Name );
}
}
So how can VB.Net defeat the convention specified by a C# function?

To answer this question you need to examine the IL code generated by VB to see if it is merely a trick. This is the IL code of the above VB.Net fragment:
  .locals init ([0] class [MySupport]MySupport.DemoClass a,
[1] class [MySupport]MySupport.DemoClass b,
// .....
[4] class [MySupport]MySupport.DemoClass VB$t_ref$S0,
[5] bool VB$t_bool$S0)
IL_0000: nop
IL_0001: ldc.i4.s 10
IL_0003: ldstr "Jack"
IL_0008: newobj instance void [MySupport]MySupport.DemoClass::.ctor(int32,
string)
IL_000d: stloc.0
IL_000e: ldloc.0
IL_000f: stloc.1
IL_0010: ldloc.0
IL_0011: ldstr "Before"
IL_0016: call void TestParameterPassing.Module1::Show(class [MySupport]MySupport.DemoClass,
string)
IL_001b: nop
IL_001c: ldloc.0
IL_001d: stloc.s VB$t_ref$S0
IL_001f: ldloca.s VB$t_ref$S0
IL_0021: call void [MySupport]MySupport.SomeFunctions::DoSomethingA(class [MySupport]MySupport.DemoClass&)
IL_0026: nop
IL_0027: ldloc.0
IL_0028: ldstr "After"
IL_002d: call void TestParameterPassing.Module1::Show(class [MySupport]MySupport.DemoClass,
string)
IL_0032: nop
IL_0033: ldstr "Are the same \? "
IL_0038: ldloc.0
IL_0039: ldloc.1
IL_003a: call bool [mscorlib]System.Object::ReferenceEquals(object,
object)
IL_003f: stloc.s VB$t_bool$S0
IL_0041: ldloca.s VB$t_bool$S0
IL_0043: call instance string [mscorlib]System.Boolean::ToString()
IL_0048: call string [mscorlib]System.String::Concat(string,
string)
IL_004d: call void [System]System.Diagnostics.Debug::Print(string)

Notice the local variable 4, VB$t_ref$S0, a compiler generated auto-variable of the same type as the function's parameter. From line IL_001c to IL_001f, the IL code is to stash the object in a to VB$t_ref$S0 and then pass this temporary variable by reference to the called function. The idea is to let that function modifies a sacrificial object without harming the protected one inside the bracket, that is a.

You can achieve the same result in C# as follows:
   DemoClass a = new DemoClass( 23, "Peter" );
DemoClass b = a;
DemoClass tmp = a;
SomeFunctions.DoSomethingA( ref tmp );
Debug.WriteLine( String.Format( "Are they the same? " + Object.ReferenceEquals( b, a ) ) );
The variable tmp is the throw away one. So there is nothing new. It is just a simple convenience trick - nothing more and nothing less.

Blog Archive