Impossibility is not an option!
My blog about .Net programming, what is possible and what (sometimes) drives me crazy!

XML serialization, doubles, decimals and SQL Server

We just had a problem with data that is sent to SQL Server as a XML string.

One of the values sent to the SQL Server is defined in the C# class as a double and interpreted as a 'DECIMAL(28, 9)' on the SQL Server.

This was working so far. Just wen someone entered a quite small number (0.000013) it stopped working.

The reson: 1.3E-05 is sent to the SQL Server and it can’t interprete this.

It COULD be parsed on the SQL Server, although would involve some floting point madness that could mess up the value.

The easyest would be to change the interface, but as we use the same class in the front end of a webservice, this would lead to an incopatability in the schema.

Now, the solution we’re going to use is this:

We specify a custom XML serialization for our class and handle the double as a decimal. I know that the value ranges are diffenrent, but in our example this doesn’t matter.

See the code below:

     
    //---------------------------------------------------------
    public class FooBar : IXmlSerializable
    {
        //---- Members -----------------------------------------------------
        public decimal ADecimal { get; set; }
        public double ADouble { get; set; }

        //---------------------------------------------------------
        public virtual void WriteXml(System.Xml.XmlWriter writer)
        {
            writer.WriteElementString("ADecimal", Convert.ToString(ADecimal));
            writer.WriteElementString("ADouble", Convert.ToString(Convert.ToDecimal(ADouble)));
        }

        //---------------------------------------------------------
        public virtual void ReadXml(System.Xml.XmlReader reader)
        {
            reader.ReadStartElement();
            ADecimal = decimal.Parse(reader.ReadElementString("ADecimal"));
            ADouble = double.Parse(reader.ReadElementString("ADouble"));
            reader.ReadEndElement();
        }

        //---------------------------------------------------------
        public XmlSchema GetSchema()
        {
            throw new NotImplementedException();
        }
    }



What makes a 'good' software developer? Part 1 of x

Once in a while everyone seems to come across one of them. One of the really good developers. They seem to dream in code and while they are typing away on their keyboards, they hardly seem to think - they just now!

But how did they got to this point?

It's hard to say. Partly it is a talent, partly it is only learned. Depending on how you came into IT and specifically software development, you most probably did learn at one point in time, that software development purely is an engineering discipline. That, of course, is true to a certain extent, but this doesn't capture it all.

Software development has to follow certain rules and there are many aids to support and guide you. Although, you won't find a given solution to all of your problems in a book. Software IS an engineering practice but it should be seen a craftsmanship, like the builders of an old cathedral is seen as a craftsman. And if you look at the cathedrals all over Europe you'd notice that the builders where indeed engineers AND craftsman!

How you get there is another topic. One of the first things you should take to heart to get better:

Care about your craft!




Fluent ComboBox configuration

While refactoring an application today, I had to configure a couple of ComboBoxes programmaticaly.
To simplify this, I cam up with the following piece of code.

public class ComboboxBinder
{
//---- Members -----------------------------------------------------
private readonly ComboBox _combobox;

//---------------------------------------------------------
private ComboboxBinder(ComboBox comboBox)
{
_combobox = comboBox;
}

//---------------------------------------------------------
public static ComboboxBinder Bind(ComboBox cbo)
{
return new ComboboxBinder(cbo);
}

//---------------------------------------------------------
public ComboboxBinder DataSource(object source)
{
_combobox.DataSource = source;
return this;
}

//---------------------------------------------------------
public ComboboxBinder ViewForDataSource(DataTable table)
{
return DataSource(new DataView(table));
}
//---------------------------------------------------------
public ComboboxBinder ViewForDataSource(DataTable table, string filter)
{
return ViewForDataSource(table, filter, "");
}

//---------------------------------------------------------
public ComboboxBinder ViewForDataSource(DataTable table, string filter, string sort)
{
var view = new DataView(table);
view.RowFilter = filter;
view.Sort = sort;
return DataSource(view);
}

//---------------------------------------------------------
public ComboboxBinder DisplayMember(string member)
{
_combobox.DisplayMember = member;
return this;
}

//---------------------------------------------------------
public ComboboxBinder ValueMember(string member)
{
_combobox.ValueMember = member;
return this;
}

//---------------------------------------------------------
public ComboboxBinder SelectedValue(object value)
{
_combobox.SelectedValue = value;
return this;
}

//---------------------------------------------------------
public ComboboxBinder SelectedIndex(int index)
{
_combobox.SelectedIndex = index;
return this;
}

}




It implements a fluent interface to setup the ComboBox with a little less noisy code:

ComboboxBinder.Bind(cboType)
.ViewForDataSource(_typeTable, "", "Name")
.DisplayMember("Name")
.ValueMember("TypeID")
.SelectedIndex(1);

ComboboxBinder.Bind(cboState)
.ViewForDataSource(_stateTable)
.DisplayMember("Description")
.ValueMember("StateID")
.SelectedIndex(1);


Hopefully its useful for someone. Of course you would probably have it change it to fit your needs.

nothing impossible
roboto


Named Format Strings

As you might have seen, there has been some blogging about named format strings in the last days.

If you didn't came across it, the general idea is to use something like:
"foo '{foo}' bar: {bar}".Format(new {foo = "abc", bar= 123})

Since I already had an analog solution for this problem I thought it would be fun to run it in 'competition' with the other implementations.
After I adopted it the the same syntax (I used \{ and \} as escape sequences), a bit of optimisation and make it pass the Phil's test suite, it turned out to run quite fast.

These are the results (output slightly changed from Phil's implementation), including an ordinary string.Format with a object array in comparison:
Hanselformat took 0.21862 ms / 00:00:10.9318279
OskarFormat took 0.30212 ms / 00:00:15.1064949
JamesFormat took 0.17788 ms / 00:00:08.8948007
HenriFormat took 0.14302 ms / 00:00:07.1513749
HaackFormat took 0.1572 ms / 00:00:07.8600728
HartFormat took 0.13706 ms / 00:00:06.8530890

Mine:
RobotoFormat took 0.12632 ms / 00:00:06.3163623

Standard string.Format:
str.Format took 0.00786 ms / 00:00:00.3935486

Find my code below. If you find any bugs, please let me know!


using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace StringLib
{
    public static class RobotoFormatter
    {
        //------------------------------------------------------------------
        /// <summary>
        /// Returns a formated string.
        /// The format may contain references to properties of this object.
        /// To add properties to an output, the format is:
        /// "Random Text={PropertyName}"
        /// If you like to add the characters '{' or '}', you have to mask them
        /// with '{{'/'}}'.
        /// </summary>
        /// <param name="format"></param>
        /// <returns></returns>
        /// <exception cref="FormatException"><c>FormatException</c> in case of invalid format.</exception>
        /// <exception cref="ArgumentNullException"><c>format</c> is null.</exception>
        public static string RobotoFormat(this string format, object @object)
        {
            if (format == null) { throw new ArgumentNullException("format");}
            if (format.Trim().Length == 0) { return format; }

            Descriptor[] descriptors = GetDescriptors(format);

            string result = format;
            Descriptor descriptor;
            object descriptorValue;

            //could be done with foreach, altough 'for' could be faster.
            for (int i = 0; i < descriptors.Length; i++)
            {
                descriptor = descriptors[i];
                descriptorValue = GetDescriptorValue(@object, descriptor);
                result = result.Replace(
                    string.Concat("{", descriptor.FullDescriptor,"}"), 
                    descriptor.ValueToString(descriptorValue));
            }
            return result.Replace(@"{{", "{").Replace(@"}}", "}");
        }

        //---------------------------------------------------------
        private static object GetDescriptorValue(object @object, Descriptor descriptor)
        {
            object result = @object;
            foreach (var name in descriptor.Names)
            {
                PropertyInfo descriptionInfo = result.GetType().GetProperty(name);
                if (descriptionInfo == null)
                {
                    throw new FormatException(string.Format("No property named '{0}' found. Invalid format!", descriptor));
                }
                result = descriptionInfo.GetValue(result, null);
            }
            return result;
        }


        //------------------------------------------------------------------
        /// <summary>
        /// Function to 
        /// </summary>
        /// <param name="format"></param>
        /// <returns></returns>
        private static Descriptor[] GetDescriptors(string format)
        {
            var list = new List<Descriptor>();
            StringBuilder descriptorBuilder = new StringBuilder(format.Length);

            bool isDescriptor = false;
            char character;
            for (int i = 0; i < format.Length; i++ )
            {
                character = format[i];
                //ignore escaped opening/closing braces
                if (( character == '{' && GetNextChar(i, format) == '{' ) ||
                    ( character == '}' && GetNextChar(i, format) == '}'))
                {
                    i++;
                    continue;
                }

                if (isDescriptor || character == '{') //we found beginning
                {
                    isDescriptor = true;
                    if (character != '}')
                    {
                        if (character != '{') 
                        {
                            descriptorBuilder.Append(character);
                        }
                    }
                    else if (GetNextChar(i, format) != '}') //found an end (ignoring escaped closing)
                    {
                        var descriptor = new Descriptor(descriptorBuilder.ToString());
                        if (!list.Contains(descriptor)) { list.Add(descriptor); }

                        descriptorBuilder.Remove(0, descriptorBuilder.Length);
                        isDescriptor = false;
                    }
                }
            }
            if (isDescriptor) //found no end
            {
                throw new FormatException("No end for descriptor found. Please use {{ to encode a { in your format.");
            }
            return list.ToArray();
        }

        //---------------------------------------------------------
        private static char GetNextChar(int i, string format)
        {
            if (((i + 1) < format.Length))
            {
                return format[i + 1];
            }
            return ' ';
        }


        //---------------------------------------------------------
        /// <summary>
        /// This class encapsulates the handling of a descriptor.
        /// </summary>
        private class Descriptor : IEquatable<Descriptor>
        {
            public Descriptor(string descriptorValue)
            {
                if (descriptorValue == null) { throw new ArgumentNullException("descriptorValue");}
                if ( descriptorValue.Trim().Length == 0 ) { throw new ArgumentException("Empty descriptor not allowed.", "descriptorValue");}

                Format = string.Empty;
                FullDescriptor = descriptorValue;

                string[] values = descriptorValue.Split(':');
                if (values.Length > 0)
                {
                    Names = values[0].Split('.');
                }
                if (values.Length > 1)
                {
                    Format = values[1];
                }
            }

            //---------------------------------------------------------
            public string[] Names { get; private set; }
            public string Format { get; private set; }
            public string FullDescriptor { get; private set; }

            //---------------------------------------------------------
            public bool HasFormat
            {
                get { return !string.IsNullOrEmpty(Format); }
            }

            //---------------------------------------------------------
            public string ValueToString(object value)
            {
                return string.Format(ToFormatString(), value);
            }


            //---------------------------------------------------------
            private string ToFormatString()
            {
                string formatString = "{0}";
                if (HasFormat)
                {
                    formatString = string.Concat("{0:", Format, "}");
                }
                return formatString;
            }

            //---------------------------------------------------------
            public bool Equals(Descriptor other)
            {
                return FullDescriptor.Equals(other.FullDescriptor);
            }
        }
    }
}



Nothing Impossible
roboto

The Future Revealed

Easy deferred execution

While programming, especially in GUI applications, you may have come across the problem of actions that take too long to run them in the foreground thread (aka GUI thread).
.Net brings a couple of different possibilities to circumvent this, for example the ThreadPool, BackGroundWorker or the Dispatcher class in WPF.  What they have in common is, that they clutter up your code.

Especially, if your are trying to separate your concerns you should think of a better solution.
One possible solution could be to use a construct that separates the concern of handling the background calculation and just gives you the result when it's ready.

An interesting approach was presented before by Ayende although in a different context (NHibernate) in his article Future<TNHibernateQuery>.
The following code is an adoption of this to non-NHibernate context
You can also find the code for it here: Future.cs and a test with example usage at: FutureTest.cs.
The 'Guard' class used in the code will be the topic of a other blog post. In the mean time, you can find it here: Gard.cs

    ///<summary>
    ///Class to move a calculation of into the background (<see cref="ThreadPool"/>). 
    ///</summary>
    ///<typeparam name="TResult">Type of the result.</typeparam>
    public class Future<TResult>
    {
        //---- Members -----------------------------------------------------
        private TResult _value;
        private Exception _exception;
        private readonly IAsyncResult _asyncResult;
        private readonly ManualResetEvent _lock;
        private readonly Action<Future<TResult>> _callback;

        //---------------------------------------------------------	
        ///<summary>
        ///Create new instance and start the evaluation of the value.
        ///If an exception happens, it will be caught and exposed through the <see cref="Exception"/> property.
        ///</summary>
        ///<param name="action">Delegate to the evaluation function.</param>
        public Future(Func<TResult> action) : this(action, future => { })
        {
        }

        //---------------------------------------------------------
        ///<summary>
        ///Create new instance and start the evaluation of the value.
        ///If an exception happens, it will be caught and exposed through the <see cref="Exception"/> property.
        ///</summary>
        ///<param name="action">Delegate to the evaluation function.</param>
        ///<param name="callback">Delegate to be called after the evaluation.</param>
        public Future(Func<TResult> action, Action<Future<TResult>> callback)
        {
            Guard.Against.Null.Argument(()=>callback);

            _lock = new ManualResetEvent(false);
            _callback = callback;
            _asyncResult = action.BeginInvoke(
                asyncResult =>
                    {
                        try
                        {
                            _value = action.EndInvoke(asyncResult);
                        }
                        catch (Exception ex)
                        {
                            _exception = ex;
                        }
                        finally
                        {
                            ((ManualResetEvent)asyncResult.AsyncState).Set();
                            try
                            {
                                _callback(this);
                            }
                            catch (Exception ex)
                            {
                                Debug.Fail("Error while executing callback on future!", ex.ToString());
                            } //ignore the failed callback
                 
                        }
                    },
                _lock);
            _callback = callback;
        }

        //---------------------------------------------------------
        ///<summary>
        ///Gets state of the calculation.
        ///</summary>
        public bool IsCompleted
        {
            get { return _asyncResult.IsCompleted && _lock.WaitOne(0, false); }
        }

        //---------------------------------------------------------
        ///<summary>
        ///Calculated value. If the value is not yet calculated,
        /// the calculation will be completed synchronously.
        ///</summary>
        public TResult Value
        {
            get
            {
                if (!IsCompleted)
                {
                    _asyncResult.AsyncWaitHandle.WaitOne();
                    _lock.WaitOne();
                }
                return _value;
            }
        }

        //---------------------------------------------------------
        /// <summary>
        /// Exception that was thrown if any.
        /// </summary>
        public Exception Exception
        {
            get { return _exception; }
        }

        //---------------------------------------------------------
        /// <summary>
        /// Determines if there was an exception while executing the
        /// evaluation.
        /// </summary>
        public bool HasThrownException
        {
            get { return _exception != null; }
        }

    }


Nothing Impossible
roboto

Welcome

Welcome to my blog about .NET programming, the universe and, generally, everything!

This year has just started and I thought it is about time to start my own blog.
I'll try to document my things learned in the IT world, especially in .NET developing. Hopefully you can pick up some tricks you didn't know so far!

But first, that's about how I came to the world of IT:
I started programming roughly 10 years ago and I'm working as a .NET developer since about 5 years. It was only about a year when I started working with somewhat 'new' concepts like IoC (inversion of control) and accompanying tools like Castle Windsor. Starting with Castle, I discovered the Alt.NET 'movement'/community and thereof following along its lines. And of course, I'm trying to steadily improve my skills, nonetheless by reading through the Alt.NET Library and following its blogs (find an extract of my blogroll soon).

nothing is impossible!
Roboto