Having recently been subject to a number of rounding issues in an application, we've had to take a closer look at how rounding works in the .Net framework.

It seams that when using Math.Round(), there is an overload that allows us to specify the type of rounding that is used in the form of the MidpointRounding enumeration.

 

As the Microsoft documentation will tell you, there are two possible values we can choose from:

  • ToEven: Round to the nearest even number.
  • AwayFromZero: Round to the nearest number away from zero.

This proves to be quite interesting when you start thinking about it in a little more detail.  I was generally taught at school that you usually round up to the nearest number so that 0.5 becomes 1, -4.5 becomes for and so on.  This is not the case in .Net it would seem and I find it a little surprising that it has taken me this long to notice.

If you write a little console application in Visual Studio, you can take a look at how this works:

            Console.WriteLine(
                "Value   Default   Even   FromZero"
                );
            for (decimal myValue = -2.0M; myValue < 2.0M; myValue += 0.1M)
            {
                Console.WriteLine(String.Empty.PadLeft(35,'-'));
                Console.WriteLine(
                    "{0}   {1}   {2}   {3}",
                    myValue.ToString("0.0").PadLeft(5),
                    Math.Round(myValue, 0).ToString("00").PadLeft(7),
                    Math.Round(myValue, 0, MidpointRounding.AwayFromZero).ToString("00").PadLeft(4),
                    Math.Round(myValue, 0, MidpointRounding.ToEven).ToString("00").PadLeft(8)
                    );
            }

The following table give you an idea of how these work for some values.

Value Round to Even Round Away from Zero
0.4 0 0
0.5 0 1
1.4 1 1
1.5 2 2

 

The interesting point is that the default value for Math.Round when not specified is ToEven which is not really what I would have expected.  I was also a little intrigued to find that there is not provision of a TowardsZero value.  Having a look at Wikipedia, there are numerous methods of rounding and they give a handy list of which languages make which preference.  .Net favors what Wikipedia calls 'Round-half-even', which is MidpointRounding.RoundToEven.  It's sometimes refereed to as Banker's Rounding.

This clearly is not a massive revelation, but when you start to deal with systems that need to perform calculations and correlate the results of those calculations with other, less-precise systems you should take note of how you will be rounding as checking this out early can prevent headaches later.


Bookmark with :
Digg It! DZone StumbleUpon Technorati Reddit Del.icio.us Newsvine Furl Blinklist
A friend working at Graphico of my recently sent me some SQL that purposed to look for missing indexes in you databases.  It pretty much sat in my inbox for a while until I had time to look at it (which I have just done).

It was a great little script and proved very useful in identifying performance improving indexes that we could include in the database that we're developing.  I asked my friend where the SQL was from and he pointed me to the article in question on the MSDN site, which you can find here:

http://msdn.microsoft.com/en-us/magazine/cc135978.aspx

It really is worth a read and has some very interesting stuff in it.  Cheers for that, Paul - most useful!

Bookmark with :
Digg It! DZone StumbleUpon Technorati Reddit Del.icio.us Newsvine Furl Blinklist

Just a little note here that we noticed testing something (how it had not occurred before, I do not know).  We have a function that we were referencing from a referenced assembly that would format values to the slightly odd format being used by the ERP that we were talking too.  In  most cases it seamed to work OK, but for smaller values it didn't quite product the result we expected.

It turns out that the result of the Division functiod in BizTalk Server 2006 is a double.  The mapper being the way it is converts this to a string (assumably using .ToString()).  At least this is how it looks when I point ildasm.exe at Microsoft.BizTalk.BaseFunctoids.dll.

Now, rather simply put, I was being a fool and trying to convert this to a decimal and wondering what was going on.  I was passing what I though was a value of "0.00002" to my referenced method and expecting it to be formatted properly.  When we looked deeper in to the issue, we noticed that the value coming out was in fact "2E-05", which is how a float or a double would represent the value 0.00002.

 

Quick use of the double.TryParse() fixes this issue and off we trundle.


Worth keeping in mind, and also worth having a look at the base functoids using ildasm.exe when relying on their output.


Bookmark with :
Digg It! DZone StumbleUpon Technorati Reddit Del.icio.us Newsvine Furl Blinklist

When trying to access remote content in Silverlight, you need to add a clientaccespolicy.xml file to the root of the web server that you are trying to access.  I did this, my file looked like this:

<?xml version="1.0" encoding="utf-8" ?>
<access-policy>
    <cross-domain-access>
        <policy>
            <allow-from http-request-headers="*">
                <domain uri="*"/>
            </allow-from>
            <grant-to>
                <resource include-subpaths="true" path="/"/>
            </grant-to>
        </policy>
    </cross-domain-access>
</access-policy>

So essentially, anyone can access this.

I wrote my code to retrieve the information in a C# console app, just to test it out the WebClient as follows:

using System;
using System.IO;
using System.Net;
using System.Linq;
using System.Xml;
using System.Xml.Linq;

namespace GetBlogContentTest
{
    class Program
    {
        static void Main(string[] args)
        {
            WebClient w = new WebClient();

            string result = w.DownloadString(new Uri("http://blogs.interakting.co.uk/MainFeed.aspx"));
            
            if (!String.IsNullOrEmpty(result))
            {
                XDocument xDoc = XDocument.Parse(result, LoadOptions.SetBaseUri);

                var blogItems = from item in xDoc.Descendants("item")
                                select new ChannelItem
                                {
                                    Title = (string)item.Element("title"),
                                    Link = (string)item.Element("link"),
                                    PubDate = (DateTime)item.Element("pubDate"),
                                    SourceUrl = (string)item.Element("source").Attribute("url"),
                                    Description = (string)item.Element("description"),
                                    Author = (string)item.Element(XName.Get("creator","http://purl.org/dc/elements/1.1/"))
                                };

                foreach (ChannelItem item in blogItems)
                {
                    Console.WriteLine("Title: {0}", item.Title);
                    Console.WriteLine("Link : {0}", item.Link);
                    Console.WriteLine("SUrl : {0}", item.SourceUrl);
                    Console.WriteLine("Auth : {0}", item.Author);
                    Console.WriteLine("Date : {0}", item.PubDate);
                    Console.WriteLine("Content Length: {0}{1}", item.Description.Length, Environment.NewLine);
                }

            }
            else
            {
                Console.WriteLine("No Results Retrieved");
            }

            Console.ReadLine();
        }
    }
}

This also, worked fine.  However, when I put the same code in to my shiny new Silverlight application and run it through debug I get myself a nice little error.  The error message itself is a little bit on the ambiguous as we sometimes come to expect from technologies in their infancy.  Essentially the error I got was "Security error".  Gee, thanks for that?!

Digging a  little deeper in tot eh actual exception, we get the stack etc and the actual error (sort of):

SecurityException

at MS.Internal.InternalWebRequest.Send()
at System.Net.BrowserHttpWebRequest.BeginGetResponseImplementation()
at System.Net.BrowserHttpWebRequest.InternalBeginGetResponse(AsyncCallback callback, Object state)
at System.Net.AsyncHelper.BeginOnUI(BeginMethod beginMethod, AsyncCallback callback, Object state)
at System.Net.BrowserHttpWebRequest.BeginGetResponse(AsyncCallback callback, Object state)
at InteraktingMainFeed.Page.GetMainFeed()
at InteraktingMainFeed.Page..ctor()
at InteraktingMainFeed.App.Application_Startup(Object sender, StartupEventArgs e)
at System.Windows.CoreInvokeHandler.InvokeEventHandler(Int32 typeIndex, Delegate handlerDelegate, Object sender, Object args)
at MS.Internal.JoltHelper.FireEvent(IntPtr unmanagedObj, IntPtr unmanagedObjArgs, Int32 argsTypeIndex, String eventName)

I was trying everything to fix this until I hit upon the idea of taking Casini (Visual Studio's web server) out of the question (just in case) and setting up a virtual directory on my local IIS to server the Silverlight web app.

That actually fixes it.  I don't know why this effects the way the Silverlight app works, but it does.  It's highly frustrating and in my opinion completely under-tested.  As developers, we generally need to be able to debug our applications but there is now a nice hurdle in the way and you can't just use F5.  Basically, I'm going to have to attach to the web process to debug.  It's not the end of the world, but it would be nice if I could just debug the lazy way.

I can see that picking up Silverlight is going to have some nice little challenges along the way.


Bookmark with :
Digg It! DZone StumbleUpon Technorati Reddit Del.icio.us Newsvine Furl Blinklist

My previous post talks about learning some Silverlight and going through some of ScottGu's articles about getting started with Silverlight.  As I have been trundling through then I have started to notice one thing that is getting particularly irritating.

When you're styling up your application, you need to be very careful about typing the Setter properties correctly.  I admit, I am using Visual Studio and not Expression <insert useful variant here>, but I would still expect a little more intelligence or when editing the XAML.

Let me explain...

Consider the following XAML from my App.xaml file in Scott's article:

<Style x:Key="ThumbNailPreview" TargetType="Image">
<Setter Property="VerticleAlignment" Value="Center" />
<
Setter Property="Margin" Value="7,7,5,5" />
<
Setter Property="Height" Value="55" />
<
Setter Property="Width" Value="55" />
</
Style>

Note how (me being me), I have spelt VerticalAlignment incorrectly.  The result of this will be that the part of the XAML that uses that Style will not render correctly and seems to cause the entire application to 'white-out'.  Now, when this is a Style that is visible to us at design-time, then the design view of the XAML will go blank and we'll get some kind of indication that something is not correct.  We don't know what is incorrect and no compilation errors appear.  In which case, get someone to check your code over for you (at the end of the day, you typed it wrong and someone else will probably pick up your mistake quicker, we all know how it is ^^).

So cool, we can fix the problem - lovely.  However, if the Style is being used by a control that is in a template for data binding, the problem does not reveal itself in design view insider Visual Studio.  It lurks somewhere in a dark corner waiting for you to run your application and bind some data to it.  At which point; BLAM!, you're application pulls a whitey and the screen goes blank.  Ye then need to go back to Visual Studio and figure out what was wrong.  Again, get someone to look over your shoulder perhaps to quickly spot your blatant typo.

I'm sure Expression Whatever is very good at all this Style stuff, and I will shortly try it out, but I really was hoping for better intellisense in Visual Studio to let me know what properties I can use in setters for the Style's TargetType.  Maybe v.Next will do this?  that would be nice.


Bookmark with :
Digg It! DZone StumbleUpon Technorati Reddit Del.icio.us Newsvine Furl Blinklist