Skip to content
Aug 7 10

Infragistics WinForms Controls inside of WPF Applications

by Dan

I recently tried to display a rather large amount of data in a WPF DataGrid control but found that it was rather slow. Particularly, when used with Data Binding (really the only way to display data from the grid). Response time was slow unless data was placed entirely asynchronously, which provides a delayed view of the data that is neither attractive, nor necessary. So instead I used a WinForms control from a third party library and thus attempted to embed my first WinForms control in a WPF application.

WinForms objects are embeddable in WPF applications and vice versa. To do so, you simply create the appropriate “host”, then place the controls you want in the host as the child. If you want more than one, you can just create a container like a Panel and add any children as children to the Panel.

How To Embed WinForms in WPF

First, you’ll need to add references to your project. In your WPF application you’ll need references to System.Windows.Forms. So check for it in the references under .NET. Additionally, if you are using a third party library like Infragistics for the controls you’ll need to right click on your project, select Properties, and verify that you are NOT using a Client Profile under your .NET framework version. Client Profiles are great for applications running only on local machines because they omit certain needless libraries pertaining to web code and servers. However, some third party libraries may link to those libraries and so you’ll need them in order to build your project. If you import the references for whatever third party controls but notice they are missing or namespaces won’t resolve, it’s because you are probably using the wrong .NET version or a Client Profile.

Once you are ready you can simply type the following:

WindowsFormsHost host = new WindowsFormsHost();
host.child = someControl;
// Add the host object to whatever your page happens to be
myWindowGrid.Children.Add(host);

Hosting a WinForms control in WPF

You should then be able to access the WinForms control and have programmatic access to all its fields, properties and methods as though it were a WinForms application.

Some Caveats

Namespace Conflicts

If you are trying to replace a WPF control with a WinForms control you should be aware of some gotchas. You will invariably run into namespace conflicts. When you hover the mouse over an object or method in VS2010 it will show you the return type of the object. Notice that many controls share a common name, however in WPF they are in System.Windows.Controls and in WinForms they are in System.Windows.Forms. Similarly, attributes and helpers in WPF tend to be in System.Media (like Colors, etc) but WinForms may be in System.Drawing. You’ll have to be explicit when talking about the type, especially since an event or attribute of a WPF control may not be compatible with a WinForms control (like Colors from styles and Points from MouseEvents).

Marshaling Data on the UI

As you may or may not know, you cannot update an object on a different thread than the one it which it was created. This is true of both WPF and WinForms, but the method by which you perform this marshaling is different. In WPF you perform an operation like this:

 this.myObjects.Dispatcher.Invoke(myDelegateFunction, DispatcherPriority.Normal, myParams); 

where the delegate function signifies the operation that will modify myObject. This simply tells .NET to perform the operation on a compatible thread when it is able to. The Priority specifies how quickly this can be done. You can find details on which priorities to specify on Microsoft’s official page on the DispatcherPriority.

Now, the same function can be (and must be) performed in WinForms in a slightly different way.

 if(this.myUIControl.InvokeRequired) this.myUIControl.Invoke(myDelegateFunction, myParams); 

Keep this in mind as you create your app since this will cause crashes if not done correctly. Specifically in Infragistics UltraGrid, this results in random exceptions and a big red X after a couple of updates.

For more details and clarity on Marshaling data, visit this page, which provides an excellent overview on the subject.


Aug 7 10

Asynchronous Data Binding in .NET (C#)

by Dan

Asynchronous operations are prevalent in all manner of modern systems, desktop and web applications. Doing this in .NET is relatively easy as Microsoft has provided us with a built in mechanism for binding data.

Specifically in WPF, we can perform databinding simply by providing a binding target and a binding source. The binding target is the object in which the data belongs and the source is the property which it will be placed (sort of backwards, but basically they refer to the two endpoints). I won’t write an entire article on Databinding but instead point you to MSDN’s official documentation on the subject.

Needless to say Databinding is immensely powerful and greatly simplifies how we as developers deal with code in UI space. Now from the Microsoft example, assume we have a databinding code snippet that looks like this:

 MyData myDataObject = new MyData(DateTime.Now);
  Binding myBinding = new Binding("MyDataProperty");
  myBinding.Source = myDataObject;
  myText.SetBinding(TextBlock.TextProperty, myBinding);

Then if we want to load the data asynchronously we would simply add:

 MyData myDataObject = new MyData(DateTime.Now);
  Binding myBinding = new Binding("MyDataProperty");
  myBinding.Source = myDataObject;
  myText.SetBinding(TextBlock.TextProperty, myBinding);
// Load this asynchronously
myText.IsAsync = true;

Which tells the binding to not wait for the value but instead move on with any other work while it waits for the value to come in. If you want to display a placeholder value, we can set that as well.

 MyData myDataObject = new MyData(DateTime.Now);
  Binding myBinding = new Binding("MyDataProperty");
  myBinding.Source = myDataObject;
  myText.SetBinding(TextBlock.TextProperty, myBinding);
// Load this asynchronously
myText.IsAsync = true;
myText.FallbackValue = "Loading..."

Which will initially display “Loading…” until the value is ready from the bound property. This is useful in situations where you want to load an image which may take a while but want to hold some placeholder image until it is ready (we see in many mobile applications where data loading may be unpredictable and slow).

If you want to load multiple levels of objects, you can create a PriorityBinding object which can contain multiple bindings as above, and set each individual Binding object to be asynchronous and it will load them in order as it gets them. You can find details about this on Microsoft’s PriorityBinding MSDN documentation page.

Lastly, remember that just because a value is asynchronous does not mean it is automatically loaded from a different thread. If you want to ensure that the UI thread is not held up, whichever property you are bound to must have its data dispatched from another thread or launch a thread. This will ensure that retrieving the property will take slightly long and make the UI thread run smooth (user interactions will take precedent).

Aug 4 10

Parsing XML in .NET C#

by Dan

Parsing XML can be a painful, error prone process. In the System.Xml Namespace, .NET provides a number of tools for parsing XML. However, there is a slightly less known but easier way to automatically parse XML files. .NET has a tool called xsd.exe, which allows you to generate objects which can be used to automatically serialize and deserialize from an XML file. If you have the schema (.xsd) file or any xml file for the target you want to parse, this process is relatively easy. First you generate the proxy objects, then you deserialize the target file into the object to gain access to the XML contents in an object model.

Generating XML Proxy Objects

Open the VS2010 command prompt available via start->programs->visual studio 2010-> vs2010 command prompt.

Navigate through the DOS prompt to the area containing your .xsd or .xml schema file

You simply run the command:

xsd schemafile.xsd /c

This will create a .cs file contain all the necessary partial class definitions for deserializing any xml file conforming to the schema. Now you are ready to parse any XML file.

Parsing XML through de-serialization

Now you simply de-serialize the object like so:

XmlReader r = new XmlReader(fileName);
// Set any XmlReader settings

ProxyObject o = new XmlSerializer(typeof(ProxyObject)).Deserialize(r) as ProxyObject;

Then all fields, tags, attributes are available in an object model where attributes are object fields and sub elements are arrays in parent objects (you can see the details in the generated .cs).

Aug 2 10

Functional Programming in C#: Map / Select Function

by Dan

C# has some particularly useful facilitates for functional programming built in. When operating on lists of data you can easily perform common functional programming tasks with built-in C# .NET functions, as long as the collection conforms to the IEnumerable interface.

Consider the following example which performs the map command, which applies a function on every object in a collection and returns a list with the result of each function call. This is accomplished in C# with the Select command.

            IEnumerable<double> myList = new List<double>();
            // Populate the list ...

            // Fills the list with the sqrt of all the values in myList
            IEnumerable<double> sqrtList = myList.Select<double, double>(Math.Sqrt);

You can use this as a short cut way of applying an operation on all the elements in a list. Of course you could do this in a slightly longer way by just iterating over all the elements in the list.

Jul 15 10

EVO 4G: Battery Life Review

by Dan

So I’ve had the pleasure of owning an EVO 4G for about three weeks and overall its been a good experience. Being an iPhone user for three years I’ve only known one mobile operating system. The transition was pretty easy and I found some added features like voice to text and native google integration incredibly useful. However, there is one part of the phone that is extremely disappointing, and that’s the battery life. Eventually its what made me decide to return it in favor of the iPhone 4, which had always been my second choice. Before I actually return it though, I wanted to do some controlled tests to determine exactly how long the battery lasts.

I’m not claiming to publish official benchmark the battery life on these phones. These are real, unaltered results from testing the performance of each phone. You should try to find as much information as possible before making any judgement.

UPDATE: Some time has passed since I actually did some tests and I’ve had my iPhone 4 for around 2 weeks, so I’ve updated some of these tests to reflect my new phone.

So I fully charged my EVO and performed a set of specialized tasks so I could find out how long it could last under a variety of tests. So let’s see how long the super smart phone stacks up.

Video Playback
In this test I disabled all radios on the phones, and played back the same 2 hour 320×240 video file. At no point did the phones screens dim or turn off.

As you can see, the old iPhone 3G beats the EVO in consumption by over 30% at 57% vs 91%.

Camcorder Recording
Obviously I couldn’t test this with the iPhone 3G, but iPhone 4 results are included.

Here the rate is a bit closer at 75% vs 86% in favor of the new iPhone 4.

I was going to include youtube battery benchmarks, but sadly the EVO couldn’t last more than 12 minutes on a 60 minute youtube video without freezing up the video (on a 4G connection). So rather than compare Apples to Oranges, I’ll just say that the EVO watching a normal youtube video for 12 minutes drops the battery by 27% to 83%.