Whaly's World tail -f /var/log/whaly

18Aug/110

Xml deserialization error with invalid character

Recently I had a strange error, I serialized a complex object and during the deserialization process I got :
"Error : System.Xml.XmlException: '.', hexadecimal value 0x00, is an invalid character. Line X, position Y."
It appears that we had a "\0" inside a string, something like "Hello\0World" ! and during a classic serialization, the character was encoded in "�"

With the help of Google I have found this post (2007) with a way to have an happy deserialization :-)

You can use XmlTextReader instead of XmlReader, but with more research I have found that you can still use XmlReader with XmlReaderSettings and CheckCharacters set to false.

Here is an example :

    public class MyObject
    {
        public string MyString { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {

            XmlSerializerFactory fact = new XmlSerializerFactory();
            XmlSerializer ser = fact.CreateSerializer(typeof(MyObject));

            MyObject obj0 = new MyObject();
            obj0.MyString = "Hello\0World";

            // Serialize the object
            StringWriter sw = new StringWriter();
            ser.Serialize(sw, obj0);
            string xml = sw.ToString();
            // We can check that in the xml a \0 is transformed in �
            Console.WriteLine(xml);

            // Classic use of XmlReader.Create
            StringReader sr1 = new StringReader(xml);
            XmlReader xr1 = XmlTextReader.Create(sr1); // xr1's type is XmlTextReaderImpl
            try
            {
                MyObject obj1 = (MyObject)ser.Deserialize(xr1);
                Console.WriteLine("XmlReader [CheckCharacters({0})] : Success : {1}", xr1.Settings.CheckCharacters, obj1.MyString);
                Console.WriteLine(obj1.MyString);
            }
            catch (Exception e)
            {
                Console.WriteLine("XmlReader [CheckCharacters({0})] : Error : {1}", xr1.Settings.CheckCharacters, e.InnerException);
            }

            // Using an XmlTextReader
            StringReader sr2 = new StringReader(xml);
            XmlTextReader xr2 = new XmlTextReader(sr2);
            // xr2.Settings is null
            MyObject obj2 = (MyObject)ser.Deserialize(xr2);
            Console.WriteLine("XmlTextReader : Success : {0}", obj2.MyString);

            // Using XmlReader with the good XmlReaderSettings
            StringReader sr3 = new StringReader(xml);
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.CheckCharacters = false; // default value is true;
            XmlReader xr3 = XmlTextReader.Create(sr3, settings); // xr3.Settings.CheckCharacters is a read only and xr3's type is XmlTextReaderImpl
            MyObject obj3 = (MyObject)ser.Deserialize(xr3);
            Console.WriteLine("XmlReader [CheckCharacters({0})] : Success : {1}", xr3.Settings.CheckCharacters, obj3.MyString);
        }
    }
Tagged as: , No Comments
27Jan/110

Viewbox and Windows Phone 7

Viewbox is not in the original WP7 because it's not in Silverlight 3.
Viewbox is in Silverlight 4.

Neil Rees extract the source for the ViewBox control from the November 2009 version of the Silverlight Toolkit.

Now you can use the Viewbox control with the Windows Phone 7.

Tagged as: , No Comments
24Jan/110

Screen Resolution

  • Quad HDTV : 3840 x 2160
  • WUXGA : 1920 x 1200 : Monitor at home
  • Full HD : 1920 × 1080
  • WSXGA+ : 1680 x 1050 : Monitor at work
  • HD Ready : 1280 × 720
  • SVGA : 1024 x 768 : iPad
  • WVGA : 800 x 480 : Windows Phone 7
  • ????????? : 960 x 640 : iPhone 4
  • HVGA : 480 x 320 : iPhone 1, 3G, 3GS

Tagged as: No Comments
15Sep/100

TortoiseGit + Dropbox, my personnal SCM combo under Windows

Why Git ?
Because I followed the early history in 2005 and I liked the design :-)

Why now ?
Because I am under Windows and I feel that the windows port is ready for my personnal use with TortoiseGit.

Where is my repository ?
Just on my local drive, but if you want to opensource your project I suggest you to go on GitHub.

How to backup and get my source from an another computer ?
Dropbox ! because I already use Dropbox to sync my files online and across my computers automatically and it works very well.
If you use my referral link for Dropbox, you will have +250 Mo with your 2 Go free account. (and me too)

Finally, if the project is not a Vaporware, you can always move your repository on GitHub or somewhere else.

Go and try TortoiseGit with Dropbox

10Mar/100

Error 415 and WCF Compatibility between .Net 2.0 and 3.5

If you try to call a 3.5 WCF Service with the framework 2.0 and WCF 3.0, you will have an error 415 :

Cannot process the message because the content type 'text/xml; charset=utf-8' was not the expected type 'application/soap+xml; charset=utf-8'

'text/xml' is the content type for SOAP 1.1 while 'application/soap+xml' is the content type for SOAP 1.2 and your client WCF 3.0 use SOAP 1.1 while the service with WCF 3.5 use SOAP 1.2.

Here is the solution that worked for me. If you have access to the service config, you just have to change the binding to use SOAP 1.1 :

Add a new custom binding in the 'bindings' section

      <customBinding>
        <binding name="Soap11HttpBinding">
          <textMessageEncoding messageVersion="Soap11" />
          <httpTransport />
        </binding>
      </customBinding>

and don't forget to update your endpoint with the new binding :

    <endpoint ...
        binding="customBinding"
        bindingConfiguration="Soap11HttpBinding">
        ...
    </endpoint>
28Jan/100

How to remove Diacritics in .net C#

If you need to remove diacritics from a string you can :

  • [Bad] do a lot's of replace like :-(
inputString = inputString.Replace('À', 'A');

repeat for ÀÁÂÃÄâãäàáÈÉÊËêëèéÌÍÎÏîïìíÒÓÔÖôõöòóÙÚÛÜûüùúÝýÑñç and maybe miss some exotic chars or the Õ in this list !

  • [Good] or you can use this function :-)
	public static string RemoveDiacritics(string inputString)
	{
		//!\\ Warning 'œ' will be replaced with a 'o' not an 'oe'
		String normalizedString = inputString.Normalize(NormalizationForm.FormD);
		StringBuilder stringBuilder = new StringBuilder();
		for (int i = 0; i < normalizedString.Length; i++)
		{
			Char c = normalizedString[i];
			if (System.Globalization.CharUnicodeInfo.GetUnicodeCategory(c) != System.Globalization.UnicodeCategory.NonSpacingMark)
				stringBuilder.Append(c);
		}
		return stringBuilder.ToString();
	}
2Nov/090

SEO: Subfolders or Subdomains

I recently moved my blogs from subdomains and multiple domain to one domain with subfolders, here are articles on the subject from Chewy's Blog and Search Engine Journal

... search engine view subdomain site as a different site so the work you have done on the sub domain does not directly affect the parent domain as they are viewed as a separate entity.

History, first I had my blog.baleinoid.fr and whaly.baleinoid.fr websites, I moved recently whaly.baleinoid.fr to wha.ly for the fun of the new domain :-) now I moved again and I have http://baleinoid.com/journal/baleine and http://baleinoid.com/whaly

I checked the pro and cons and I choosed the subfolders path, because I don't have a lots of backlinks and it's easier to get a better search engine rank with one domain.

Subfolders Pro:

  • to spread/share the rank of the domain

Subdomains Pro:

  • if you have different hosting server for your blog / forum / website
9Oct/090

WCF WSDL SOAP binding: Rpc or Document, Encoded or Literal

Yeah, my new WebService must be Rpc/Encoded. What ????

Hopefully this page from Ibm explain the different style/use in SOAP message.

A WSDL document describes a Web service. A WSDL binding describes how the service is bound to a messaging protocol, particularly the SOAP messaging protocol. A WSDL SOAP binding can be either a Remote Procedure Call (RPC) style binding or a document style binding. A SOAP binding can also have an encoded use or a literal use.

Ok now I know that four style/use models:
RPC/Encoded, RPC/literal, Document/encoded or Document/literal

But how do I do that in WCF C# ?? It's very easy, just use the [XmlSerializerFormat] attribute.

Here is a very very simple test to check the different result in the soap message:

Interface of the Wcf service used :

using System.ServiceModel;

namespace WcfService1
{
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        [XmlSerializerFormat(Style = OperationFormatStyle.Rpc, Use = OperationFormatUse.Encoded)]
        string TestRpcEncoded(int value);

        [OperationContract]
        [XmlSerializerFormat(Style = OperationFormatStyle.Rpc, Use = OperationFormatUse.Literal)]
        string TestRpcLiteral(int value);

        //[OperationContract]
        //[XmlSerializerFormat(Style = OperationFormatStyle.Document, Use = OperationFormatUse.Encoded)]
        //string TestDocumentEncoded(int value);

        [OperationContract]
        [XmlSerializerFormat(Style = OperationFormatStyle.Document, Use = OperationFormatUse.Literal)]
        string TestDocumentLiteral(int value);
    }
}

Result captured on the network with fiddler:

For clarity, I have removed:

  • s:Envelope tag
  • xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"
  • xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  • xmlns:xsd="http://www.w3.org/2001/XMLSchema"
  • xmlns="http://tempuri.org/"

RPC / Encoded call

<!-- Request -->
<s:Body s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
  <q1:TestRpcEncoded>
    <value xsi:type="xsd:int">42</value>
  </q1:TestRpcEncoded>
</s:Body>

<!-- Response -->
<s:Body s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
  <q1:TestRpcEncodedResponse>
    <TestRpcEncodedResult xsi:type="xsd:string">You entered: 42</TestRpcEncodedResult>
  </q1:TestRpcEncodedResponse>
</s:Body>

RPC / Literal call

<!-- Request -->
<s:Body>
  <TestRpcLiteral>
    <value xmlns="">42</value>
  </TestRpcLiteral>
</s:Body>

<!-- Response -->
<s:Body>
  <TestRpcLiteralResponse>
    <TestRpcLiteralResult xmlns="">You entered: 42</TestRpcLiteralResult>
  </TestRpcLiteralResponse>
</s:Body>

Document / Encoded call
If you add the TestDocumentEncoded you will get an InvalidOperationException.
This combination is not supported.

Document / Literal call

<!-- Request -->
<s:Body></code>
  <TestDocumentLiteral><value>42</value></TestDocumentLiteral>
</s:Body>

<!-- Response -->
<s:Body>
  <TestDocumentLiteralResponse>
    <TestDocumentLiteralResult>You entered: 42</TestDocumentLiteralResult>
  </TestDocumentLiteralResponse>
</s:Body>
24Sep/090

WWW or NO-WWW ?

For my new domain "frederichusson.com" I used links without "www." like "http://frederichusson.com" mainly because I like when things are simple.

Then I realized that maybe it was a mistake and maybe a "www." site can get a better ranking in search engine.
Then I searched on this subject and came accross "www. is deprecated" and a little after on an article at sitepoint.com

And so I decided to stay without "www." and to take some actions :

  1. Keep my current link without the www.
  2. Add a .htaccess file to redirect (301) visitors from http://www.frederichusson.com to http://frederichusson.com (for help look at "How can I become Class B?")
  3. Use the Google Webmasters Tools to configure my favorite domain.
15Sep/090

Howto test if and index exist in SQL Server

IF INDEXPROPERTY(OBJECT_ID('TableName'), 'IndexName', 'IndexID') IS NOT NULL
	PRINT 'Index is here'
ELSE
	PRINT 'Index not found'