Converting Float/Single To Network Order And Back In C#

I’ve seen a few posts & threads around the Internet about network order (aka big-endian) and floating point values in C#. First – all binary values are affected by the underlying architecture – this includes floating point values. It’s akin to Hebrew – all the words are written right-to-left, not just some. Now that we’ve cleared that up, I’m sure you’re wondering just how we reverse the ‘endianness’ of floats given that IPAddress only lets you convert ints.

A 32bit int is merely 32 bits of data. We just label it as an ‘int’ and always interpret it thus. What we need to do, is take a 32bit float and pretend it’s an int, get C# to convert it, then send it down the network pipe. The receiver can then fix the endianness and read it as a float. I’ve written some code that does just that:

/// <summary>
/// Convert a float to network order
/// </summary>
/// <param name="host">Float to convert</param>
/// <returns>Float in network order</returns>
public static byte[] HostToNetworkOrder(float host)
    byte[] bytes = BitConverter.GetBytes(host);

    if (BitConverter.IsLittleEndian)

    return bytes;

/// <summary>
/// Convert a float to host order
/// </summary>
/// <param name="network">Float to convert</param>
/// <returns>Float in host order</returns>
public static float NetworkToHostOrder(int network)
    byte[] bytes = BitConverter.GetBytes(network);

    if (BitConverter.IsLittleEndian)

    return BitConverter.ToSingle(bytes, 0);

Remember Network Order is always big-endian. .NET itself can be big-endian or little-endian depending on the underlying architecture. For this reason we always check if we even need to perform a conversion by checking if we’re running on a little-endian system. As an aside Java is always big-endian, regardless of the underlying architecture it’s running on.

Posted by Dan in C#, Guides, 1 comment

Notify Property Weaver

I’ve found MVVM to require somewhat excessive amounts of boilerplate code, and as far as I’m concerned if you have a lot of boilerplate (aka. repeated) code then you’re doing it wrong. There’s a few articles out there on using a little IL weaving to automatically provide notifications for the INotifyPropertyChanged interface. This dramatically reduces the amount of boilerplate you have to write, and dramatically increases readability. Simon Cropp has released the best solution by far – a NuGet package that you can integrate into your app and forget about.

The solution works with Silverlight 3.5 and .NET 3.5 onwards. Most importantly it works well with Windows Phone 7 – something many other solutions don’t always work particularly well with. The solution even works automatically with dependencies – so if one property changes as a result of another changing, the notifications will automatically be fired for both properties. Very, very clever.

Go give it a go!

Posted by Dan in C#, Windows Phone, 1 comment

Isolated Storage and Multithreading

The documentation is a little weak on thread safety when it comes to Isolated Storage, with just a little message on the subject: “Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.”.

What I’ve found is this: Reading files from Isolated Storage is fine from multiple threads at the same time – obviously if a thread is saving the file then things are a little murkier.

However, writing files is not thread safe. Do not attempt to write two different files at the same time to Isolated Storage, you’ll get an exception sooner or later.

My fix is a little messy, I have a global lock object I use whenever I want to write to Isolated Storage; this means I can only ever save one file at a time.

Posted by Dan in Windows Phone, 0 comments

Deployment Failed – The parameter is incorrect

In your output window you may find something like:

Deploying C:\Users\Username\Documents\Visual Studio 2010\Projects\MyApp\MyApp\Bin\Debug\MyApp.xap…
Deployment of application to device failed.
The parameter is incorrect.

The problem is probably due to the ApplicationIcon.png or Background.png files. These files must be actual files within the project – they can’t be linked to.

Another problem can be an incorrectly formatted WMAppManifest.xml file. Create a dummy project so you can compare your manifest file to the freshly created correct manifest. Pay particular attention to the Genre (must be ‘apps.normal’) and the IconPath and BackgroundImageURI values. Also make sure the DefaultTask’s ‘NavigationPage’ is set correctly.

Posted by Dan in Windows Phone, 1 comment

ID_CAP_LOCATION ‘Location Services’ Incorrectly Detected With WP7Contrib

I had an issue where my app would incorrectly report ‘location services’ when attempting to submit for certification. The problem turned out to be two classes in WP7Contrib using the Microsoft.Phone.Controls.Maps and System.Device.Location namespaces. When the capability detection tool runs, it checks for any use of a namespace, not just methods that actually check the user’s location. Unfortunately you can’t override it in the WMAppManifest.xml file – which begs the question of why even have the flags there if all they do is increase the chances of an exception.

Anyway, to fix the problem you need to comment out two classes in WP7Contrib.Common. In ‘Serialization’ are ‘SerializeGeoCoordinate’ and ‘SerializeLocationRect’. Comment out these classes in their entirety and re-build both WP7Contrib.Common and your app. Your app should no longer be incorrectly detected as using location services.

Posted by Dan in Windows Phone, 0 comments

Global ProgressBar in WP7

I quite like to have a global Performance Progress Bar in my Windows Phone 7 apps so the user has a consistent frame of reference when I’m interacting with web services. The requirements are simple, a progress bar that appears on all pages without any special requirements (ie. no custom controls, special code snippets, etc.). It should be managed in one place, and be easy to extend. Fortunately the extreme flexibility Silverlight offers makes this a doddle:

First add the following style to your App.xaml file:

<Style x:Key="mainFrameStyle" TargetType="phone:PhoneApplicationFrame">
    <Setter Property="Template">
            <ControlTemplate TargetType="phone:PhoneApplicationFrame">
                <Border x:Name="ClientArea"
                        BorderBrush="{TemplateBinding BorderBrush}"
                        BorderThickness="{TemplateBinding BorderThickness}"
                        Background="{TemplateBinding Background}"
                        HorizontalAlignment="{TemplateBinding HorizontalAlignment}"
                        VerticalAlignment="{TemplateBinding VerticalAlignment}">
                            Foreground="{StaticResource PhoneAccentBrush}"
                                ContentTemplate="{TemplateBinding ContentTemplate}"
                                Content="{TemplateBinding Content}"
                                HorizontalAlignment="{TemplateBinding HorizontalAlignment}"
                                HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}"
                                VerticalAlignment="{TemplateBinding VerticalAlignment}"
                                VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}"
                                Margin="{TemplateBinding Padding}">

Next go into the code behind, and add the following variable to the top of the class:

private PerformanceProgressBar _globalProgressBar = null;

Next add the following methods to the bottom the App class:

private void globalProgressBar_Loaded(object sender, RoutedEventArgs e)
    _globalProgressBar = sender as PerformanceProgressBar;

public void ShowProgressBar()
    if (_globalProgressBar != null)
        _globalProgressBar.Visibility = Visibility.Visible;

public void HideProgressBar()
    if (_globalProgressBar != null)
        _globalProgressBar.Visibility = Visibility.Collapsed;

Now find the InitializePhoneApplication() method, and amend the RootFrame instantiation code to the following:

RootFrame = new PhoneApplicationFrame()
    Style = (Style)Resources["mainFrameStyle"]

And you’re done! You can call the progress bar like so:


You can download the sample project here for your reference.

Update: This method for displaying a global ProgressBar doesn’t always play well with the WP7 Toolkit Transitions. However, I would highly recommend using the WP7Contrib Transitions anyway (they work well with the global ProgressBar too). I’ve created a 3-part guide on the transitions here.

Posted by Dan in C#, Guides, Windows Phone, 3 comments