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

Saturday, June 26, 2010

Serialization should eat its own dog food

@YaronNaveh

An enum in c# can be used as a bit field by adding the Flags attribute:


[Flags]
public enum Groups
{
   Admins = 1,
   Users = 2,
   Guests = 4,
   RemoteUsers = 8
}


We can then define a class that uses it:


[DataContract]
public class User
{
   [DataMember]
   public Groups Groups {get; set;}
}


When we serialize an instance of the class, with either .Net 2.0 serialization or data contract serialization, we get something like this:


...
<Groups>Admins RemoteUsers</Groups>
...


assuming the active flags are Admins and RemoteUsers.

If we deserialize this back to the class everything works fine. But what if the xml needs to be manually parsed for some reason and we need to do something like this:


Enum.Parse(typeof(Groups), "Admins RemoteUsers");


We would get this exception:


Requested value 'Admins RemoteUsers' was not found.


The reason is that Enum.Parse expects a comma between the values and not a space. So this fails:


Enum.Parse(typeof(Groups), "Admins RemoteUsers");


while this work:


Enum.Parse(typeof(Groups), "Admins,RemoteUsers");


Since a space is not valid inside an enum member we can safely do this when reading from the xml:


Enum.Parse(typeof(Groups), value.Replace(" ", ","));


Which will work.

However in the general case manually deserializing a value is dangerous. For example the enum may contain serialization flags:


[Flags]
public enum Groups
{
   [XmlEnum(Name="administrators")]
   Admins = 1,
...
}


This will affect the resulting xml:


...
<Groups>administrators RemoteUsers</Groups>
...


and Enum.Parse will fail. So it is always better to let whoever generated the xml from the first place to eat its own dog food and deserialize it back.

@YaronNaveh

What's next? get this blog rss updates or register for mail updates!

Friday, April 2, 2010

Quiz #2 - The answer (goto in c#)

@YaronNaveh

A few days ago I published the below reflector generated code:


private void NoGoto()
{
     int i = 0;
     if (i == 0)
     {
         switch (i)
         {
             case 0:
             case 1:
             goto Label_002C; //WTF?!
         }
         i--;
     }
    Label_002C:
         i++;
}


And asked what was the original code. Well, here it is:



void NoGoTo()
{
        int i = 0;
        if (i==0)
        {
            switch (i)
            {
                case 0:
                    break;
                case 1:
                    break;
                default:
                    i-- ;
                    break;
            }
        }

        i++;
}


no goto at all.

Liran and an anonymous reader corresponded that goto may not be that bad in all cases. They are right, loop controls such as break and continue are disguised goto's. Liran also mentioned the multi-level breaks in Java which satisfy some of the goto possible use cases. For me all of these are an attempt to capture the 'good' goto use cases and keep our code clean from possible abuse of the generic flavor.

My motivation for the whole inquiry was seeing a lot of goto's in framework code using the reflector. One example is BasicHttpMessageSecurity.CreateMessageSecurity(). I wanted to make sure I am up to the times with the latest coding fashions. When I have downloaded the WCF sources locally to debug them I no no sign of goto.

@YaronNaveh

What's next? get this blog rss updates or register for mail updates!

Monday, March 29, 2010

Quiz #2: Goto statement in C#

@YaronNaveh

I have written a very simple C# method. This method did not contain any goto statements (they're bad, right?). I have then opened my method in the reflector and found this:


private void NoGoto()
{
     int i = 0;
     if (i == 0)
     {
         switch (i)
         {
             case 0:
             case 1:
             goto Label_002C; //WTF?!
         }
         i--;
     }
    Label_002C:
         i++;
}


The quiz question is: What is going on here? What was my original code?

@YaronNaveh

What's next? get this blog rss updates or register for mail updates!

Friday, February 12, 2010

Quiz #1 - the answer

@YaronNaveh

Quiz #1 is over. Pablo and Dmitry were right, the XmlWriter uses the builder design pattern. A common algorithm traverses over the xml nodes, while a concrete builder (derived from XmlWriter) builds the resulting object (the stream) in a concrete way. This allows multiple builders (xml text writer, xml binary writer) to be used.

@YaronNaveh

What's next? get this blog rss updates or register for mail updates!

Monday, February 8, 2010

Question #1 for the readers: Which design pattern is used here?

@YaronNaveh

There's an interesting design patterns riddle for you readers in the end of this post.

Jesse wrote an interesting post about xml and the .Net framework. He reminds us that xml is actually an abstraction and that Angle brackets are just one (inefficient) way of representing it.

For this reason this code:


...
xmlWriter.WriteStartElement("rawBytes");
xmlWriter.WriteBase64(arr);
xmlWriter.WriteEndElement();
...
xmlWriter.WriteStartElement("blog");
xmlWriter.WriteString("yaron's blog");
xmlWriter.WriteEndElement();
...


can actually generate both "regular" xml and optimized binary one, depending on the implementation of XmlWriter handed to it.

This is actually a great example of a design pattern implemented in the .Net framework BCL.

Can you guess which design pattern is it? Here's the DP list. Give your best shot at the comments bellow!

@YaronNaveh

What's next? get this blog rss updates or register for mail updates!

Thursday, November 19, 2009

Generating meaningful names from a url

@YaronNaveh

A common programming task is to extract some meaningful name from a url.
One example is saving the contents of a url to a file name on disk - we need to have the name for the file.
Bellow there is a c# method that I have written that extracts this name + the results it produces on a few urls.


http://www.myServer.com/Services/Sanity.asmx?WSDL - Sanity
http://www.myServer.com/Services/Sanity.asmx?wsdl=1&xsd=2 - Sanity
http://www.myServer.com/Services/Sanity12345678901234567890123456789012345678901234567890123456789012.asmx - Sanity1234567890123456789012345678901234567
http://www.myServer.com/Services/Sanity.asmx - Sanity
http://www.myServer.com/Services/Sanity/ - Sanity
http://www.myServer.com/Services/Sanity - Sanity
http://www.myServer.com/Services/Sanity?wsdl - Sanity_wsdl
http://www.myServer.com/Services/Sanity/?wsdl - Sanity





public static string GetSuggestedNameFromUrl(string url, string defaultValue)
{
  const int MaxChars = 50;

  string res = Path.GetFileNameWithoutExtension(url);

  //check if there is no file name, i.e. just folder name + query string
  if (String.IsNullOrEmpty(res) || IsNameOnlyQueryString(res))
  {
    res = Path.GetDirectoryName(url);
    res = Path.GetFileName(res);

    if (String.IsNullOrEmpty(res))
       res = defaultValue;
  }

  res = ReplaceInvalidCharacters(res);

  if (res.Length > MaxChars)
     res = res.Substring(0, MaxChars);

  return res;
}


private static string ReplaceInvalidCharacters(string res)
{
  return Regex.Replace(res, @"[^\w]", "_", RegexOptions.Singleline);
}


private static bool IsNameOnlyQueryString(string res)
{
  return !String.IsNullOrEmpty(res) && res[0]=='?';
}

@YaronNaveh

What's next? get this blog rss updates or register for mail updates!