Sci Fi collector shop.

Our daughters are huge Dr Who fans, so it was only natural that we would look for a Dr Who toy for them for Christmas. Well, Hannah (our 4 year old) thinks the Adipose are wonderful. For those who don’t know, the Adipose were a creature from the last series who were made up of fat. They looked cute and Hannah nicknamed them cutibles. So, we were going to buy a soft toy Adipose for Hannah but you couldn’t find them for love or money.

Well – to cut a long story short, this site (http://www.scificollector.co.uk/) had them in stock and their customer service and helpfulness is wonderful. If you are looking for Sci Fi merchandise, you owe it to yourself to stop on by.

MoXAML 2.2 Released

Well – MoXAML 2.2 has been released, with a new Create Dependency Property command.

The Create Dependency Property command lets you create an ordinary DP or Attached DP (or readonly versions) with a minimum of effort. Better still, it provides method implementations for you as well.

Selecting the menu (from inside the code editor window) brings up a dialog to enter the core information that you need to create the DP. When you enter the default value, you need to put it in “exactly” as you would if you entered it manually. This means that you must put quotes around it if that’s what is expected by the datatype.

The Create Dependency Property window

When you choose Create, the relevant code gets added into the class.

So I won a prize.

I won third prize on Community Credit, of a USB flash drive lighter. It’s so cool.

If you’re geeky in any way, and contribute to a blog or any other way, sign up to Community Credit – it’s a fantastic site run by one of the coolest guys on the planet. If you want to know where Silverlight gets its name, it’s named after David Silverlight – the guy behind Community Credit and half a dozen other great net resources.



Bulk loading in ObservableCollection.

Today, in Code Project, a poster asked a question about the best way to insert multiple items in ObservableCollection as a bulk insert. The poster wondered why it was taking so long to add records doing an Add for each item in the collection. Now, in several of the .NET collections, there’s an AddRange method that allows you to add multiple items in “one hit”, so why isn’t there one in ObservableCollection? Well, part of the reason seems to be that this goes outside what you would use an ObservableCollection for. In other words, it’s not aimed at adding multiple items, it’s aimed at monitoring small changes.

So, what makes ObservableCollection unsuitable for large scale inserts? Well, the primary reason lies in the fact that an Add operation fires off a CollectionChanged event – it’s this event that is contributing to a large part of the slowdown. Fortunately, there is a way to get round this limitation, and it lies in the wonderful world of inheritance.

The following class is based on an ObservableCollection, and adds a new method (AddRange) that adds the items in quickly by suppressing the CollectionChanged event until the load has finished. (It doesn’t implement a RemoveRange method, but it would follow a similar pattern). Simple tests showed that this ran 3 times faster than the ordinary methods.

public class RangeObservableCollection<T> : ObservableCollection<T>
{
  private bool _suppressNotification = false;

  protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
  {
    if (!_suppressNotification)
      base.OnCollectionChanged(e);
  }

  public void AddRange(IEnumerable<T> list)
  {
    if (list == null)
      throw new ArgumentNullException("list");

    _suppressNotification = true;

    foreach (T item in list)
    {
      Add(item);
    }
    _suppressNotification = false;
    OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
  }
}

Anyway, I hope this helps you out.

Still lovin’ WPF

In a previous  post I looked at why WPF was something to really take a look at. I posted a bare bones WPF page that just contained a status bar. In this post, I’d like to show how to spruce the WPF up with just a little bit of effort (and hopefully to demonstrate why I really like it).

Anyway, without further ado, here is the updated class:

<Window x:Class="WorkforcePF.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Main Window" Height="450" Width="600">
    <Window.Resources>
        <LinearGradientBrush x:Key="MyBlueGradientBrush" EndPoint="0,1" StartPoint="0,0">
            <GradientStop Color="#FFE3EFFF" Offset="0"/>
            <GradientStop Color="#FFD4E5FC" Offset="0.2"/>
            <GradientStop Color="#FFB3CFF5" Offset="0.6"/>
            <GradientStop Color="#FF89B3ED" Offset="1"/>
        </LinearGradientBrush>
    </Window.Resources>
    <DockPanel>
        <StatusBar Name="statusBar1" Background="{StaticResource MyBlueGradientBrush}"  
            Height="20" VerticalAlignment="Bottom" DockPanel.Dock="Bottom">
            <StatusBar.ItemsPanel>
                <ItemsPanelTemplate>
                    <Grid>
                        <Grid.RowDefinitions>
                            <RowDefinition Height="*"/>
                        </Grid.RowDefinitions>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="4*" />
                            <ColumnDefinition Width="*" />
                        </Grid.ColumnDefinitions>
                    </Grid>
                </ItemsPanelTemplate>
            </StatusBar.ItemsPanel>
            <StatusBarItem>Ready</StatusBarItem>
            <StatusBarItem Grid.Column="1">
                <TextBlock TextAlignment="Right">Set</TextBlock>
            </StatusBarItem>
        </StatusBar>
    </DockPanel>
</Window>

As you can see, we have declared a style (similar to the way you think of styles in CSS). The background of the statusbar is set to this style and, lo-and-behold, the status bar now has a nice blue gradient. In the next post, we’ll look at adding extra elements and see how the styling can help it to stand out more. 

Help me – I’m a user.

I need help. I’m a user – I admit it. I love using the using statement in C# (I’m not talking about the one that’s equivalent to the #include statement). Imagine my surprise that some people haven’t heard of this wonderful, wonderful keyword.

So what does it actually do? Well, you can think of it as automatically calling Dispose on a disposable object. Effectively, it translates into a try/finally block where Dispose is called automatically in the finally section. So:

using (SqlConnection conn = new SqlConnection())
{
 // Do something...
}

translates into

SqlConnection conn = null;
try
{
  conn = new SqlConnection();
  // Do something..
}
finally
{
  if (conn != null && conn is IDisposable)
    ((IDisposable)conn).Dispose();
  
}

It’s perfectly possible to nest using blocks, and the compiler will ensure that Dispose is called in the correct fashion. So, if a class has a Dispose method, you should really consider wrapping it in a using(…) block.

Warning – If the class you are referencing in the using statement doesn’t implement IDisposable then you can’t do this.

Now, did you know that you can alias namespaces in a using statement? It’s true – if you don’t want to put in that StreamWriter is in the System.IO namespace all over your code and you are in the midst of classname conflicts, it’s a simple matter to put something like the following in your code:

using io = System.IO;

Then, elsewhere in your code you can use:

using (io.StreamWriter sw = new io.StreamWriter(@"c:\dev.txt"))
{
}

Note the “clever” use of the two different using types.

Config Files and Dlls.

Well – A request recently came up on CodeProject asking how to associate a config file with a DLL and then use that configuration file. Like me you would think that this would be an easy thing to do, and that it would be taken care of for you automatically. Unfortunately, it would seem that this isn’t the case – it’s easy enough to do, but you have to do it yourself. One way to do it would be to use XML to read the configuration file directly and then deal with it from there, but it turns out that there is another way that allows you to use the ConfigurationManager directly. To do this, you need to load the application into a separate application domain and then use remoting to access it. This does give you the ability to load plugins with their own config file and isolate them from the main process just in case they are a bit naughty.

Here’s a quick overview of the process – suppose you have a config file for your plugin Dll that contains the following settings:

<appSettings>
  <add key="PluginName" value="My Funky Plugin" />
  <add key="RequiredVersion" value="2.1" />
<appSettings>

Your Dll class may implement the following interface:

public interface IPluginConfiguration
{
  string PluginName { get ; }
  string RequiredVersion { get ; }
} 
public class MyPlugin : IPluginConfiguration
{
  public string PluginName
  {
    get
    {
      return ConfigurationManager.AppSettings["PluginName"];
    }
  }
  public string RequiredVersion
  {
    get
    {
      return ConfigurationManager.AppSettings["RequiredVersion"];
    }
  }
}

Now, in your calling application you could do the following:

private IPluginConfiguration _config;
public void ActivatePlugin(string configFile, string domainName)
{ 
  AppDomainSetup setup = new AppDomainSetup(); 
  setup.ConfigurationFile = configFile; 
  AppDomain domain = AppDomain.CreateDomain(domainName, null, setup); 
 
  _config = (IPluginConfiguration)domain.CreateInstanceAndUnwrap("MyDll", "MyDll.MyDllClass");
  Console.WriteLine("Name {0}", _config.PluginName);
}

There you go – you can now refer to the localised config file. It’s that simple.

CodeProject MVPs

Well, I’ve just been made a CodeProject MVP. This is a great honour for me as I’m among some illustrious company here. There are some truly amazing people in this list, and I guess I’m just there to make the coffee for them.

Let me offer my congratulations to all of the other MVPs and to all of the Microsoft MVPs. You guys and girls really are the best. Thanks also to Chris Maunder and his fantastic team for making CodeProject my second home, it’s really amazing what you’ve accomplished over the last year.

Finally, thanks to everybody who’s posted a question that I could answer or posted a piece of crap that I can pour scorn on. I appreciate it.

Microsoft Synchronisation Framework

Microsoft is soon to be releasing their Synchronisation Framework. To some people, it’s Microsoft’s answer to Google Gears, but I would have to disagree with them. Simply assessing the two technologies as being like for like misses some fairly fundamental points.

  1.  Google Gears is aimed at extending Internet applications onto the desktop. In other words, you can run some fairly sophisticated applications in a browser and have them interact as though they are desktop based. I say appear here because they run in some fairly tight restrictions, such as they are sandboxed. Plus, there is a certain lack of control for the user – where is their data stored, offline, online or some weird combination of the two? Effectively, you can think of Gears as being local storage for web applications.
  2. Sync Framework is designed to work the other way round. It’s a desktop based technology so it can run from the desktop up to the server.
  3. Sync Framework extends from synchronising items such as folders, emails, databases or pretty much anything else you can think of.

In this example, you can see how easy it is to synchronize file changes.

public void SyncFiles(SyncId sync, SyncId destinationId, string sourceRoot, string destRoot, 
  FileSyncScopeFilter filter, FileSyncOptions options 
{ 
  using (FileSyncProvider source = new FileSyncProvider(sync, sourceRoot, 
      filter, options)) 
  { 
    using (FileSyncProvider destination = FileSyncProvider(destinationId, destRoot, 
       filter, options)) 
    { 
      destination.AppliedChange += new EventHandler<AppliedChangeEventArgs>(OnApplyChange); 
      SyncAgent agent = new SyncAgent(); 
      agent.LocalProvider = source; 
      agent.RemoteProvider = destination; 
      agent.Direction = SyncDirection.Upload; 
      agent.Synchronize(); 
    } 
  } 
}  public void OnApplyChange(object sender, AppliedChangeEventArgs args) 
{ 
  if (args.ChangeType == ChangeType.Create) 
    Console.WriteLine("The file {0} has been moved to {1}", 
      args.OldFilePath, args.NewFilePath); 
}

As you can see, synchronising the files is very simple indeed. This level of functionality is available for database content as well. I look forward to its release.