Dan Rigsby – Coding Up Style

Developer.Speaker.Blogger

Archive for February, 2008

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 »

    Don’t Wrap Wcf Service Hosts or Clients in a Using Statement

    Posted by Dan Rigsby on 26th February 2008

    Ok, this article is going to go against everything your mother taught you about cleanly disposing of your objects.  Didn’t she always say, “Always dispose of your resources when you are finished with them.  And scope it with a using statement if you can!”?  My mother practically beat that into me growing up and she would probably disown me if she read this post.

    So at first glace I would think that this is how I might create a service and client in Wcf:

    using (ServiceHost serviceHost =
        new ServiceHost(
            typeof(MyService),
            new Uri("http://localhost:8000/MyService")))
    {
        serviceHost.Open();
    }
    
    using (ChannelFactory<IMyService> channelFactory =
        new ChannelFactory<IMyService>())
    {
        channelFactory.Open();
    }

     

    Don’t tell your mother, but I’m going to tell you right now, “Don’t do this!“. 

    Now one comment you might have is, “Dan, I don’t see a Dispose method on the ServiceHost or ChannelFactory anyway.”  Well, I’m going to give you a bonus tip. Sometimes the .Net gods change the protection level of the Dispose method so that it doesn’t show up.  Don’t believe me?  Check out the Msdn article for ServiceHost and ChannelFactory (and some other classes).  It clearly shows that they implement IDisposable, but they are marked as “private” (sometimes they mark it “protected”).  Using a “using” statement will basically treat it like the following which is legal since it implements IDisposable even though the protection level is not public:

    ServiceHost serviceHost;
    try
    {
        serviceHost =
            new ServiceHost(
                typeof(MyService),
                new Uri("http://localhost:8000/MyService")));
        serviceHost.Open();
    }
    finally
    {
        if (serviceHost != null && serviceHost is IDisposable)
        {
            ((IDisposable)serviceHost).Dispose();
        }
    }
     

    If your call to Open() on the service host fails, then the finally block will still be executed.  This results in Dispose being called. The reason this is bad is because of what the Dispose method actually does.  It tries to call Close().  Now since we failed in Open, the connection hasn’t been established, so this will throw a InvalidOperationException and a CommunicationObjectFaultedException.  This is not desirable, but these are considered “Expected Exceptions”, so they are left up to the developer to handle.  The correct way to setup the servicehost and client is to handle the “Expected Exceptions” gracefully and propagate any “Unexpected Exceptions”.

    So how should you open and close service hosts and clients?  Something like what I have below is considered “best practice”:

    ServiceHost serviceHost = null;
    try
    {
        serviceHost =
            new ServiceHost(
                typeof(MyService),
                new Uri("http://localhost:8000/MyService"));
        serviceHost.Open();
    
        // Do work...
    
        serviceHost.Close();
    }
    catch (CommunicationException)
    {
        if (serviceHost != null)
        {
            serviceHost.Abort();
        }
    }
    catch (TimeoutException)
    {
        if (serviceHost != null)
        {
            serviceHost.Abort();
        }
    }
    catch (Exception)
    {
        if (serviceHost != null)
        {
            serviceHost.Abort();
        }
        throw;
    }
    
    ChannelFactory<IMyService> channelFactory = null;
    try
    {
        channelFactory =
            new ChannelFactory<IMyService>();
        channelFactory.Open();
    
        // Do work...
    
        channelFactory.Close();
    }
    catch (CommunicationException)
    {
        if (channelFactory != null)
        {
            channelFactory.Abort();
        }
    }
    catch (TimeoutException)
    {
        if (channelFactory != null)
        {
            channelFactory.Abort();
        }
    }
    catch (Exception)
    {
        if (channelFactory != null)
        {
            channelFactory.Abort();
        }
        throw;
    }
     

    If you notice, I am catching a CommunicationException and not a CommunicationObjectFaultedException.  This is ok because it inherits from CommunicationException, so it will be caught along with any other exceptions that derive from CommunicationException.

    I’m sure you are thinking something like, “Why doesn’t dispose automatically handle this”.  Honestly that is a good question.  It’s probably part of the reason why they make the Dispose() method private.  I am sure there is a good reason, but this is not intuitive to the developer and doesn’t follow the well understood standards that we have been taught.  So remember to always open and close both your service host and clients using something similar to the mechanism show above.  This will help you gracefully handle these “expected exceptions”.

    You could even use a wrapper object to handle this for you.  Since both ServiceHost and ChannelFactory derive from CommunicationObject, you could build a wrapper around this.  The wrapper would allow you to call Close() or Dispose() with the desired exception handling and aborting.  If you wanted to do something custom when these “excepted exceptions” are thrown you would have to modify the wrapper or not use a wrapper at all.  Here is a example of a wrapper you could use:

    public class CommunicationObjectWrapper : IDisposable
    {
        private System.ServiceModel.Channels.CommunicationObject m_CommunicationObject;
    
        public System.ServiceModel.Channels.CommunicationObject CommunicationObject
        {
            get
            {
                return m_CommunicationObject;
            }
        }
    
        public CommunicationObjectWrapper(
            System.ServiceModel.Channels.CommunicationObject communicationObject)
        {
            m_CommunicationObject = communicationObject;
        }
    
        public void Close()
        {
            if (m_CommunicationObject != null)
            {
                m_CommunicationObject.Close();
            }
        }
    
        public void Dispose()
        {
            if (m_CommunicationObject != null)
            {
                try
                {
                    ((IDisposable)m_CommunicationObject).Dispose();
                }
                catch (CommunicationException)
                {
                    m_CommunicationObject.Abort();
                }
                catch (TimeoutException)
                {
                    m_CommunicationObject.Abort();
                }
                catch (Exception)
                {
                    m_CommunicationObject.Abort();
                    throw;
                }
            }
        }
    }

    These msdn articles helps explain these issues:
    http://msdn2.microsoft.com/en-us/library/aa355056.aspx
    http://msdn2.microsoft.com/en-us/library/aa354510.aspx

    Posted in Wcf | 4 Comments »

    How to Extend the Provider Model to Make It Easy to Use

    Posted by Dan Rigsby on 22nd February 2008

    The Provider Model has been around for quite awhile now and its in use all over the .Net Framework and Enterprise Library since .Net 2.0.  The provider model allows you to program against an intermediary, while the actual implementation can be defined in the app.config file.  The best example of this is a data access layer.  You might program a generic data access layer, but the actual implementation may be for Sql Server or Oracle and can be decided in the app.config file.  I have used the provider model to abstract things such as a data access layer, a geocoding service, an authentication system, etc.  Its nice to be able to just create a different implementation and swap it out in the app.config filer.

    There is a decent amount of information out there (including a recent post by Joel Ross) and there is built in support for it in System.Configuration.Provider.  However, while the tools in .Net make it possible to use the Provider Model, there is little guidance and some missing features in this namespace. This article is about how to extend the provider model to make it easier to use, and give a little insight into how it might be used.  We are going to specifically look at the following areas:

    1. ProviderBase extensions:
      1. Exposing the configuration values through the provider so they can be used later in the code
      2. Using the provider type as the default name if no name is specified
    2. How to create a ProvidersSection that allows you to specify the default provider to use
    3. ProviderCollection extensions:
      1. Add Generics support
      2. Add the ability to get an Provider by index instead of just by name
    4. How to build a generic ProviderRepository

    Note: At the bottom of this post I have zipped up all of the code and samples in this article.  The sample included is a complete working example of the basic principles outlined here.

    Definitions

    Abstract Provider: an abstract class that services as a base for your providers.  This usually contains all abstract methods and properties or overloaded methods and implementation details that can be shared by all providers.  This usually derives from ProviderBase.

    Provider:  the actual implementation of an abstract base provider.  For instance, this could be your actual SQL Server implementation of the abstract data provider.

    ProvidersSection: the configuration section used by providers in the app.config file

    ProviderCollection: a collection of providers

    ProviderRepository: a repository that abstracts the need to manually try to determine which provider to use from the app.config file and wraps up tools needed to work with provider and the entire collection of providers.

    ProviderBase Extensions

    When working with the provider model each provider is named.  This is important so that each provider in the list can be recognized from the others such as:

    <DataService defaultProvider="SqlDataProvider">
        <providers>
            <add
                name="SqlDataProvider"
                type="DataAccessLayer.SqlClient.SqlDataProvider, DataAccessLayer.SqlClient"
            />
            <add
                name="OracleDataProvider"
                type="DataAccessLayer.OleDb.OracleDataProvider, DataAccessLayer.OleDb"
            />
        </providers>
    </DataService>

     

    As you can see, each provider has a name and a type.  Here is my extended implementation of ProviderBase:

    using System;
    using System.Collections.Specialized;
    using System.Configuration;
    using System.Configuration.Provider;
    
    namespace Rigsby.Configuration.Provider
    {
        /// <summary>
        /// Provides a base implementation for the extensible provider model.
        /// </summary>
        public class ProviderBase : System.Configuration.Provider.ProviderBase
        {
            #region Private Properties
            private NameValueCollection m_Configuration = new NameValueCollection();
            private bool m_IsInitialized = false;
            private string m_Name = String.Empty;
            #endregion Private Properties
    
            #region Public Properties
            /// <summary>
            /// Gets the configuration.
            /// </summary>
            /// <value>The configuration.</value>
            public NameValueCollection Configuration
            {
                get
                {
                    return m_Configuration;
                }
            }
    
            /// <summary>
            /// Gets or sets the friendly name used to refer to the provider during configuration.
            /// </summary>
            /// <value></value>
            /// <returns>The friendly name used to refer to the provider during configuration.</returns>
            public new string Name
            {
                get
                {
                    return m_Name;
                }
                set
                {
                    m_Name = value;
                }
            }
    
            /// <summary>
            /// Gets a value indicating whether this instance is initialized.
            /// </summary>
            /// <value>
            ///     <c>true</c> if this instance is initialized; otherwise, <c>false</c>.
            /// </value>
            public bool IsInitialized
            {
                get
                {
                    return m_IsInitialized;
                }
            }
            #endregion Public Properties
    
            #region Overrides
            /// <summary>
            /// Initializes the provider.
            /// </summary>
            public void Initialize()
            {
                Initialize(String.Empty);
            }
    
            /// <summary>
            /// Initializes the provider.
            /// </summary>
            /// <param name="name">The friendly name of the provider.</param>
            public void Initialize(
                string name)
            {
                Initialize(name, new NameValueCollection());
            }
    
            /// <summary>
            /// Initializes the provider.
            /// </summary>
            /// <param name="name">The friendly name of the provider.</param>
            /// <param name="config">A collection of the name/value pairs representing the provider-specific attributes specified in the configuration for this provider.</param>
            public override void Initialize(
                string name,
                NameValueCollection config)
            {
                if (config == null)
                {
                    config = new NameValueCollection();
                }
    
                // Get default name if empty or null
                if (String.IsNullOrEmpty(name))
                {
                    if (!String.IsNullOrEmpty(m_Name))
                    {
                        name = m_Name;
                    }
                    else
                    {
                        name = this.GetType().Name;
                    }
                }
                m_Name = name;
    
                // Store configuration values
                m_Configuration.Clear();
                foreach (string key in config.Keys)
                {
                    m_Configuration.Add(key, config[key]);
                }
    
                // Call the base class's Initialize method
                base.Initialize(name, config);
    
                m_IsInitialized = true;
            }
            #endregion Overrides
        }
    }

    The default System.Configuration.Provider.ProviderBase will hide all of the configuration values after Initialize is called.  I wanted to expose this collection so that you can add in custom configuration attributes easily and access them later in your code.  The default provider base would also throw exceptions if there were any unknown attributes.  I found this to be undesirable. If I wanted to add a new attribute that only one of my providers might need, I would want to be able to add it without it on the fly without having to extend my provider and make sure it understood the attribute.  So now based on this new ProviderBase we can do things like this:

    // Configuration file
    <DataService defaultProvider="SqlDataProvider">
        <providers>
            <add
                name="SqlDataProvider"
                type="DataAccessLayer.SqlClient.SqlDataProvider, DataAccessLayer.SqlClient"
                useStoredProcedure="true"
            />
        </providers>
    </DataService>
    
    // Code
    if (provider.Configuration["useStoredProcedure"])
    {
        // handle stored procedures
    }

     

    This may not seem like much, but it can be a real time saver if you use the Provider Model a lot and need inject custom attributes.

    Creating a ProvidersSection

    In our previous example, we showed the list of providers an app.config file and the root configuration section specified a "defaultProvider" attribute.  This is an example of the custom ProvidersSection.  It’s just a generic ConfigurationSection that allows for a "defaultProvider" attribute and a collection of ProviderSettings.  You can extend this to add your own attributes, but for most purposes any custom attributes you will need will be on the provider settings themselves and not on the ProvidersSection.

    using System;
    using System.Configuration;
    
    namespace Rigsby.Configuration.Provider
    {
        /// <summary>
        /// A configuration section for a collection of providers.
        /// </summary>
        public class ProvidersSection : ConfigurationSection
        {
            private const string m_DefaultProviderProperty = "defaultProvider";
    
            /// <summary>
            /// Gets the providers.
            /// </summary>
            /// <value>The providers.</value>
            [ConfigurationProperty("providers")]
            public ProviderSettingsCollection Providers
            {
                get
                {
                    return (ProviderSettingsCollection)base["providers"];
                }
            }
    
            /// <summary>
            /// Gets or sets the default provider.
            /// </summary>
            /// <value>The default provider.</value>
            [ConfigurationProperty(m_DefaultProviderProperty, IsRequired=false)]
            public string DefaultProvider
            {
                get
                {
                    return (string)base[m_DefaultProviderProperty];
                }
                set
                {
                    base[m_DefaultProviderProperty] = value;
                }
            }
        }
    }

    ProviderCollection Extensions

    The default ProviderCollection does not contain support for generics.  This means you have to do a lot of extra casting and things aren’t strongly typed.  It is also setup to only allow retrieval of providers by name.   In some cases you need to be able to get the provider by index.  Suppose you want to setup the provider model to try to use the first provider in the list, and if that doesn’t work, then use the next provider, and so on.  If you could only get the providers by name, there is no way to easily get the next provider.  The custom ProviderCollection shown below adds generics support and the ability to retrieve a provider by index.

    using System;
    using System.Configuration;
    using System.Configuration.Provider;
    
    namespace Rigsby.Configuration.Provider
    {
        /// <summary>
        /// Represents a collection of provider objects that inherit from <see cref="ProviderBase"/>.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        public class ProviderCollection<T> : ProviderCollection
            where T : Rigsby.Configuration.Provider.ProviderBase
        {
            #region Public Properties
            /// <summary>
            /// Gets the <see cref="T:DataProvider"/> with the specified name.
            /// </summary>
            /// <value></value>
            public new T this[string name]
            {
                get
                {
                    return (T)base[name];
                }
            }
    
            /// <summary>
            /// Gets the cref="&lt;T&gt;"/> at the specified index.
            /// </summary>
            /// <value></value>
            public T this[int index]
            {
                get
                {
                    int counter = 0;
    
                    foreach(T provider in this)
                    {
                        if (counter == index)
                        {
                            return provider;
                        }
                        counter++;
                    }
    
                    return null;
                }
            }
            #endregion Public Properties
    
            #region Public Methods
            /// <summary>
            /// Adds a provider to the collection.
            /// </summary>
            /// <param name="provider">The provider to be added.</param>
            /// <permissionSet class="System.Security.permissionSet" version="1">
            ///     <IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="UnmanagedCode, ControlEvidence"/>
            /// </permissionSet>
            public override void Add(
                System.Configuration.Provider.ProviderBase provider)
            {
                if (!(provider is T))
                {
                    throw new ArgumentException(
                        String.Format("The provider is not of type {0}.", typeof(T).ToString()));
                }
    
                this.Add((T)provider);
            }
    
            /// <summary>
            /// Adds the specified provider.
            /// </summary>
            /// <param name="provider">The provider.</param>
            public void Add(
                T provider)
            {
                if (!provider.IsInitialized)
                {
                    provider.Initialize();
                }
    
                base.Add(provider);
            }
            #endregion Public Methods
        }
    }

    Creating a Generic ProviderRepository

    All of the changes listed above are extensions of the the default provider model to make it easier to use.  The ProviderRepository though is a new concept not in the default provider model, but builds on the extensions we have already talked about.  The ProviderRepository is designed to encapsulate the loading of providers from the app.config file.  It will contain the list of available providers and specify which provider should be used based on the "defaultProvider". It is a generic class that takes in the type of provider you are working with.  For most implementations you will probably be extending ProviderBase the, so you will use ProviderRepositoy<MyProviderType>.  For example if you have a custom data access layer provider you might call it DataProvider and use ProviderRepository<DataProvider>.

    In the ProviderRepository you specify the name of the configuration section to use from the app.config file. If you leave this null or empty, then it will attempt to look for a configuration section with same name as the generic provider type.  So if you created it like ProviderRepository<Rigsby.Test.DataAccessLayer>, then it will look for a configuration section named <Rigsby.Test.DataAccessLayer> in the app.config file that is a ProvidersSection.

    using System;
    using System.Configuration;
    using System.Configuration.Provider;
    using System.Collections.Generic;
    using System.Text;
    using System.Web.Configuration;
    
    namespace Rigsby.Configuration.Provider
    {
        /// <summary>
        /// Represents a repository to give access to providers.
        /// </summary>
        public class ProviderRepository<T>
            where T : ProviderBase
        {
            #region Private Properties
            private T m_Provider = null;
            private ProviderCollection<T> m_Providers = null;
            private volatile object m_SyncRoot = new object();
    
            private string m_SectionName = String.Empty;
            #endregion Private Properties
    
            #region Public Properties
            /// <summary>
            /// Gets the provider.
            /// </summary>
            /// <value>The provider.</value>
            public T Provider
            {
                get
                {
                    if (m_Provider == null && m_Providers.Count > 0)
                    {
                        m_Provider = m_Providers[0];
                    }
    
                    return m_Provider;
                }
            }
    
            /// <summary>
            /// Gets the providers.
            /// </summary>
            /// <value>The providers.</value>
            public ProviderCollection<T> Providers
            {
                get
                {
                    return m_Providers;
                }
            }
    
            /// <summary>
            /// Gets the name of the configuration section.
            /// </summary>
            /// <value>The name of the section.</value>
            public string SectionName
            {
                get
                {
                    return m_SectionName;
                }
            }
            #endregion Public Properties
    
            #region Constructors
            /// <summary>
            /// Initializes a new instance of the <see cref="ProviderRepository&lt;T&gt;"/> class.
            /// </summary>
            public ProviderRepository(
                ) : this(true)
            {
            }
    
            /// <summary>
            /// Initializes a new instance of the <see cref="ProviderRepository&lt;T&gt;"/> class.
            /// </summary>
            /// <param name="throwErrorIfUnableToLoadSection">if set to <c>true</c> [throw error if unable to load section].</param>
            public ProviderRepository(
                bool throwErrorIfUnableToLoadSection)
            {
                if (String.IsNullOrEmpty(m_SectionName))
                {
                    m_SectionName = typeof(T).ToString();
                }
    
                LoadProviders(throwErrorIfUnableToLoadSection);
            }
    
            /// <summary>
            /// Initializes a new instance of the <see cref="ProviderRepository&lt;T&gt;"/> class.
            /// </summary>
            /// <param name="sectionName">Name of the section.</param>
            public ProviderRepository(
                string sectionName) : this(sectionName, true)
            {
            }
    
            /// <summary>
            /// Initializes a new instance of the <see cref="ProviderRepository&lt;T&gt;"/> class.
            /// </summary>
            /// <param name="sectionName">Name of the section.</param>
            /// <param name="throwErrorIfUnableToLoadSection">if set to <c>true</c> [throw error if unable to load section].</param>
            public ProviderRepository(
                string sectionName,
                bool throwErrorIfUnableToLoadSection)
            {
                m_SectionName = sectionName;
                LoadProviders(throwErrorIfUnableToLoadSection);
            }
    
            /// <summary>
            /// Initializes a new instance of the <see cref="ProviderRepository&lt;T&gt;"/> class.
            /// </summary>
            /// <param name="provider">The provider.</param>
            public ProviderRepository(
                T provider)
            {
                m_Providers = new ProviderCollection<T>();
                m_Providers.Add(provider);
    
                m_Provider = provider;
            }
    
            /// <summary>
            /// Initializes a new instance of the <see cref="ProviderRepository&lt;T&gt;"/> class.
            /// </summary>
            /// <param name="providers">The providers.</param>
            public ProviderRepository(
                ProviderCollection<T> providers)
            {
                m_Providers = providers;
            }
            #endregion Constructors
    
            /// <summary>
            /// Loads the providers.
            /// </summary>
            protected virtual void LoadProviders(
                bool throwErrorIfUnableToLoadSection)
            {
                // Avoid claiming lock if providers are already loaded
                if (m_Providers == null)
                {
                    lock (m_SyncRoot)
                    {
                        // Do this again to make sure provider is still null
                        if (m_Providers == null)
                        {
                            // Get the providers
                            m_Providers = new ProviderCollection<T>();
    
                            // Get a reference to the section
                            ProvidersSection section = null;
                            try
                            {
                                section =
                                    ConfigurationManager.GetSection(m_SectionName) as ProvidersSection;
                            }
                            catch (Exception)
                            {
                                section = null;
                            }
    
                            if (section == null)
                            {
                                if (throwErrorIfUnableToLoadSection)
                                {
                                    throw new ProviderException(
                                        String.Format("Unable to load configuration section: '{0}'.",
                                            m_SectionName));
                                }
                            }
                            else
                            {
                                ProvidersHelper.InstantiateProviders(section.Providers, m_Providers, typeof(T));
    
                                if (m_Providers.Count > 0)
                                {
                                    // If there is a default provider specified, then grab it, 
                                    // else grab the first provider in the collection
                                    if (!String.IsNullOrEmpty(section.DefaultProvider))
                                    {
                                        m_Provider = (T)m_Providers[section.DefaultProvider];
                                    }
                                    else
                                    {
                                        m_Provider = m_Providers[0];
                                    }
                                }
    
                                if (throwErrorIfUnableToLoadSection)
                                {
                                    // If we have no provider, then throw an exception
                                    if (m_Provider == null)
                                    {
                                        throw new ProviderException(
                                            String.Format("Unable to load default provider for section: '{0}'.",
                                                m_SectionName));
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    Putting It All Together

    To get this all to work you just need to do the following:

    1. Create the base provider you want to use. This should derive from ProviderBase.
    2. Created at least one implementation of your base provider. This should derive from the class you made in the previous step.
    3. Setup a section in your app.config file to specify the providers.
    4. Create an instance of the ProviderRepository<> in your code that you will use to reference the provider.

    Below are examples of these 4 steps to put all of this together.

    Step 1 Example:

    public abstract class DataProvider : ProviderBase
    {
        public abstract System.Data.DataTable GetRows();
    
        public string GetConnectionString()
        {
            string connectionStringName = this.Configuration["connectionStringName"];
            if (String.IsNullOrEmpty(connectionStringName))
            {
                throw new ProviderException("Empty or missing connectionStringName");
            }
            if (WebConfigurationManager.ConnectionStrings[connectionStringName] == null)
            {
                throw new ProviderException("Missing connection string");
            }
    
            return WebConfigurationManager.ConnectionStrings
                [connectionStringName].ConnectionString;
        }
    }

     

    Step 2 Example:

    public class SqlDataProvider : DataProvider
    {
        // TODO: Implement data access layer here
    
        /// <summary>
        /// Gets the rows.
        /// </summary>
        /// <returns></returns>
        public override System.Data.DataTable GetRows()
        {
            return new System.Data.DataTable();
        }
    }

     

    Step 3 Example:

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
        <configSections>
            <section name="DataService"
                type="Rigsby.Configuration.Provider.ProvidersSection, Rigsby.Configuration.Provider"
                allowDefinition="MachineToApplication"
                restartOnExternalChanges="true" />
        </configSections>
    
        <connectionStrings>
            <add name="connectionString"
                providerName="System.Data.SqlClient"
                connectionString="Data Source=localhost;Initial Catalog=DB;UID=sa;PWD=;" />
        </connectionStrings>
    
        <DataService defaultProvider="SqlDataProvider">
            <providers>
                <add
                    name="SqlDataProvider"
                    type="Rigsby.Configuration.Provider.Sample.DataAccessLayer.SqlDataProvider,
                        Rigsby.Configuration.Provider.Sample"
                    connectionStringName="connectionString"
                    providerInvariantName="System.Data.SqlClient"
                />
            </providers>
        </DataService>
    </configuration>
     

    Step 4 Example:

    public static class Program
    {
        private static ProviderRepository<DataAccessLayer.DataProvider> m_DatabaseProviders =
            new ProviderRepository<DataAccessLayer.DataProvider>("DataService");
    
        public static void Main(string[] args)
        {
            Console.WriteLine(
                String.Format("ProviderName = '{0}'", m_DatabaseProviders.Provider.Name));
            Console.WriteLine(
                String.Format("ConnectionString = '{0}'", m_DatabaseProviders.Provider.GetConnectionString()));
    
            Console.ReadLine();
        }
    }

     

    Here is a link to the complete code and samples: http://www.danrigsby.com/files/rigsby.configuration.provider.zip

    Posted in Common Libraries, Design Patterns | No Comments »

    Xna Game Development on the Zune

    Posted by Dan Rigsby on 20th February 2008

    As a Zune30 owner X2, I just had to post about this.  Microsoft just announced that XNA Game Studio 3.0 will support building XNA games for the Zune.  I was afraid this would only be for the 2nd generation Zunes, but it looks like it will support Zune 4/8, Zune 30, and Zune 80 devices.  Some features include:

    1. Ability to write a game in XNA and target it for Zune, 360, or PC
    2. Network support for up to 8 Zunes
    3. A stripped down version of the XNA graphics API
    4. Ability to customize game background soundtracks with mp3s
    5. Ability to create real time visualization.  I am guessing this means visualization animations for music.
    6. Games are limited to 16MB for code and content though

    A preview of the new framework will be available this spring (maybe as early as April).  The full release is expected around Christmas 2008.

    Check here for more information: http://forums.xna.com/ShowThread.aspx?PostID=46553

    Posted in Zune | 1 Comment »

    How to throttle a Wcf service, help prevent DoS attacks, and maintain Wcf scalability

    Posted by Dan Rigsby on 20th February 2008

    What can you do to prevent denial of service (DoS) attacks on your Wcf services?  A DoS attack occurs when a flood of client requests come into a service and prevent legitimate requests from being made or slow down intended processing.  At the same time, you need to be careful not to stranglehold legitimate requests and activity.

    Throttling

    Throttling is one mechanism that can be used to help mitigate the load from a DoS attack.  Throttling allows you to "smooth" out the load on the server.
     
    Wcf handles throttling through the ServiceThrottlingBehavior class.  This represents a behavior that can be applied to a service.  Behaviors can be applied programmatically:
     
    ServiceHost host = new ServiceHost(
        typeof(MyContract),
        new Uri("http://localhost:8080/MyContract"));
    host.AddServiceEndpoint(
        "IMyContract",
        new WSHttpBinding(),
        "");
    System.ServiceModel.Description.ServiceThrottlingBehavior throttlingBehavior =
        new System.ServiceModel.Description.ServiceThrottlingBehavior();
    throttlingBehavior.MaxConcurrentCalls = 16;
    throttlingBehavior.MaxConcurrentInstances = Int32.MaxValue;
    throttlingBehavior.MaxConcurrentSessions = 10;
    host.Description.Behaviors.Add(throttlingBehavior);
    host.Open();
     
    or through the app.config:
     
    <system.serviceModel>
        <services>
            <service
                name="IMyContract"
                behaviorConfiguration="myContract">
                <host>
                    <baseAddresses>
                        <add baseAddress="http://localhost:8080/MyContract"/>
                    </baseAddresses>
                </host>
                <endpoint
                    name="wsHttp"
                    address=""
                    binding="wsHttpBinding"
                    contract="IMyContract">
                </endpoint>
            </service>
        </services>
        <behaviors>
            <serviceBehaviors>
                <behavior name="myContract">
                    <serviceMetadata httpGetEnabled="True" />
                    <serviceThrottling
                        maxConcurrentCalls="16"
                        maxConcurrentInstances="2147483647"
                        maxConcurrentSessions="10"/>
                </behavior>
            </serviceBehaviors>
        </behaviors>
    </system.serviceModel>
     
    There are 3 properties supported on the ServiceThrottlingBehavior:
    1. MaxConcurrentCalls (default = 16) [Per-message] The maximum number of messages that can actively be processed.  Each client channel can have one pending message that does not count against this total until the service begins to process it.  Increase this value if you want your service to be able to process a larger message load.
    2. MaxConcurrentInstances (default = Int32.Max)  The maximum number of InstanceContext objects in a service that can execute at one time.
      • What this setting translates into depends on the InstanceContextMode that is set on the ServiceBehaviorAttribute on the service.  If this is set to "PerSession", then this would represent the maximum number of sessions.  If this is set to "PerCall", then this is the maximum number of concurrent calls.  If this is set to "Single", then this value doesn’t really mean anything anymore.
      • When a message comes into the service and the maximum number of InstanceContext objects already exists, then the message goes into a wait pattern until an existing InstanceContext is closed.  This could cause a client to receive a timeout if no connection could be created in the allotted amount of time.
    3. MaxConcurrentSessions (default = 10) [Per-channel] The maximum number of sessions that a service can accept at one time.  This setting only affects "session" enabled channels, so a channel like BasicHttpBinding will not be affected.  Once this threshold is reached, no channels will not be accepted to the service.  Each listener object can have one pending channel session that does not count against this total until the service beings to process it.  Increase this value if you want to allow more than 10 concurrent sessions to be connected at any given time.
      • If you get exceptions like this, you may need to increase this value:

    "The open operation did not complete within the allotted timeout of 00:00:59.9989999. The time allotted to this operation may have been a portion of a longer timeout."


    "The socket transfer timed out after 00:00:59.9979998. You have exceeded the timeout set on your binding. The time allotted to this operation may have been a portion of a longer timeout."

    You could set all the these values to Int32.Max.  This is probably a good think when you really want to perform some load testing of the server. (This is how I discovered the usefulness of these settings)  However it is important to understand what consequences there are to doing this.

    Recommendations:

    If your InstanceContext is set to "PerCall" you should set maxConcurrentSessions and maxConcurrentCalls to the same value since each call is its own session.  You should target this value to be at least 25-30.  However you shouldn’t need to go higher than 64.

    If your InstanceContext is set to "PerSession" you should set maxConcurrentCalls to be at least 25-30.  Your maxConcurrentSessions should be the number of users you want to have concurrently connected.

    If your InstanceContext is set to "Single" you should use the same settings as "PerSession", but the maxConcurrentSessions will only apply if session support is active (this is set with the SessionMode attribute on the ServiceContractAttribute).

    Quotas

    Another potential area that is vulnerable to a DoS attack is where the client may force the server to allocate a significant amount of memory over what should be used.   To help prevent this you can use Quotas.  When a quota is exceeded a QuotaExceededException is thrown.  Without Quotas a malicious message could attempt to access all available memory can create an OutOfMemoryException, or access all available stacks to cause a StackOverflowException.  The best part of the QuotaExceededException is that the message causing it can just be discarded and the service can keep on running.  Without quotas the resulting exceptions could cause the service to terminate.

    The most useful quota to work with to mitigate DoS attacks is the maxRecievedMessageSize on the binding itself.  This setting restricts the maximum messages size so that a client can’t send messages that are too large and flood the system.  The default value is 65536 bytes.

    <bindings>
        <netTcpBinding>
            <binding name="netTcp"
                maxReceivedMessageSize="2147483647"
                maxConnections="2147483647">
                <readerQuotas
                    maxDepth="64"
                    maxStringContentLength="2147483647"
                    maxArrayLength="2147483647"
                    maxBytesPerRead="4096"
                    maxNameTableCharCount="16384"/>
            </binding>
        </netTcpBinding>
    </bindings>
     

    Other quotas exist on the ReaderQuotas property that can be used to restrict message complexity.  This can help mitigate excessive use of endpoint processing resources like CPU and memory. These are:

    1. MaxDepth (default = 32) The maximum nested node depth.
    2. MaxStringContentLength (default = 8192)  The maximum string length allowed by the reader.  You may need to increase this value if you anticipate potentially large messages.
    3. MaxArrayLength (default = 16384)  The maximum allowed array length.  How many items can be in a single array in the message.
    4. MaxBytesPerRead (default = 4096) The maximum allowed bytes returned for each read.  This is the number of bytes consumed by a single call from the reader to Read().  In practice this is used to limit the size of start tags, since a start tag must be completely buffered for the message to be processed.  This can be a common attack area.  It is recommended to keep this value at its default.
    5. MaxNameTableCharCount (default = 16384) The maximum number of characters in a table name.

    Some bindings such as NetTcpBinding offer a maxConnections property.  This setting on the client indicates the maximum number of connections to be pooled for subsequent reuse.  On the server, this setting is the maximum number of connections allowed to be pending dispatch.  The default is 10.

    Posted in Wcf | 10 Comments »

    Wcf Clients: To call Open() or not to call Open()?

    Posted by Dan Rigsby on 18th February 2008

    You could directly call Open() in a ChannelFactory<> like:

    System.ServiceModel.ChannelFactory<IContactService> factory =
        new System.ServiceModel.ChannelFactory<IContactService>(
            "netTcp");
    factory.Open();
    IContactService contactService = factory.CreateChannel();
     

    Or from a proxy like so:

    ContactService.ContactServiceClient client =
        new ContactService.ContactServiceClient();
    client.Open();
     
    However, you don’t have to explicitly call Open() on your proxy or channel from your client to the server.   You could just create the client, make your requests to the server, and never call Open() yourself. If you don’t call it, then the first request you make the the server will implicitly call Open() behind the scenes.
     
    Advantages for calling Open() explicitly:
    1. You can specify the Timeout that will be used when trying to open the connection.  If you let Open() be called implicitly then the default timeout will be used.
    2. Your initial calls to the server will be faster since you have already opened the connection.  Users expect to have to wait a couple of seconds for an application to start up, but once its up in running, it should be as fast and responsive as possible.

    Advantages for letting Open() be called implicitly:

    1. Applications start up faster.
    2. If you never make a call to the Wcf service, then you never had to create the connection and have saved resources.

    So, if you know your application will always make at least one call to the service or if there is a very good chance it will, then you should always call Open() explicitly.

    Posted in Wcf | No Comments »

    Presenation: Diving into Wcf

    Posted by Dan Rigsby on 14th February 2008

    I just completed a presentation on Wcf at the local .Net User’s Group.  This presentation was designed to give an introduction into windows communication foundation as well as to dive deep into a few areas. Topics included:

    • Everything you need to know to get started
    • How to convert webservice and remoting apps
    • Bindings
    • Message Formatting
    • Serialization
    • Duplexing
    • What new in .Net 3.5
    • ChannelFactories vs. Proxy Clients

    There were four code demonstrations:

    1. A simple Wcf service and client from scratch
    2. A more advanced Wcf Service to show off DataContracts, Message Encodings, and ClientBase<>
    3. A Duplex example of a pub/sub service
    4. A Web Programming Model Wcf Service that demonstrated the new WebGet attribute and UriTemplates to produce REST type interfaces

    Attendance was small tonight.  I guess people have Valentine’s Day plans after all.  We had about 1/2 as many people attend as usual.  However I think the presentation was well received, there were no “presentation hiccups”, and there were a number of good questions asked during and after the presentation.  For those of you not there, I think you missed out.

    Here is the entire presentation including slides, before and after projects, code snippets, notes, etc.

    http://www.danrigsby.com/files/Presenation/DivingIntoWcf.zip

    Posted in Community, Wcf | 2 Comments »

    IndyNDA on Facebook

    Posted by Dan Rigsby on 9th February 2008

    I added a Facebook group for IndyNDA.  If you are a IndyNDA member or a .Net developer in Indianapolis and want to learn more, feel free to join the group.

    Jeff Moser has also started up a feed for IndyNDA developers. Contact him if you want to be a part of this. http://feeds.feedburner.com/IndyNDABloggers

    Posted in Community | No Comments »