Dan Rigsby – Coding Up Style

Developer.Speaker.Blogger

Archive for the '.Net' Category

Generic Notify Property Change Controller

Posted by Dan Rigsby on 14th March 2008

This is another example of a class you could put into a common library.   Suppose I want to create a class that fires an event every time the value of a property changes.  I could implement such a class like this:

public class MyClass : INotifyPropertyChanged
{
    private string m_Text;
    public string Text
    {
        get { return m_Text; }
        set
        {
            if (m_Text != value)
            {
                m_Text = value;
                OnPropertyChanged("Text");
            }
        }
    }

    protected virtual void OnPropertyChanged(
        string propertyName)
    {
        PropertyChangedEventHandler handler = m_PropertyChanged;
        if (handler != null)
        {
            m_PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    #region INotifyPropertyChanged Members
    private event PropertyChangedEventHandler m_PropertyChanged;
    public event PropertyChangedEventHandler PropertyChanged
    {
        add { m_PropertyChanged += value; }
        remove { m_PropertyChanged -= value; }
    }
    #endregion INotifyPropertyChanged Members
}
 
If you have a large class library and a lot of properties, this can add up to a lot of code.  There is an easier way to do this at a very small cost of performance.  Ill show the code for the PropertyController class at the end of this post, but this is an example of what the above code could look like:
 
public class MyClass : INotifyPropertyChanged
{
    private PropertyController m_PropertyController
    private string m_Text;
    public string Text
    {
        get { return m_Text; }
        set { m_PropertyController.ChangeProperty("Text", value);
    }

    #region INotifyPropertyChanged Members
    public event PropertyChangedEventHandler PropertyChanged
    {
        add { m_PropertyController.PropertyChanged += value; }
        remove { m_PropertyController.PropertyChanged -= value; }
    }
    #endregion INotifyPropertyChanged Members
}

 

That is significantly less code and much cleaner.  Just, imagine if I had a class library with 30 classes.

You could also do this:

set { m_PropertyController.ChangeProperty("Text", value);

 

instead of:

set { m_PropertyController.ChangeProperty(value);

 

The cost of doing this is that the PropertyController has to look at the stack trace, but depending on what you are doing, this may be worth the cost.

The ChangeProperty method returns a boolean to indicate whether or not the value was changed.  So inside your property code you could react depending on the result.

Here is the complete PropertyController class.  Feel free to use it, modify it, ignore it, etc. You could even use this class and not even expose the PropertyChanged event, if you don’t need it.

public class PropertyController : INotifyPropertyChanged, IDisposable
{
    private Dictionary<string, PropertyInfo> m_Properties =
        new Dictionary<string, PropertyInfo>();

    public PropertyController()
    {
    }

    #region INotifyPropertyChanged Members
    private event PropertyChangedEventHandler m_PropertyChanged;

    public event PropertyChangedEventHandler PropertyChanged
    {
        add
        {
            m_PropertyChanged += value;
        }
        remove
        {
            m_PropertyChanged -= value;
        }
    }
    #endregion INotifyPropertyChanged Members

    protected PropertyInfo GetProperty(string propertyName)
    {
        if (!m_Properties.ContainsKey(propertyName))
        {
            m_Properties.Add(propertyName, this.GetType().GetProperty(propertyName));
        }

        return m_Properties[propertyName];
    }

    public virtual bool ChangeProperty(object newValue)
    {
        return ChangeProperty(new System.Diagnostics.StackTrace().GetFrame(1).GetMethod().Name, newValue);
    }

    public virtual bool ChangeProperty(string propertyName, object newValue)
    {
        System.Reflection.PropertyInfo property =
            GetProperty(propertyName);

        if (property.GetValue(this, null) != newValue)
        {
            property.SetValue(this, newValue, null);
            OnPropertyChanged(propertyName);

            return true;
        }

        return false;
    }

    public virtual void OnPropertyChanged(
        string propertyName)
    {
        PropertyChangedEventHandler handler = m_PropertyChanged;
        if (handler != null)
        {
            m_PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    #region IDisposable Members
    public void Dispose()
    {
        m_PropertyChanged = null;
    }
    #endregion IDisposable Members
}

Posted in .Net, Common Libraries | 2 Comments »

.Net EventHandlers – Best Practices

Posted by Dan Rigsby on 9th March 2008

One question that comes up a lot is, “How can I can clean up my event handlers in an object?”.  What are the best practices for cleaning up event handlers?  This is actually a pretty important question.  One of the number one reasons for memory drains in .Net is because event handlers aren’t removed.   For instance: if ObjectA is registered for an event on ObjectB and ObjectB goes out of scope and should be garbage collected, it can’t because ObjectA still has a reference to do it via the event handler.  Get into some complex circular patterns, and you are just eating memory.

In an ideal world every time an object registers for an event, it should remove it when that object is destroyed, but what happens when the object it is listening for events on should be destroyed?

One way I use to get around this, is to declare the event as private, then expose it through a public property with Add and Remove accessor methods like so:

private System.EventHandler m_MyEvent;  

public event System.EventHandler MyEvent
{
    add
    {
        m_MyEvent += value;
    }
    remove
    {
        m_MyEvent -= value;
    }
}

Then in your Dispose() method or in some other clean up method, you can set the private event to null to remove all subscriptions to the event.

public void Dispose()
{
    m_MyEvent = null;
}

By setting the private event to null, you are basically telling it to remove any events listening to it. So that there are no more references to the object, so it can be disposed cleaning. This is similar to getting the invocation list of the event and removing all of the delegates:

foreach(System.EventHandler e in MyEvent.GetInvocationList())
{
    MyEvent -= e;
}

You could also use WeakReference objects which can be used to bypass this same situation.  However, it does involve rewriting a good chuck of code, and take a bit of thought to decide where to put it and where not to.  Using the method above can work with a WeakReference as well.  The nice thing about the method above is that the object is cleaning itself up and doesn’t rely on the GC or something else to do its dirty work.

Posted in .Net | 1 Comment »

XmlSerializer vs DataContractSerializer: Serialization in Wcf

Posted by Dan Rigsby on 7th March 2008

wwwf The XmlSerializer has been in .Net since version 1.0 and has served us well for everything from Remoting, Web Services, serializing to a file, etc. However in .Net 3.0 the DataContractSerializer came along.  And all of a sudden a lot of guidance suggests that we should use it over the old tried and true XmlSerializer. Wcf even uses this as the default mechanism for serialization.  The question is, “Is it really better?”.  The verdict is yes, and no.  Like most things it depends on your implementation and what you need.  For Wcf, you should prefer to use the DataContractSerializer.  If you need full control over how the xml looks though, you should go back to the XmlSerializer.

Lets look at the both of these in detail and leave it up to you to decide which is best for your implementation.  Here are a few of the advantages and disadvantages of each of them:

XmlSerializer DataContractSerializer
Advantages:
1. Opt-out rather than opt-in properties to serialize. This mean you don’t have to specify each and every property to serialize, only those you don’t wan to serialize2. Full control over how a property is serialized including it it should be a node or an attribute

3. Supports more of the XSD standard

Disadvantages:
1. Can only serialize properties

2. Properties must be public

3. Properties must have a get and a set which can result in some awkward design

4. Supports a narrower set of types

5. Cannot understand the DataContractAttribute and will not serialize it unless there is a SerializableAttribute too

Advantages:
1. Opt-in rather than opt-out properties to serialize. This mean you specify what you want serialize

2. Because it is opt in you can serialize not only properties, but also fields.  You can even serialize non-public members such as private or protected members. And you dont need a set on a property either (however without a setter you can serialize, but not deserialize)

3. Is about 10% faster than XmlSerializer to serialize the data because since you don’t have full control over how it is serialize, there is a lot that can be done to optimize the serialization/deserialization process.

4. Can understand the SerializableAttribute and know that it needs to be serialized

5. More options and control over KnownTypes

Disadvantages:
1. No control over how the object is serialized outside of setting the name and the order

What is Serialization?

Let’s start with the basics.  Serialization has been a key part of .Net since version 1.  It is basically the process of converting an object instance into a portable and transferable format.  The objects can be serialized into all sorts of formats.  Serializing to Xml is most often used for its interoperability.  Serializing to binary is useful when you want to send the object from one .Net application to another.  .Net even supports the interfaces and base classes to build your own serializes. There are libraries out there to serialize to comma delimited strings, JSON, etc.

Deserialization is basically the reverse of serialization.  Its the process of taking some data (Xml, binary, etc) and converting it back into an object.

What is the XmlSerialzer?

For those that may not be familiar with System.Xml.Serialization.XmlSerializer let’s go over it briefly.  This is the xml serializer that has been around since .Net version one.  To serialize or deserialize an object, you basically just need to create an instance of the XmlSerializer for the type you want to work with, then just call Serialize() or Deserialize().  It works with streams, so you could serialize to any stream such as an MemoryStream, FileStream, etc.

// Create serializer for the type
System.Xml.Serialization.XmlSerializer xmlSerializer =
    new System.Xml.Serialization.XmlSerializer(typeof(MyType)); 

// Serialize from an object to a stream
xmlSerializer.Serialize(stream, myInstanceOfMyType); 

// Deserialize from a stream to an object
myInstanceOfMyType = (MyType)xmlSerializer.Deserialize(stream);

However not just any object can be serialized.  It supports a number of the base types in .Net and most custom types.  Many people think that the SerializableAttribute is required on the class in order for it to be serializable by the XmlSerializer, but this is not the case.  It is good practice to use the SerializableAttribute, but it not required.  As long as your class contains all types that the serializer understands, then it will work.  You need to break out IXmlSerializable to implement your own custom serialization for types that the XmlSerializer cannot understand.  Any public property that is of a known serializable type and has a get and set will be serialized by the XmlSerialzer.  This can be referred to as an “opt-out” approach, because you chose what you don’t want to include, not what you want to include.

There are a number of attributes you can use in your class to change how it is serialized:

  1. System.Xml.Serialization.XmlIgnoreAttribute: This is used to mark a public property as “not to be serialized”. This is the “opt-out” approach used by the XmlSerializer.  There are no properties on this attribute.
  2. System.Xml.Serialization.XmlRootAttribute: This is used on the class itself to change the name or namespace of the root node. The following properties are supported on the attribute:
    1. AttributeName: Gets or sets the name of the XML attribute.
    2. DataType: Gets or sets the XSD data type of the XML attribute generated by the XmlSerializer.
    3. Form: Gets or sets a value that indicates whether the XML attribute name generated by the XmlSerializer is qualified.
    4. Namespace: Gets or sets the XML namespace of the XML attribute.
    5. Type: Gets or sets the complex type of the XML attribute.
    6. TypeId: When implemented in a derived class, gets a unique identifier for this Attribute.
  3. System.Xml.Serialization.XmlAttributeAttribute: Serialize the property as an xml attribute.  You can specify things such as the name to use (instead of the property name).  The following properties are supported on the attribute:
    1. AttributeName: Gets or sets the name of the XML attribute.
    2. DataType: Gets or sets the XSD data type of the XML attribute generated by the XmlSerializer.
    3. Form: Gets or sets a value that indicates whether the XML attribute name generated by the XmlSerializer is qualified.
    4. Namespace: Gets or sets the XML namespace of the XML attribute.
    5. Type: Gets or sets the complex type of the XML attribute.
    6. TypeId: When implemented in a derived class, gets a unique identifier for this Attribute.
  4. System.Xml.Serialization.XmlElementAttribute: Serialize the property as an xml element.  You can specify things such as the name to use (instead of the property name), whether or not to serialize it if it is null, the order to serialize the property in relative to other properites, etc. The following properties are supported on the attribute:
    1. ElementName: Gets or sets the name of the XML element.
    2. DataType: Gets or sets the XSD data type of the XML attribute generated by the XmlSerializer.
    3. Form: Gets or sets a value that indicates whether the XML attribute name generated by the XmlSerializer is qualified.
    4. Namespace: Gets or sets the XML namespace of the XML attribute.
    5. IsNullable: Gets or sets a value that indicates whether the XmlSerializer must serialize a member that is set to nullNothingnullptra null reference (Nothing in Visual Basic) as an empty tag with the xsi:nil attribute set to true.
    6. Order: Gets or sets the explicit order in which the elements are serialized or deserialized.
    7. Type: Gets or sets the complex type of the XML attribute.
    8. TypeId: When implemented in a derived class, gets a unique identifier for this Attribute.

Here is an example class setup to use the XmlSerializer.  The only thing fancy here is that I don’t want to serialize the Social Security number:

[System.Serializable]
public class Individual
{
    private string m_FirstName;
    private string m_LastName;
    private int m_SocialSecurityNumber; 

    public string FirstName
    {
        get { return m_FirstName; }
        set { m_FirstName = value; }
    } 

    public string LastName
    {
        get { return m_LastName; }
        set { m_LastName = value; }
    } 

    [System.Xml.Serialization.XmlIgnore]
    public int SocialSecurityNumber
    {
        get { return m_SocialSecurityNumber; }
        set { m_SocialSecurityNumber = value; }
    } 

    public Individual()
    {
    }
    public Individual(string firstName, string lastName)
    {
        m_FirstName = firstName;
        m_LastName = lastName;
    }
}

What is the DataContractSerializer?

The System.Runtime.Serialization.DataContractSerializer is new in .Net 3.0 and was designed for contract-first development and speed.  Specifically it was brought in to be used by Wcf, but can be used for general serialization as well. Using the DataContractSerializer isn’t that much different than using the XmlSerializer.  There are a few more options, but the only real key difference is that you use a WriteObject() method to serialize instead of a Serialize() method and a ReadObject() method to deserialize instead of a Deserialize() method.  It works with the same types of streams, so you can write to memory, files, etc.

DataContractSerializer dataContractSerializer =
    new DataContractSerializer(typeof(MyType)); 

// Serialize from an object to a stream
dataContractSerializer.WriteObject(stream, myInstanceOfMyType); 

// Deserialize from a stream to an object
myInstanceOfMyType = (MyType)dataContractSerializer.ReadObject(stream);

One thing to note: before you can use the DataContactSeriliazer, you must include a reference to System.Runtime.Serialization.  mscorelib gives you some parts of System.Runtime.Serialization, but you must include this reference to get the DataContactSeriliazer and the associated attributes.

image

Again, not just any object can be serialized.  It supports a number of the base types in .Net and most custom types.  One nice advantage that the DataContractSerializer has over the XmlSerializer is that it understands the SerializableAttribute and classes built for the XmlSerializer or ISerializable.  So if your class is declared with an DataContactAttribute and it contains a type that uses the SerializableAttibute, all will be well.  Unlike the XmlSerializer though you must define either the SerializableAttribute or the DataContractAttributeon the class in order for it to be serializable by the DataContractSerializer.

The DataContactSerializer implements an “opt-in” approach.  The basically means that you have to explicitly say what will be serialized by adding the DataMemeberAttribute to it.  The nice thing about this is that this attribute can be applied to fields and well as properties, you can set it on any access modified (private, protected, etc) not just public, and you can use it on properties that do not have a “set”.  However if you label a property that doesn’t have a “set”, then you can only serialize that property.  You won’t be able to deserialize it since it has no idea how to set the property.  This also means you cant use it for communication over Wcf.  But you can still use a “private set” to ensure that your model is clean.  However, you cannot specify that properties should be xml attributes and control other more complex things about how the xml will look.  It hurts not having this flexibility, but because of this rigidness, the format is highly predictable and the serializer can make some big optimizations.  The DataContractSerializer can serialize and deserialize about 10% faster than the XmlSerializer.  This can be pretty significant if you are working with a lot of data.

There are really only 2 attributes to use in your class:

  1. System.Runtime.Serialization.DataContactAttribute: Declares that the class is serializable and allows you to specify the namespace and name to serialize it as.  This is similar to a combination of the SerializableAttribute and XmlRootAttribute in the XmlSerializer. The following properties are supported on the attribute:
    1. Name: Gets or sets the name of the data contract for the type.
    2. Namespace: Gets or sets the namespace for the data contract for the type.
    3. TypeId:When implemented in a derived class, gets a unique identifier for this Attribute.
  2. System.Runtime.Serialization.DataMemberAttribute: This is used to declare a property or a field to be serialized.  This can work with any access modifier.  The following properties are supported on the attribute:
    1. EmitDefauleValue: Gets or sets a value that specifies whether to serialize the default value for a field or property being serialized.
    2. IsRequired: Gets or sets a value that instructs the serialization engine that the member must be present when reading or deserializing.
    3. Name: Gets or sets a data member name.
    4. Order: Gets or sets the order of serialization and deserialization of a member.  This can be pretty powerful if you have fields that might depend on one another and you really need to define the order that the properties are serialize and deserialized in.
    5. TypeId: When implemented in a derived class, gets a unique identifier for this Attribute.

If you are going to work with the DataMemberAttribute, here is an concise post about best practices around it: http://blogs.msdn.com/drnick/archive/2008/02/22/datamember-best-practices

Below example class setup to use the DatContractSerializer.  Notice that I am explicitly setting the DataMemberAttribute on the properties I want to serialize, but not on the others.

[DataContract]
public class Individual
{
    private string m_FirstName;
    private string m_LastName;
    private int m_SocialSecurityNumber; 

    [DataMember]
    public string FirstName
    {
        get { return m_FirstName; }
        set { m_FirstName = value; }
    } 

    [DataMember]
    public string LastName
    {
        get { return m_LastName; }
        set { m_LastName = value; }
    } 

    public int SocialSecurityNumber
    {
        get { return m_SocialSecurityNumber; }
        set { m_SocialSecurityNumber = value; }
    } 

    public Individual()
    {
    }
    public Individual(string firstName, string lastName)
    {
        m_FirstName = firstName;
        m_LastName = lastName;
    }
}

 

One other important thing to talk about with the DataContractSerializer are the ServiceKnownTypeAttribute and KnownTypeAttribute attributes.  These are similar to the XmlIncludeAttribute used by the XmlSerializer.  When used in Wcf, these identify what types should be represented in the WSDL that is generated.

The KnownTypeAttribute specifies types that should be recognized by the DataContractSerializer when serializing and deserializing a type.  It is applied to a class and basically specifies what other types are used in the class.  You don’t need to specify known .Net types, but any custom classes should be added here.  This attribute can be used multiple times to identify multiple types.

[DataContract]
[KnownType(typeof(MyOtherType))]
public class MyType
{
    [DataMember]
    public MyOtherType TheOtherType;
} 

[DataContract]
public class MyOtherType
{
    [DataMember]
    public string MyValue;
}

The ServiceKnownTypeAttribute specifies known types to be used by a service when serializing or deserializing.  It is applied to a ServiceContract or to an OperationContract and specifies what types are used in the methods.  Again (like the KnownTypeAttribute), you don’t need to specify known .Net types and this attribute can be used multiple times to identify multiple types.

[ServiceContract]
[ServiceKnownType(typeof(MyType))]
[ServiceKnownType(typeof(MyOtherType))]
public interface MyService
{
    [OperationContract]
    [ServiceKnownType(typeof(YetAnotherType))]
    void MyMethod();
}

What about the NetDataContractSerializer?

I haven’t really mentioned this yet because it is just like the DataContractSerializer, but there is also a System.Runtime.Serialization.NetDataContractSerializer.  It differs from the DatContactSerializer in that it includes CLR type information in the serialized xml, whereas the DataContractSerializer does not.  So it can only work if the serializing and derserializing ends share the same CLR types.   The nice thing about this serializer is that since the CLR type information is sent around, you don’t have to implement the ServiceKnownTypeAttirbute or KnownTypeAttribute. Like the DataContractSerializer it can work serialize types that implement either the DataContractAttribute, SerializableAttribute, or ISerializable.

I don’t recommend using this serializer often.  If possible you should declare your known types explicitly for better understand of the code and of course for the greater interoperability.

Why another xml serializer?

So why the need to even create another xml serializer? The XmlSerializer has served us well over the years.  Well part of it it speed.  Since the DataContracts are faster to serialize because the structure is predictable and can be more highly optimized.  This results in about a 10% performance gain.  If you are working with pure Wcf the gain in speed is probably worth the trade off in loss of control over what the Xml is to look like.  Sometimes you might need to control what the xml looks like to get it to fit to some other schema.  If that is the case, then you will want to switch to the XmlSerializer.

There is more to the story.  Microsoft wants us think of in terms of “Contracts” with Wcf.  We often hear the term “Contract First Development”.  Some of this principal is already in play by forcing all Wcf Services to be defined in an interface (contract).  In the old days of pure WebServices, you could just tag a class as WebService and you didn’t need a separate interface or contract.  In some respects, the DataContractSerializer is pushing us down this route too.  By declaring a class as a DataContract and explictily setting the DataMembers, you are building a contract of how the class should look.  One could argue that you could do this through the Serializable attribute, however you don’t define what goes in the contract. Instead you only specify what isn’t suppose to be serialized and the serializer decides what is should serialize.  There is no way to look at the class or use reflection and really get a good feel for the data contract for the class.  While with the DataContract and DataMember attributes, you could use reflection to see exactly what the contract is.

How to change Wcf to use a different serializer?

By default Wcf uses the DataContactSerializer, so if you want to use it, you need to do nothing else.  If you want to use the XmlSerializer through, all you need to do is add the System.ServiceModel.XmlSerializerFormatAttribute to the contact interface.  The nice thing about this attribute is that it can be applied to the entire service contract, or just to an operation contract.  So you could keep the entire service as a whole using the DataContractSerializer, but only the methods you chose to use the XmlSerializer.

[ServiceContract]
[XmlSerializerFormat]
public interface MyService
{
    [OperationContract]
    [XmlSerializerFormat]
    void MyMethod();
}

You can also set the service to use the XmlSerilizer by default, but specify which methods use the DataContractSerializer with the help of the System.ServiceModel.DataContractFormatAttribute:

[ServiceContract]
[XmlSerializerFormat]
public interface MyService
{
    [OperationContract]
    [DataContractFormat]
    void MyMethod();
}

 

Now what about changing to use the NetDataContractSerializer.  Or what if I want to use a different serializer or create my own? In order to do this you need to create a custom operation behavior using the IOperationBehavior interface and the Attribute class.

Here is an example of a custom operation behavior written to use the NetDataContractSerialier.  You could use this, build your own, or modify it to work with a different serializer.

public class NetDataContractFormatAttribute : Attribute, IOperationBehavior
{
    public void AddBindingParameters(OperationDescription description, BindingParameterCollection parameters)
    {
    } 

    public void ApplyClientBehavior(OperationDescription description, ClientOperation proxy)
    {
        ReplaceDataContractSerializerOperationBehavior(description);
    } 

    public void ApplyDispatchBehavior(OperationDescription description, DispatchOperation dispatch)
    {
        ReplaceDataContractSerializerOperationBehavior(description);
    }
    public void Validate(OperationDescription description)
    {
    } 

    private static void ReplaceDataContractSerializerOperationBehavior (OperationDescription description)
    {
        DataContractSerializerOperationBehavior dcs = description.Behaviors.Find<DataContractSerializerOperationBehavior>(); 

        if (dcs != null)
            description.Behaviors.Remove(dcs); 

        description.Behaviors.Add(new NetDataContractSerializerOperationBehavior(description));
    } 

    public class NetDataContractSerializerOperationBehavior : DataContractSerializerOperationBehavior
    {
        private static NetDataContractSerializer serializer = new NetDataContractSerializer(); 

        public NetDataContractSerializerOperationBehavior(OperationDescription operationDescription) : base(operationDescription) { } 

        public override XmlObjectSerializer CreateSerializer(Type type, string name, string ns, IList<Type> knownTypes)
        {
            return NetDataContractSerializerOperationBehavior.serializer;
        } 

        public override XmlObjectSerializer CreateSerializer(Type type, XmlDictionaryString name, XmlDictionaryString ns, IList<Type> knownTypes)
        {
            return NetDataContractSerializerOperationBehavior.serializer;
        }
    }
}Once you have this you can just mark up your service like before using the new attribute:

[ServiceContract]
[NetDataContractSerializerFormat]
public interface MyService
{
    [OperationContract]
    void MyMethod();
}

Once you have this you can just mark up your service like before using the new attribute:

[ServiceContract]
[NetDataContractSerializerFormat]
public interface MyService
{
    [OperationContract]
    void MyMethod();
}

When to use which serializer?

For Wcf, you should prefer to use the DataContractSerializer.  If you need full control over how the xml looks though, you should go back to the XmlSerializer.   If you are doing general serialization, it is up to you, but I would weigh out the advantages and disadvantages.  I would still prefer the DataContractSerializer for the same reasons I prefer it for Wcf.  I do not recommend using the NetDataContractSerializer unless you have to.  You can lose too much interoperability and its not as descriptive.

If you need some custom xml serializer, by all means go ahead and implement it.  Wcf supports any serializer you can throw at it.  Just be careful not to “reinvent the wheel”.  The XmlSerializer is very configurable and may suit your needs. If that doesn’t work, then ISerializable gives you full control.

kick it on DotNetKicks.com

Posted in .Net, Wcf | 21 Comments »

Unity and Enterprise Library 4.0 Release Plans

Posted by Dan Rigsby on 28th February 2008

As a big fan of Microsoft Enterprise Library and out of my shear excitement for Unity, I had to post this:

http://blogs.msdn.com/agile/archive/2008/02/27/entlib-unity-roadmap.aspx

  • March 15 – Unity 1.0 release
  • March 15 – Enterprise Library 4.0 CTP (includes new features of WMI2 support, ability to provide your own cache manager, and other enhancements to the application blocks based on the community feedback (listed here); note, this CTP will not include integration of blocks with Unity, just an update of OB1 to OB2)
  • mid-end April – Enterprise Library 4.0 release (includes all of the above + integration with Unity).
  •  

    I cant wait for March 15th!  Beware the Ides of March!

    Posted in .Net, Design Patterns | 1 Comment »

    Wcf Binding Comparision List and Supported Features (Reference)

    Posted by Dan Rigsby on 19th January 2008

    I have been working pretty heavily with Wcf over the last couple of weeks and really dived into understanding the ABC’s (Addressing, Binding and Contracts) of Wcf. If you dont already know, Addressing and Contracts are very straight forward. An Address is the uri string and the contract is the name of the interface that the endpoint implements. Binding is a quite a bit more difficult to understand and get right. There are a number of different binding, configuration settings, and behaviors to wrap your arms around. I put together a little “Cheatsheet” reference to help me understand each binding and when to use each. This data is primarily taken from http://msdn2.microsoft.com/en-us/library/ms731092.aspx with quite a bit of additions.

    Name (Config Name) [Schemas] Transport Message Encoding Message Version Interop Security Session Tx Flow Duplex
    BasicHttpBinding
    (basicHttpBinding)
    [http, https]
    HTTP/HTTPS

    Text

    SOAP 1.1

    Basic Profile 1.1 None, Transport, Message, Mixed N
    A binding that is suitable for communicating with WS-Basic Profile conformant Web services like ASP.NET Web services (ASMX)-based services.
    WSHttpBinding
    (wsHttpBinding,
    webHttpBinding)
    [http, https]
    HTTP/HTTPS Text, MTOM

    SOAP 1.2, WS-A 1.0

    WS None, Transport, Message, Mixed None, Transport, Reliable Session No, Yes (WS-AT) N
    A secure and interoperable binding that is suitable for non-duplex service contracts.
    WS2007HttpBinding
    (ws2007HttpBinding)
    [http, https]
    HTTP/HTTPS Text, MTOM SOAP 1.2, WS-A 1.0 WS-Security, WS-Trust, WS-SC, WS-SP None, Transport, Message, Mixed None, Transport, Reliable Session No, Yes (WS-AT) N
    WSDualHttpBinding
    (wsDualHttpBinding)
    [http]
    HTTP Text, MTOM

    SOAP 1.2, WS-A 1.0

    WS None, Message Reliable Session No, Yes (WS-AT) Y
    A secure and interoperable binding that is suitable for duplex service contracts or communication through SOAP intermediaries.
    WSFederationHttpBinding
    (wsFederationHttpBinding)
    [http, https]
    HTTP/HTTPS Text, MTOM

    SOAP 1.2, WS-A 1.0

    WS-Federation None, Message, Mixed None, Reliable Session No, Yes (WS-AT) N
    A secure and interoperable binding that supports the WS-Federation protocol, enabling organizations that are in a federation to efficiently authenticate and authorize users.
    WS2007FederationHttpBinding
    (ws2007FederationHttpBinding)
    [http, https]
    HTTP/HTTPS Text, MTOM

    SOAP 1.2, WS-A 1.0

    WS-Federation None, Message, Mixed None, Reliable Session No, Yes (WS-AT) N
    A secure and interoperable binding that derives from WS2007HttpBinding and supports federated security.
    NetTcpBinding
    (netTcpBinding)
    [net.tcp]
    TCP Binary

    SOAP 1.2

    .Net None, Transport, Message, Mixed Transport, Reliable Session No, Yes (OleTx) Y
    A secure and optimized binding suitable for cross-machine communication between WCF applications.
    NetPeerTcpBinding
    (netPeerTcpBinding)
    [net.p2p]
    P2P Binary

    SOAP 1.2

    Peer None, Transport, Message, Mixed Y
    A binding that enables secure, multi-machine communication.
    NetNamedPipeBinding
    (netNamedPipeBinding)
    [net.pipe]
    Named Pipe (IPC) Binary

    SOAP 1.2

    .Net None, Transport None, Transport No, Yes (OleTx) Y
    A secure, reliable, optimized binding that is suitable for on-machine communication between WCF applications.
    NetMsmqBinding
    (netMsmqBinding)
    [net.msmq]
    MSMQ Binary

    SOAP 1.2

    .Net None, Transport, Message, Both No, Yes (OleTx) N
    A queued binding that is suitable for cross-machine communication between WCF applications.
    MsmqIntegrationBinding
    (msmqIntegrationBinding)
    MSMQ * MSMQ None, Transport No, Yes N
    A binding that is suitable for cross-machine communication between a WCF application and existing MSMQ applications.

    *Doesn’t use a WCF message encoding – instead it lets you choose a pre-WCF serialization format
    Notes: Items in bold are the defaults for features that have multiple values. “–“ = No Support
    Abbreviations: WS-SC = WS-SecureConversation, WS-SP = WS-SecurityPolicy, WS-A = WS-Addressing, WS-AT = WS-AtomicTransaction, OleTx = OleTransactions

    Feature Description
    Name The name of the binding.
    Config Name The name of the binding used in configuration such as app.config or web.config.
    Scheme The supported Uri schemes.
    Transport The supported types of message transport (similar to Providers in Remoting).
    Message Encoding The supported types of message encoding.
    Message Version The supported message versions.
    Interop Names the protocol or technology with which the binding ensures interoperation.
    Security Specifies how the channel is secured:

    • None: The SOAP message is not secured and the client is not authenticated.
    • Transport: Security requirements are satisfied at the transport layer.
    • Message: Security requirements are satisfied at the message layer.
    • Mixed: This security mode is known as TransportWithMessageCredentials. It handles credentials at the message level, and integrity and confidentiality requirements are satisfied by the transport layer.
    • Both: Both message level and transport level security are used. This ability is unique to the NetMsmqBinding.
    Session Specifies whether this binding supports session contracts.
    Transaction Flow Specifies whether transactions are enabled and the transaction flow type in ().
    Duplex Specifies whether duplex contracts are supported. Note this feature requires support for Sessions in the binding.

    Posted in .Net, Wcf | 6 Comments »

    Enterprise Library 4.0 Product Backlog Available

    Posted by Dan Rigsby on 9th January 2008

    It looks like the Patterns and Practices team at Microsoft has exposed the product backlog for Enterprise Library 4.0 out on codeplex.  The major new item is the Dependency Injection Application Block (DIAB) which is geared up as a more complete alternative to Spring.Net, StructureMap, Castle Windsor, and other dependency injection frameworks.  The nice thing about this is that the base implementation of DIAB can be swapped out with one of the other engines to allow a lot more flexibility. It will  support for containers and both declarative and imperative configuration.  Jeremy Miller gives a much better introduction to DIAB than I ever could. It will be interesting to watch the progress they make with this and what will happen to ObjectBuilder which is already a “lightweight” dependency injection framework that is used in Enterprise Library and the Composite UI Application Block (CAB). We use EntLib 3.1 and CAB extensively, so we have a vested interest in this.

    Here are a few other items in the list that I am interested in:

    1. Provide extensibility points for Caching Block to allow alternate caching implementations (including distributed cache providers) to be plugged in. The objective here is NOT to replace the ASP.NET caching but to provide more choices.
    2. Improve performance of the Logging Block by optimizing text formatter (lazy formatting in case of the local logger, and eager formatting in case of the remote logger).
    3. Provide more descriptive error messages.
    4. LAB: allow finer-grained local filters in the config tool.
    5. Hands-on Labs: Validation Block, Policy Injection Block, Dependency Injection Block.
    6. Allow to run multiple rulesets in Validation block.

    Posted in .Net, Design Patterns | No Comments »

    XsltTransformer: Transforming an xml string with an xslt string

    Posted by Dan Rigsby on 21st December 2007

    There are many times when I have xml and xslt as strings and need the transformed data as a string.  I put together a utility class to take care of this.

    /// <summary>
    /// Transforms the specified xml string using the specified xslt string.
    /// </summary>
    /// <param name="xml">The xml string to transform.</param>
    /// <param name="xslt">The xslt string to transform with.</param>
    /// <returns>The transformed xml string.</returns>
    public static string Transform(
        string xml,
        string xslt
        )
    {
        string output = String.Empty;
        StringWriter stringWriter = null;
        XmlTextWriter xmlWriter = null;
        XmlDocument inputDocument = new XmlDocument();
        XmlDocument xsltDocument = new XmlDocument();
        System.Xml.Xsl.XslCompiledTransform xslCompiledTransformer = null;
    
        try
        {
            // Create Xml Document
            inputDocument.LoadXml(xml);
    
            // Create XsltDocument
            xsltDocument.LoadXml(xslt);
    
            stringWriter = new StringWriter();
            xmlWriter = new XmlTextWriter(stringWriter);
    
            // Apply the generated text stylesheet. 
        #if DEBUG
            xslCompiledTransformer =
                new System.Xml.Xsl.XslCompiledTransform(true);
        #else
            xslCompiledTransformer =
                new System.Xml.Xsl.XslCompiledTransform(false);
        #endif
            xslCompiledTransformer.Load(xsltDocument);
            xslCompiledTransformer.Transform(inputDocument, xmlWriter);
    
            // Generate the output Xml
            output = stringWriter.GetStringBuilder().ToString();
        }
        finally
        {
            if (xmlWriter != null)
            {
                xmlWriter.Close();
            }
    
            if (stringWriter != null)
            {
                stringWriter.Dispose();
            }
    
            if (xslCompiledTransformer != null)
            {
                xslCompiledTransformer.TemporaryFiles.Delete();
            }
        }
    
        return output;
    }

     

    A couple of things of note:

    1. When I first started using this, I had this running in memory and it would transform over 100 times an hour.  We had a variety of stylesheets, and the xml was almost always different.  If we didn’t make a call to TemporaryFiles.Delete(), then these temporary files would be kept and overtime this resulted in a lot of useless files.  This seems like a bug to me that this files aren’t cleaned up by default, but I am sure there is some clever reason for this.  It may depend on how you are implementing it.  I do like having the flexibility of deciding whether or not to keep them though.  You can read more about these options on the MSDN page for XsltCompiledTransform.
    2. I had thought of making the XsltCompiledTransform a static variable, but depending on how this method is used, I didn’t want to always have this loaded in memory.  If you make use of this code, you may decide to do this.

    Posted in .Net, xslt | No Comments »

    ReadOnlyController Codeproject Published

    Posted by Dan Rigsby on 19th December 2007

    I finally got around to publishing an article on codeproject.  I chose the ReadOnlyController as its a fairly simple concept, is an excellent demonstration of how to use the IExtenderProvider, and would be a small enough project to get up on codeproject and learn the ropes.  I have created projects on codeplex before.  Codeplex is very nice, but is meant for projects.  Single components like the ReadOnlyController are better suited for codeproject.

    The ReadOnlyController is a Component so that can be dropped on a form in design mode and implements IExtenderProvider so that it can extend the properties on controls on the form. Controls that have either a Readonly or Enabled property can be extended to enable control from the ReadOnly Controller. See the screenshot below for how this might look in the designer:

    ReadOnlyController

    Link:
    http://www.codeproject.com/KB/cs/ReadOnlyController.aspx

    Posted in .Net, Common Libraries | No Comments »

    Missing static generic alternatives in Enum class?

    Posted by Dan Rigsby on 16th December 2007

    I ran into an issue earlier this week while working with a generic class where one of the template parameters would represent a possible enum value.  (Basically we have different enum lists representing different actions). You cant use a “where” clause for the enum class.  So how would take a string or an int and cast it back to the type of enum defined in the template parameter? I had thought the static Enum class would provide new methods such as Enum.ToObject<T> and Enum.Parse<T> to match the non-generic methods, but they weren’t there.  My needs here were pretty specific, but I soon realized that every time I cast an into to an enum I had to cast the result of Enum.ToObject(int) to the enum type.  Why wouldn’t they have implemented generic methods for these common task?  Generics were built for stuff like this.

    Here is a basic EnumUtilities class I built to work around this issue and to assist with enum casting in the future:

    using System;
    namespace ININ.Common
    {
        /// <summary>   
        /// Utilities to assist with enums.   
        /// </summary>   
        public static class EnumUtilities
        {
            /// <summary>       
            /// Parses the enum.       
            /// </summary>       
            /// <typeparam name=”T”></typeparam>       
            /// <param name=”name”>The name.</param>       
            /// <returns></returns>       
            public static T ParseEnum<T>(
                string name)
            {
                if (String.IsNullOrEmpty(name))
                {
                    throw new NullArguementException("name is null or an empty string.");
                }
                return (T)Enum.Parse(typeof(T), name);
            }        
    
            /// <summary>       
            /// Parses the enum ID to the enum type.       
            /// </summary>       
            /// <typeparam name=”T”></typeparam>       
            /// <param name=”i”>The i.</param>       
            /// <returns></returns>       
            public static T ToObject<T>(
                int i)
            {
                return (T)Enum.ToObject(typeof(T), i);
            }
        }
    }

    Posted in .Net, Common Libraries | No Comments »

    Indianapolis InstallFest 2007

    Posted by Dan Rigsby on 15th December 2007

    Last night we had an Installfest here in Indianapolis for Visual Studio 2008. This event has been in the works for a couple of months now and was made possible by our Friends and Microsoft as sort of a "mini" release event to show their appreciation for the .Net user’s groups across the country.  This took the place of our normal monthly .Net User’s meeting, but was a welcomed diversion from the standard "pizza and a speaker" format.  The evening played out as followed:

    1. The Setup – As an officer for the user’s group, I arrived early to volunteer my time helping to set things up.  I spent a lot of time making sure Guitar Hero 3 was working correctly for all the members in attendance.  I know they appreciated all the time I spent testing all of the songs to make sure the disk wasn’t corrupt.
    2. The Sign-In – Not all of the people who registered attended, but we did have over 150 in attendance and over a third of those brought gifts for the RVT6 Toy Drive.
    3. The Wait – We were given copies of the CD at the door and a lot of people had begun the installs.  We ran cables and power strips down every isle of chairs to provider power for the attendees.  Food was serviced, but we were told to wait until the event began.
    4. Introduction – InstallFest finally began with Brad Jones and Dave Bost going over the format format for the evening and introducing Visual Studio 2008.
    5. Installs and Play Time – The major of the evening was spent eating, installing, playing games, and networking.  I ran into many old friends and spent a good portion of the evening talking.
    6. Mini-Demos – We were asked to present mini demos of features in Visual Studio 2008 or .Net 3.5.  Unfortunately I didn’t present a topic as I have been pretty busy with a project for school.  However we had a hand full of people present including two of my friends from work: Aaron Lerch and Jeff Moser.  Jeff ending up winning a Zune for his efforts, Congrats!
    7. Prizes – There were numerous prizes including 2 XBoxes, 3 Zunes, lots of games, and a pile of books.  Amazingly I didn’t win anything again.  That is a trend, but congrats to all of the winners!

    Dave Bost made it down the for the event, but Larry Clarkin missed out again.  Overall it was very enjoyable and I can’t wait for other events in the future.

    Posted in .Net, Community | 2 Comments »