Sunday, June 05, 2016

Simple WPF app using Task and Await with .NET 4.5

Here is a simple example showing how to create background tasks in a WPF app with .NET 4.5 and above. This is so much easier than the old BackgroundWorker approach.

<Window x:Class="TestAsyncTasks.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:TestAsyncTasks"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
 <Grid Margin="4">
  <Grid.RowDefinitions>
   <RowDefinition Height="Auto"></RowDefinition>
   <RowDefinition Height="*"></RowDefinition>
  </Grid.RowDefinitions>
  <StackPanel Grid.Row="0" Orientation="Horizontal">
   <Button x:Name="ButtonStart" Content="Start" Click="Start_Click" Padding="4"/>
   <Button x:Name="ButtonCancel" Content="Cancel" Click="Cancel_Click" Padding="4"/>
  </StackPanel>
  <TextBox Grid.Row="1" x:Name="Label1"></TextBox>
 </Grid>
</Window>
 
 
 
 
 
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
 
namespace TestAsyncTasks
 {
 /// <summary>
 /// Interaction logic for MainWindow.xaml
 /// </summary>
 public partial class MainWindow : Window
  {
  public MainWindow()
   {
   InitializeComponent();
   }
 
 
  // To allow background task to be cancelled with cts.Cancel()   
  CancellationTokenSource cts;
 
 
  private async void Start_Click(object sender, RoutedEventArgs e)
   {
   // Disable button so it can't be clicked again until finished  
   ButtonStart.IsEnabled = false;
   Label1.Text = "Start\r\n";
 
   // Setup the function to be called with updates     
   var progressUpdate = new Progress<int>(ReportProgressOnUIThread);
 
   // Create a new CancellationTokenSource and optionally set a time 
   // when the task will automatically cancel if it has not already 
   // finished.              
   int AutoCancelAfterMS = 50000;
   cts = new CancellationTokenSource(AutoCancelAfterMS);
 
   // Must be in Try/Catch to trap the OperationCanceledException  
   try
    {
    int loopTo = 10;
    int result = await MyBackgroundTaskAsync(loopTo, progressUpdate, cts.Token);
 
    // This code does not run until MyBackgroundTaskAsync finishes 
    Label1.Text += $"Final result : {result}\r\n";
    }
   catch (OperationCanceledException ex)
    {
    // Do stuff to handle the cancellation exception    
    Label1.Text +=  "CANCELLED\r\n";
    }
   catch (Exception ex)
    {
    //Do stuff to handle other exceptions       
    Label1.Text += $"Exception : {ex.Message}\r\n";
    }
 
   // Reenable Start button           
   ButtonStart.IsEnabled = true;
   Label1.Text += "Finished\r\n";
   }
 
 
  private void Cancel_Click(object sender, RoutedEventArgs e)
   {
   cts.Cancel();
   }
 
 
  async Task<int> MyBackgroundTaskAsync(int DataFromParent, IProgress<int> progress, CancellationToken ct)
   {
   int result = await Task.Run<int>(async () =>
    {
    for (int n=0; n< DataFromParent; n++)
     {
     //You cannot do this because it's running on a non UI thread
     // Label1.Text += $"{n} I don't work!\r\n";
 
     // Throw OperationCanceledException if cts.Cancel() called 
     ct.ThrowIfCancellationRequested();
 
     // Report progress back to UI thread      
     progress.Report(n);
 
     // Do the slow things in the background     
     await SlowStuff();
     }
 
    // result gets this value which is returned as final result 
    return 42;
    }, ct);
 
   return result;
   }
 
 
  async Task SlowStuff()
   {
   // Simulate some slow code. This runs on a background thread.  
   await Task.Delay(1000);
   }
 
 
  void ReportProgressOnUIThread (int value)
   {
   // This runs on the UI thread so it can update the WPF controls 
   Label1.Text += value.ToString() + "\r\n";
   }
  }
 }
 

Tuesday, November 10, 2015

Dell PremierColor Display Splitter on XPS15 9550

I've been setting up a Dell XPS15-9550 today. It comes with Windows 10 and the most awful Dell addin you have ever seen. I normally use Dell because they refrain from adding too much crapware or useless third party apps. However, this addin, enabled by default, is awful. It adds a popup menu whenever you try and drag a window (or dialog box or popup borderless window) to reposition it on the screen. It's totally unnecessary as Windows 10 already includes a perfectly good "Windows Snap" feature. The popup window is always "in the way" and when you release the mouse the window then flies off to an illogical place on the screen. Truly awful UI design.
 
Finally I've worked out how to stop it. It turns out it's a feature of "Dell PremierColor". To disable this right click on the "Dell PremierColor" icon in the notification area and select "Disable Display Splitter".
 
Why oh why are you including this enabled by default? Crazy. Please ensure it is disabled by default ASAP at it is confusing and totally unnecessary.

Wednesday, October 21, 2015

Getting field names from anonymous types using WPF DataGrid

Often it is useful to use a bit of LINQ to prepare data for display in a WPF control. Here is a very simple example. The WPF window contains a DataGrid used to display the data.

<Window x:Class="DCView.Window15"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:DCView"
        mc:Ignorable="d"
        Title="Window15" Height="300" Width="300" Loaded="Window_Loaded">
    <Grid>
        <DataGrid x:Name="DataGrid1" AutoGenerateColumns="False" SelectionChanged="DataGrid1_SelectionChanged">
            <DataGrid.Columns>
                <DataGridTextColumn Header="Number" Binding="{Binding NumberX1}" />
                <DataGridTextColumn Header="Number x 10" Binding="{Binding NumberX10}" />
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</Window>

The data might be prepared for display with a bit of LINQ. A new anonymous type is created using field names that are then used in the WPF control bindings.

private void Window_Loaded(object sender, RoutedEventArgs e)
 {
 List<int> data = Enumerable.Range(1, 10).ToList();
 
 var query = from d in data
      select new { NumberX1 = d, NumberX10 = d * 10 };
 
 DataGrid1.ItemsSource = query;
 }

The problem comes when you respond to selection changed events. How do you get to the fields in the anonymous type. You could create a new class instead of using the anonymous type but the advantage of LINQ is it is quick and easy.

private void DataGrid1_SelectionChanged(object sender, SelectionChangedEventArgs e)
 {
 dynamic dynamictype1 = DataGrid1.SelectedItem;
 int number = dynamictype1.NumberX10;
 
 Title = number.ToString();
 }

The problem is DataGrid1.SelectedItem returns an object and you can't cast it to an anonymous type. To solve the problem you can use a bit of dynamic black magic to get to the fields in the anonymous type. The example above shows how to use dynamic to get to the anonymous fields. There is no Visual Studio Smart Completion to help but as long as the field names match it will work.

Saturday, February 07, 2015

Changing the rear light cluster on 2013 VW Sharan (VW part VAG 7N0945096G)

A Cambridge cyclist managed to smash the rear light cluster on our car on Thursday night (thanks for riding off without having the courtesy to stop!). A new one is just £73 and really quite easy to fit yourself once you know this little trick.
 
The 12V power socket slides down to reveal a single screw that holds the light cluster in place. Press the top of the 12V socket  panel and slide it downwards. 
 
Using a 11mm socket set simply unscrew the central white nut which holds the light cluster in place. Once the light cluster is unscrewed unclip the power cable and replace the light unit. Total time about 5 minutes.
 
Sorry for a slightly random blog post. Please let me know if it was helpful to you!
 
 

Thursday, September 11, 2014

The Ultimate Times Table Excel Spreadsheet!

It's that time of year again. The kids are back to school and it's time for them to learn their times tables. Please find below an Excel spreadsheet that you can use to print out a sheet of random times tables (multiplications and divisions).

To use the spreadsheet simply select which times tables should be included from the yellow cells on the first tab.

Then switch to the "Random Multiplication" or "Random Division" tab and print. Job done!
 

Wednesday, November 13, 2013

No Windows Easy Transfer on Windows 8.1

I have a new PC Windows 8.1 laptop and need to transfer the 600Gb of files from my old laptop which is also running 8.1. Frustratingly I've discovered that Windows Easy Transfer in 8.1 no longer allows machine to machine transfer of files! Apparently you are supposed to copy everything to and from SkyDrive. Well 600Gb would take months over my ADSL and I've only got 100Gb on my SkyDrive account! It seems a crazy solution to remove this feature however I've found a solution. I found an old Windows 8.0 machine and copied the whole c:\Windows\System32\MigWiz folder to the two 8.1 laptops. You can then simply run the 8.0 migwiz.exe on the old and new laptops. I'm pleased to report that the Windows 8.0 version runs fine on 8.1 and successfully copies over the files.

I really think Microsoft should put the file transfer option back in. It would also be helpful if people sold USB3 Easy Transfer cables to speed up the transfer time.

Wednesday, October 09, 2013

MessageBox.Show does not work on Windows 7 Embedded

I have the world's simplest C# Winform application. A Form with a single button. Here is the entire app.

private void button1_Click(object sender, EventArgs e)
{MessageBox.Show("Hello World", "Button Click Event");
}
Amazingly on Windows 7 Embedded the MessageBox does not display. It works on every other non-embedded version of Windows.

It turns out that Windows 7 Embedded has an option to automatically click the default button on any MessageBox. See http://msdn.microsoft.com/en-us/library/aa940743(v=winembedded.5).aspx for more details.

Strange but true!






 

Thursday, September 12, 2013

Dial up VPN connections fail following Win 8 to Win 8.1 RTM upgrade

I had a strange problem yesterday. I have several dial-up VPN connections that I use daily. With Windows 8 these were working fine. I upgraded the machine from Win 8 to Win 8.1 with the RTM bits. Following the upgrade none of the dial up VPN connections would work. They all reported Error 720 : A Connection to the remote computer could not be established. Other Windows 8 machines on the same network could connect to identical servers without any problem. In the end I found that rebooting the ADSL router (the one the client machines were connected to) fixed the problem. I've no idea why all the Windows 8 machines could connect but the Windows 8.1 machine refused until the router was restarted. If you come across the same problem it might be worth trying a router reboot. Let me know if it works for you.

Andrew

Wednesday, September 11, 2013

Get Libraries back in Windows 8.1

Really annoyingly the Libraries feature in File Explorer seems to be turned off when you upgrade to Windows 8.1. To turn them back on Right click in the space between folders and select "Show Libraries".

Thursday, June 13, 2013

Are you a Manager or a Leader?

Are you a manager or a leader?
  1. The manager has subordinates; the leader has followers.
  2. The manager does things right; the leader does the right thing.
  3. The manager administers; the leader continually innovates.
  4. The manager is a copy; the leader is an original.
  5. The manager maintains; the leader develops.
  6. The manager focuses on systems and structure; the leader focuses on innovation.
  7. The manager relies on control; the leader inspires trust.
  8. The manager has a short-range view; the leader has a long-range perspective.
  9. The manager asks how and when; the leader asks what and why.
  10. The manager has his or her eye always on the bottom line; the leaders eye is on the horizon.
  11. The manager imitates; the leader originates.
  12. The manager accepts the status quo; the leader challenges it.
  13. The manager is the classic good soldier; the leader is his or her own person.
  14. The manager seeks group consensus for each decision; the leader makes decisions independently and regardless of the opinion of others.
  15. The manager assembles teams of those, like themselves, to advise on and validate every decision, leaders decide for themselves without external influence.
  16. The manager acts on expert advice; the leader has the courage to act against an expert’s advice.
  17. The manager knows the cost of everything, the leader knows the value of everything.
  18. The manager asks for a task to be performed, the leader shows the best way to do it.
  19. The manager always has someone else to blame for every mistake, the leader learns from his own mistakes.
  20. A leader takes people where they don’t necessarily want to go but ought to be.
  21. When the leader is finished with his work, the people say it happened naturally.
  22. Leaders are not team players, they feel no need to function as a group.
  23. The manager climbs the corporate ladder quickly, leaders don’t use ladders to climb.
  24. The person at the top of the org chart is rarely its true leader.
  25. Managers spend most of their time thinking they are leaders by virtue of their position.
  26. Leaders don't have all the answers whilst managers believe they do.
  27. Managers can be managed themselves, leaders can't be easily led or managed.
  28. Leaders 'begin with the end in mind.' Managers 'begin with the beginning in mind'.
  29. Leadership is freedom of action. Management is working within set boundaries.
  30. Leadership cannot be outsourced or delegated, management can.
  31. Leaders persevere until the goal is reached, managers abandon projects because they see only on the bottom line.
  32. Managers seek continuity, Leaders seeks change.
  33. Managers focus on goals for improvement. The Leader focuses on goals of innovation.
  34. Management's power is based on position or authority; Leadership power is based on personal influence and trust.
  35. The manager demonstrates skill in technical competence but the Leader demonstrates skill in selling the vision.
  36. The manager demonstrates skill in administration. A Leader demonstrates skill in dealing with ambiguity.
  37. The manager demonstrates skill in supervision. A Leader demonstrates skill in persuasion.
  38. The manager diligently seeks legal agreement at each stage of a project. A leader proceeds much more quickly by personal agreement based on trust.
  39. You manage things, you lead people.
  40. Leadership has no performance metrics, management does.
  41. Managers manage, so by nature are natural followers. Leaders lead.
  42. Management is a career. Leadership is a calling.
  43. Managers focus on the bottom line; leaders focus on adding value.
  44. Managers minimise todays costs, leaders maximise future value.
  45. Managers solve problems sequentially - step by step, leaders solve problems quicker by working in parallel.
  46. Managers take a salary, leaders work to change the world.
  47. A managers social identity is defined by title and position, a leaders identity by how he's changed the world.
  48. Without followers, there is no leader … there is just one person with a goal or idea.
  49. Managers prefer process, leaders prefer agility.
  50. The manager is SAD, the leader is MAD. SAD = Same as we've Always Done. MAD = Makes A Difference

Tuesday, August 28, 2012

Installing NVIDIA drivers on 64bit Windows 8

I upgraded a Sony laptop from Windows 7 to Windows 8 but the upgrade did not detect the Nvidia graphics chipset. I grabbed the latest Windows 8 64bit Nvidia driver from http://www.laptopvideo2go.com/ but the installer failed. It turns out that 64 bit Windows 8 will not install a driver unless it’s signed. You can disable signature checking by :

  • Windows Key + C to bring up charms menu
  • Click “Settings”
  • Click “Change PC Settings”
  • Click “General”
  • Under Advanced Start-up click the “Restart Now” button
  • Click “Troubleshoot”
  • Click “Advanced Options”
  • Click “Start-up Settings”
  • Click “Restart” button
  • Press option 7 – Disable driver signature enforcement
  • You can now install your un-signed 64bit driver

No DVD after upgrading Windows 7 to Windows 8

I upgraded my Windows 7 laptop to Windows 8 RTM but the DVD player refused to work. It's a MATSHITA BD-CMB UJ141EF drive in a Toshiba laptop. It was showing a yellow exclamation mark in Device Manager which reported the following error "Windows cannot start this hardware device because its configuration information (in the registry) is incomplete or damaged. (Code 19)". Deleting and re-scanning in Device Manager made no difference.

SOLUTION:

I noticed a service called "TOSHIBA Optical Disk Drive Service" which was presumably installed as part of the original Windows 7 setup. I used "System Configuration" to stop this service and the drive now works correctly in Windows 8.

Sunday, August 19, 2012

Getting CRM2011 Outlook Client running on Windows 8

I upgraded my Windows 7 machine to Windows 8 and found a problem with CRM2011. I upgraded the Outlook Client to UR10 but still had problems. There are two things you need to do

  1. Ensure Windows Identity Framework 3.5 is installed (this is now a 'feature' of Windows 8 and can be enabled from "Turn Windows Features on or off" from Programs and Features.
  2. Ensure you are using your full Domain username when entering the account details in the CRM connection dialog. I was originally using my email address to login. For some reason that does not work and you need to use the full domain username. You can find the full domain username from System>Administration>Users> Select a user >General>Account Information.
It's the second point that seems critical on Windows 8.

Sunday, April 15, 2012

Programming with Scratch

Inspired by the launch of the Raspberry Pi computer (http://www.raspberrypi.org/) I went into my daughter’s school last month to teach the key stage 2 kids some games programming with Scratch. See more here ( http://www.barnabasoley.cambs.sch.uk/Our+School/Golden+Time ). Just waiting for some Pi's to arrive and we can make our own games console!

I was introduced to computing by soldering together ZX80 kits when I was about their age. I think it’s critical for the UK to get a new generation of kids into creating content rather than just consuming it. I hope the Raspberry Pi will be as influential as the BBC Micro was for me and my generation.

Thursday, December 08, 2011

Celsius wins at 2011 UK IT Industry Awards

I'll be talking about how our celsius product won the Infrastructure Innovation of the Year Award at the 2011 UK IT Industry Awards at 06:20 on 12/12/2011 - BBC Radio Cambridgeshire.

Wednesday, November 30, 2011

BBC Micro is 30 years old!

A great article on the BBC Micro which is 30 years old today http://www.reghardware.com/2011/11/30/bbc_micro_model_b_30th_anniversary/. The BBC Model B was my third computer (after a self-assembled ZX80, and a ZX81 and excluding the school Research Machines RML 380Z which I exclusivly used but never really owned). Those were the days! I remember saving up all my paper round money to go on an Acorn dealer courses for the BBC Micro when I was about 17. It cost a fortune to go on the 5 day course. To their great credit Acorn never invoiced me for that course. I guess sitting at the front and asking all the questions has some benifit. Cheers Acorn!

It's strange now that I'm based in Cambridge and occasionally bump into people who were involved with Acorn / Sinclair in the old days.

Wednesday, November 16, 2011

Silicon Valley comes to Cambridge

Looking forward to meeting Reid Hoffman (Chairman of LinkedIn) and numerous other of the most exciting and disruptive Silicon Valley companies (Apple, Google...) at the Silicon Valley comes to UK event in Cambridge on Friday. Alquist are one of the showcase companies exhibiting at the event. It should be an interesting day!

Friday, November 11, 2011

UK IT Industry Awards

Great news! We won the 2011 UK IT Industry award for Infrastructure Innovation with celsius, our high definition temperature monitoring solution for data centres. The award was presented to us by TV funny man, Alexander Armstrong.

Friday, September 02, 2011

Alquist's celsius product has been named as a finalist in the British Computer Society & Computing UK IT Industry Awards 2011, in the category of Infrastructure Innovation of the Year.


The UK IT Awards are a platform for the entire profession to celebrate best practice, innovation and excellence. The shortlisted organisations have been selected based on their business success in the past 12 months, and demonstrable high levels of customer satisfaction and business benefits from the users of their products and services, with judges considering each on its merits in terms of professionalism, excellence, innovation and measurable success.

With the announcement of the finalists, David Clarke, Chief Executive Officer, BCS, The Chartered Institute for IT, said: “Congratulations to the finalists; the competition to reach this stage of our prestigious Awards is tough. Our Awards are central to our mission to recognise the innovation and professionalism of those working in IT and I’m delighted that every year we have such a variety of high quality entries. They are an excellent reflection of the impact IT has on so many aspects of our information society and the potential IT has to transform business, society and our lives.”

Abigail Waraker, Editor of Computing commented: “I would like to congratulate the finalists. The UK IT Industry Awards are rigorously judged and to be announced as a finalist is a great achievement.”

The award ceremony itself will take place in London on 10th November.
 
See http://www.ukitindustryawards.co.uk/ and Computing Magazine Article

Tuesday, December 28, 2010

Datacenter Leaders Award winner

I am delighted that our cwww.alquist.co.uk/products.aspxelsius product won the 2010 DataCenterDynamics "Future Thinking and Design Concepts" award. Presented by comedian Rory Bremner at the Lancaster London hotel on Thursday 16 December 2010. For more information please see www.datacenterdynamics.com/awards