by Dean
8. May 2010 12:56
As .NET developers we have all implemented dictionaries. Often, its a small dictionary with strings or Guids as the key – which is simple and robust. However, sometimes we need to do something a little more ‘serious’ and implement a dictionary that has a complex key consisting of a combination of values. In this case, it is extremely important that the type we use for the key has the following characteristics: Instances of the key’s type must be immutable, as changing their state once they are added to the dictionary will most likely mean that the value they represent cannot be found The key’s type must produce a wide range of hash codes during use, so you’ll need to override the GetHashCode() method, and implement your own algorithm You must override the Equals() method of the key’s type to implement the correct equality algorithm. Also the keys type must implement IEquatable<T> for easy lookups in generic dictionaries. The keys type should ideally be a struct r...
[More]
by Dean
6. May 2010 08:08
In the MVVM world, things like message boxes (MessageBox.Show) and Dialogs (open file, save file etc), don't naturally fit. These popups are closely tied to the ‘View’ part of MVVM, but they can only really be invoked from the ‘ViewModel’ which will break the clean separation in MVVM. If you google this issue, you will find a wide range of elaborate solutions, many of which are significant engineering projects in their own right. I am a huge fan of implementing simple solutions wherever possible, as verbose code is the number one culprit in un-maintainable projects, so I was keen to find a solution that is simple, robust, elegant and doesnt break the MVVM pattern The solution I came up with, is to use generic Action and Func Delegates. OK, to illustrate my solution, I have created a new project using the ‘WPF Model-View-ViewModel Toolkit’, (http://wpf.codeplex.com/wikipage?title=WPF%20Model-View-ViewModel%20Toolkit), which installs a project template in VS2008 Here is my altered...
[More]
by Dean
27. April 2010 21:51
Many WPF applications need to handle a very large data collections – maybe the users really need a million rows in their GridView control. The way we cope with this is to ‘virtualize’ the data, and have it available to your control on an ‘as needed’ basis. Most list controls in WPF (including the standard ListView/GridView) include the concept of a ‘viewport’ under the hood. A viewport is a virtual ‘window’ on the underlying data collection, which only requires the data currently being displayed – so if your collection is a million rows, and your ‘viewport’ is only 100 rows high, then you only need 100 rows (although they must be the ‘right’ rows). In addition, if the data collection that is your DataContext implements the non-generic ‘IList’ interface, the viewport will optimize it access to the collection calling the ‘IList.this[index]’ for row enumeration rather than GetEnumerator(). This means that if we create a custom collection that implements the non-generic ‘IList’ interfac...
[More]
by Dean
26. April 2010 21:15
I’ve been playing a lot with F# lately, particularly in the area of financial option modelling, which requires quite a lot of number crunching – a perfect scenario for tinkering around in F# interactive. However, I need to get data out of my data store, and use it to create collections of records, that represent the data that I need. This was becoming a little cumbersome, so I thought I’d create a little ORM function to do the trick open System.Data.SqlClient
open Microsoft.FSharp.Reflection
let BuildData<'T> (connection:string, command:string) =
let conn = new SqlConnection(connection)
let comm = new SqlCommand(command,conn)
let recordType = typeof<'T>
let fieldCount = FSharpType.GetRecordFields(recordType).Length
conn.Open()
let db = comm.ExecuteReader()
let rec populate (reader:SqlDataReader) (l:'T list) =
match reade...
[More]
by Dean
12. April 2010 20:51
For many years, OOP abstractions and design patterns have been the cornerstones of my development methodology as a senior C# developer in investment banking. However, over the last year or so I have taken quite a shine to Microsoft’s new FP language (F#), not just because purely functional program code is concise powerful and elegant, but because the eclectic mix of functional and OOP paradigms in F# enable me to develop better, faster, stronger and more maintainable applications. In investment banking, the business has been changing fast, and being able to get production quality WPF apps onto the trader desks has been a big priority, and with F# I find myself more able to meet that challenge. The WPF design pattern ‘du jour’ is MVVM. Anyone who’s serious about enterprise-strength development in WPF would have come across this pattern and probably have used it at some point in the recent past. Detailed below is a very basic implementation where :- There is a WPF project that co...
[More]
by Dean
20. March 2010 21:28
I recently stumbled across an area of artificial intelligence programming called AIML ‘chatterbots’. These programs are interpreters for an XML based AI language called AIML. AIML and the code that processes it are the basis of the first and most famous chatterbot called A.L.I.C.E, where the founders and followers are infamous for promoting and winning the Loebner Prize in Artificial Intelligence. Among the available technologies, there are the usual suspects including implementations in PHP, Perl, Python, Java and even Pascal – but nothing in .NET On Saturday my wife (who runs her own gourmet coffee roasting business here in rural Kent – www.coffeebeanshop.co.uk) was in Germany buying a new coffee roaster, so to fill time I decided to have a go at a C# implementation, which is detailed below. Firstly, before you do anything, you need to download some AIML files, which describe how the interpreter should handle human conversation, and sets out the rules of engagement. AIML also incl...
[More]
466e1591-da09-4427-89f5-4d47cb58acfa|3|5.0
Tags:
C# | AIML
by Dean
28. February 2010 12:42
We all get clobbered at least once by memory leaks in our shiny new applications. One of the main causes of this is when objects that are expected to be garbage collected are not because we have not (or are unable) to unsubscribe them from the event handlers of longer living (static) objects. The de-facto solution is to implement Microsoft’s ‘WeakEventManager’, but it takes a lot of coding, and adds another layer of complexity to your applications. Wouldn’t it be great to do something a bit easier like: public partial class MainWindow : Window
{
private EventProxy<RoutedEventHandler> proxy = new EventProxy<RoutedEventHandler>();
public MainWindow()
{
InitializeComponent();
Loaded += WindowLoaded;
}
private void WindowLoaded(object sender, RoutedEventArgs e)
{
AddPublishers();
var customer = new ...
[More]
by Dean
3. February 2010 07:45
When I’m building prototypes in WPF or working on a GUI spike in an agile development team I often find it really unproductive to continuously switch between working in XAML (with my designer hat on), and working on the plumbing code (with my C# hat on). Wouldn't it be nice to be able to model my data in XAML, and seamlessly use it with XAML Binding expressions that’ll be valid once the ‘real’ data gets plumbed in. Well, thanks to the dynamic features in CLR v4 this is now a trivial task. Firstly lets look at the XAML – you’ll quickly see the flexibility in using this approach - <Window x:Class="DynamicWPF.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:collections="clr-namespace:System.Collections;assembly=mscorlib"
xmlns:sys="clr-namespace:System;assembly=mscorlib"...
[More]
by Dean
1. February 2010 12:22
A common problem in WPF (& Silverlight) development is when you are working with multiple threads that need to change a collection that is a binding source and implements INotifyCollectionChanged. Basically, the standard ObservableCollection<T> will only allow updates from the dispatcher thread, which means you need to write a lot of code for the worker threads to marshal changes onto the main message pump via the dispatcher. This can be a bit tedious, so I recently wrote a collection that performs all of the necessary marshalling internally, so users of this type do not have to be concerned about thread affinity issues. Also, I decided to use a ReaderWriterLock to provide thread-safety during updates to the collection. Here is my collection class: public class SafeObservable<T> : IList<T>, INotifyCollectionChanged
{
private IList<T> collection = new List<T>();
private Dispatcher dispatcher;
...
[More]
by Dean
29. January 2010 10:59
Today I was happy to sign myself up for a 6 month contract to deliver high performance WPF and Winforms GUI projects for a AAA investment bank’s ‘front-office’ trading team. The project will be very demanding and test my strong knowledge of multi-threaded WPF to the max :) This blog will therefore become more focussed on WPF, especially any interesting posts I can write on high-performance and multi-threading issues. Happy days !! Dean
6ba41d2e-ed5a-42a3-969e-d543dbeff932|0|.0
Tags:
by Dean
21. January 2010 16:25
After a desperately busy year, where many things fell to the wayside (including this blog), I have returned to the world of Silverlight and WPF blogging. I hope over the coming weeks to make regular contributions to this blog Dean
64cfc487-5b43-467b-82af-c8edce2db3c5|0|.0
Tags:
by Dean
11. February 2009 10:39
I love the fact that in Silverlight you can get all of your data onto the datagrid at the same time, rather than having to used a paged control in ASP.NET. However I’ve found that some users really want the data paging to remain, which means that I’ve got to roll may own DataGrid paging control. I know there are a few example out there, but I wanted to create a control that was a simple as possible but covered all of the major bases – so as little ‘code-behind’ as possible, and all the styling done in Blend. So this is what I came up with: Screenshot Here’s the XAML <Grid x:Name="LayoutRoot" Background="White" Width="Auto"
Height="Auto" HorizontalAlignment="Left" VerticalAlignment="Top"
Margin="10,10,10,10">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*&quo...
[More]
by Dean
6. February 2009 14:13
During the creation of a recent demo Silverlight project, I tasked myself with creating a generic (re-useable) filter control that I could use to filter rows in a Silverlight DataGrid. The control had to be lightweight, and work automatically with any object collection that the DataGrid was bound to – thus making it plug-and-play for any future uses. I’ve created a great starting point with this, by designing a set of inter-operating classes that have the following key features. The Filter control of writtem completely in Xaml, using Xaml binding syntax (good designer supprt) By virtue of point 1, it is easily modified in Blend The filter control works by creating Lambda/Linq Expression trees to perform filtering. The filter control can ustilise the DescriptionAttribute for plug-and-play. Here are a couple of screenshots: 1) No filtering 2) Adding a couple of filters, by clicking on the ‘Add New Filter’ button, setting the filter and clicking on ‘Apply All Filters...
[More]
by Dean
5. February 2009 14:58
Working in investment banking, I often get asked to create semi-functional prototypes of user interfaces, where the development methodology is all about speed and not about code-quality. Often these projects will be centred around the Silverlight DataGrid, and I want to get it up and running fast with whatever data object that needs to be used (the DataGrid will need to be bound to a collection of such objects). By default, a DataGrid for Silverlight will automatically generate columns, which is a great little feature in these scenarios, which is a great time saver – especially when the underlying object that your rows are binding to is in a state of flux. However, when automatically generating columns for your data, the column header is just set to the name of the property – which isn't going to impress the audience when you show off your prototype. A great solution I put together, is to use the ‘DescriptionAttribute’ on your data object’s properties, and have the DataGrid automat...
[More]
by Dean
31. January 2009 10:57
A contractor colleague of mine (Phil Steel) had an interesting Silverlight problem yesterday. He wanted to populate a Silverlight ComboBox with an enumeration, and implement 2-way binding to a property on his Data class (i.e. binding his property to the ‘SelectedItem’ on the ComboBox. His requirements were as follows: The solution must have full design-time support in Expression Blend The code must give the developer an opportunity to create metadata for the enumeration that can be used for ‘user friendly’ visual values in the ComboBox There must be full 2-way binding, so no need to tap into the ‘SelectionChanged’ event to update the data object. Minimal C# code, with as much as possible being re-useable ‘as is’ for any enumeration. Ok, so I googled around and only found fragments of a possible solution, so I decided to engineer one myself. The details are below Task 1 : Create reusable code that converts a .NET enumeration into a collection There are 2 c...
[More]
by Dean
25. January 2009 12:37
Some of you may have come across an issue when developing ‘fast and dirty’ demo apps in Silverlight that have a WCF backend service on the web application. When developing throwaway demo apps for clients, you need to take all of the shortcuts you can get, so I always use the ‘Add service reference’ feature of Visual Studio to add a service reference within my Silverlight app to the host ASP.NET service (not advisable for production-quality apps though). This is a great feature because as you change the service interface you can keep in sync on your Silverlight app using a single service ‘Update’ button. However, the big drawback of this approach is that the Visual Studio tool that creates the service reference hard-codes the service Uri into the generated classes. If you were just using Visual Studio then this wouldn't be a problem, but unfortunately VS and Blend use different development servers that cannot co-exist on the same TCP port, so for one of the two development environmen...
[More]
by Dean
24. January 2009 14:25
I've spent some time tracking down Silverlight oriented (or related technology) blogs so I can keep on top of the community using FeedReader on my daily train journey into London. If anyone would like to add these blog references into their own RSS reader, you can download the OPML file below Silverlight and Related Feeds (OPML File) Please let me know if I've missed anyone, and I’ll keep this file up-to-date Dean
by Dean
24. January 2009 10:37
When using the GridView in ASP.NET it is very handy to be able to include a ‘FormatString’ attribute to bound columns and the like – enabling you to display those dates, currency values, numbers etc in a more readable form. I was surprised that Silverlight or WPF doesn't offer this out of the box, and I couldn't find any ‘obvious’ answers when I googled the subject, Therefore, I created a simple IValueConverter to achieve the same result. Here's the code for the converter: namespace CBSSilverlight
{
public class FormatStringValueConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter,
CultureInfo culture)
{
if (value == null)
return string.Empty;
return !string.IsNullOrEmpty(parameter.ToString()) ? string.Format(culture,
parameter.ToString(), value) : value.ToString...
[More]
by Dean
19. January 2009 17:31
In my previous post showed how to create a lightweight collection class that can be used in expression blend enabling design-support for data bound control development. In this post, I thought I’d expand on my previous writings and actually create a sample project from beginning to end – demonstrating how easy it is to use this solution. Step 1 – Create Your Project (Programmers Job) In VS2008, create a Silverlight application project – Im going to call mine EmployeeInfo for the purpose of this blog. I also need to create my data classes, So I’m going to create 3 My generic base collection class that provides all of the test data (CollectionBase.cs) My Domain/Business object – in this example, it’s going to be a ‘person’ object that represents employee data (Person.cs) My person-specific collection class that provides a data-binding target for Expression Blend design (PersonCollection.cs) The code for CollectionBase.cs and PersonCollection.cs is available in the...
[More]
by Dean
18. January 2009 23:54
One of the big issues for me with using Expression Blend for design in conjunction with VS2008 for the hard coding, is that you need to create at least test data loading stubs in the middle tier, delivered over WCF/WS in order visualize databound controls in the Silverlight app. This means that you often need to have everything ‘working’ on the data delivery backend before you can effectively design the visual elements, otherwise you’ll be trying to work with empty ListBoxes and DataGrids etc. In order to solve this problem, I have designed a base collection class that automatically generates test data in debug builds, but loses all of that redundant functionality for efficiency and security in release builds. Without further ado – here is the code for the base class I am using for my data collections (explanations follow) public class CollectionBase<T> : ObservableCollection<T>
{
private static readonly Random rand = new Rand...
[More]
by Dean
18. January 2009 15:36
When loading large object collections in Silverlight, there is enough of a time delay so that I need some kind of animated icon that indicates a ‘loading’ state. There were many such icons used when loading data via AJAX, which are basically animated Gif’s. As Gif’s aren't supported in Silverlight, I needed to create one. I decided therefore to create a design in Expression Design, and then animate it in Blend, with a little tidying up in VS2008. Im not sure how well it’ll perform with large number of instances in a single control, but it does the trick for my needs. The code for my animated spinning logo is below. (Use the scaletransform in the grid to change the size) <Grid x:Name="LayoutRoot" Background="White">
<Grid.RenderTransform>
<ScaleTransform x:Name="SpinnerScale" ScaleX="0.5" ScaleY="0.5" />
</Grid.RenderTransform>
<Canvas RenderTransformOrigin...
[More]
by Dean
17. January 2009 16:19
This blog is under construction and will be coming soon
b90f06a8-aed0-4484-a9bc-bf99c2c7b2f3|0|.0
Tags: