My Development Blog

My Development experiences

Archive for the ‘C#’ Category

WCF Services – Dispose can cause you problems

Posted by ipwright83 on November 7, 2013

Normally when you’re working with something that implements IDisposable you should always call Dispose() on it. Unfortunately there are a whole bunch of classes that implement IDisposable implicitly. What that means is that you don’t see Dispose in intelli-sense, which makes it quite difficult to check. The general rule is if it’s going to deal with Stream/Connections/GDI/Databases there will probably be a dispose in there somewhere. The simplest way to do this is to wrap the code in a using statement to ensure that Dispose is called even if there is an error.

Once such example of this is the WCFClient. You would normally expect to write something like the following

using(PaymentPortTypeClient client = new PaymentPortTypeClient())
{
    // Do Stuff
}

Unfortunately however for WCF the base class System.ServiceBase.ClientBase can throw an Exception in Dispose if the connection failed to open for any reason. This is a bit of a pain, so instead we need to conditionally dispose depending on the connection state.

A little helper for achieving this:

 ///
/// Use the service safely such that it will correctly dispose itself upon success or failure.
///
/// The delegate to execute safely 
public static void Use<T>(UseServiceDelegate codeBlock) 
{ 
   // Ensure that the factory has been initialized 
   IClientChannel proxy = (IClientChannel)channelFactory.CreateChannel(); 
   bool success = false; 
   try 
   { 
       codeBlock((T)proxy); 
       proxy.Close(); 
       success = true; 
   } 
   finally 
   { 
       if (!success) 
       { 
           proxy.Abort(); 
       } 
   } 
}

At this point assuming you’ve placed the method in a class called Service you can use the following code to safely call the same code that Dispose would on your connection:

Service.Use<PaymentPortType>(proxy =>
{ 
   // Do Stuff
}

Posted in C# | Tagged: , | 2 Comments »

Windows 8 Style Progress Bar

Posted by ipwright83 on June 1, 2012

I recently saw a preview of Windows 8, I didn’t see very much of it but one of the things I did see really caught my eye. The new file transfer progress bar that is in use. For those of you who haven’t seen it a screenshot is included below. Not only does it report progress, but it shows you the current rate of transfer and how that has varied over time.

I wondered whether or not this was something that Microsoft would be releasing, a question on StackOverflow led to ‘maybe’, but chances are it would only be avaliable for Windows 8 anyway. I could see some real potential for this sort of feedback for the application I contribute toward at my workplace, many of the customers won’t be using Windows 8 for some time. I love writing custom tools to make my development life easier, so I thought why not write a new progress bar mimicking this behaviour?

I could have chosen to do this in WinForms and GDI. This would have been well in the realm of comfort although probably tedious ensuring things were pixel perfect. I have been trying to learn some WPF in my spare time, and one of the big problems, is coming up with small isolated projects that are interesting and achievable, I felt like this fit the bill so got started during my lunch breaks and evenings.

I originally thought that I’d just inherit from a ProgressBar and modify some visuals (I actually did do this in the end) but when I discovered I had to use templates this gave me some shivers, I struggle with the bindings still in XAML and didn’t felt like I could easily seek answers to the wrong implementation. So I started off writing a purely code based solution – ProgressGraph.cs.

Although it was fairly easy, and did seem to work, it felt like it was breaking the WPF paradigm. I hadn’t touched a piece of XAML and I’m sure it had bugs in it. I loaded up Reflector to see how ProgressBase.cs had been implemented, and extended this implementation to include the relevant Rate based information that I needed – RateBase.cs. This is a reusable class that you can build your own templates for if you so wish. I’d learnt a few things on the way, a little about DependencyProperties, I was reminded that co-ordinates were based from the top-left and initally had forgotten to use the Dispatcher.

I then started writing my template, which was relatively easy actually once I knew what the bindings should be (note to self… controls don’t appear if you forget to apply the template!). I wanted to do as much as possible in the XAML and using converter’s where possible, I managed to achieve much of this when I stumbled across a blog about a Javascript based multi-converter. This allows me to do much of the calculation within the XAML itself. The only aspect I’m less pleased with is how I’ve handled updating the graph as this had to be done in the code behind. I don’t want to pollute the RateBase with a property of historical values, but I do need to store these somewhere to produce a graph. It works at least and I managed to achieve most of it in XAML which wasmy aim.

Keep an eye out for the next post where I’ll be sharing a link to the source and compiled version…

Posted in C#, WPF | Tagged: , , | Leave a Comment »

Multiple Input Devices – Controlling the accelerator pedal

Posted by ipwright83 on April 27, 2012

My work machine has a couple of input devices, mainly to try and reduce the onset of RSI. I’ve got an EM500 Ergonomic Computer Mouse and a Logitech MX600 Laser Mouse

ImageImage

The Ergonomic mouse by the way is brilliant and really helps prevent RSI ensuring that you’re wrist is better supported and more naturally placed. There was one significant problem with it however, the sensitivity was much less than my MX600. This meant if ever myself or a fellow developer wanted to use the MX600 on my machine there was a speed conflict. Either the MX600 had the speed of a Ferrari and you had to be very careful not to twitch the accelerator pedal too much, or the EM500 had the speed of a tortoise.

Changing the speed of the mice in control panel quickly became a hassle, so I had a quick look around to see if there were any applications that would automatically switch it based on the device. I found one but unfortunately it cost $15 and therefore would have been a lot of hassle getting it ordered. I figured it surely can’t be that hard to write my own can it?

MouseSpeedSwitch

I started off by looking for libraries – it’s always better reusing existing code than writing something from scratch. I quickly came across RawInputSharp which is a port of a C++ library for monitoring mouse input. I had an attempt at getting the demo’s in the library working, the compiled version worked fine, but whenever I tried to built it from source it just wouldn’t work. I left it alone and came back to it a few weeks later and discovered the problem was due to the build configuration (the target platform if I remember off the top of my head). I got it all working and was then able to register for mouse events.

public void MouseSpeedSwitch(){
   // Register for the mice
   this.mouseInput = new RawMouseInput();
   this.mouseInput.RegisterForWM_INPUT(this.Handle);
}

A little special handling later to fire the necessary updates:

/// Handle the Mouse Move Events and Update the Mouse Speed 
protected const int WM_INPUT = 0x00FF; 
protected override void WndProc(ref Message m) 
{ 
   switch (m.Msg) 
   { 
      case WM_INPUT: // Read in new mouse values. 
         if (this.mouseInput != null) 
         { 
             this.mouseInput.UpdateRawMouse(m.LParam); 
             MouseMoved(); 
         } 
         break; 
    } 
    base.WndProc(ref m); 
}

At this point I had mouse events and the ID’s of the devices every time I moved a mouse within my application. I made a minor change to the original library which suddenly switched the application to detecting mouse events globally in the operating system, regardless of whether the mouse was in my application or not. Brilliant!

public void RegisterForWM_INPUT(IntPtr hwndTarget) 
{
   RAWINPUTDEVICE rid = new RAWINPUTDEVICE();
   rid.usUsagePage = 0x01;
   rid.usUsage = 0x02; //mouse
   rid.dwFlags = 0x00000100; // Register for events outside the current window
   ...
}

Things were starting to look good at this point. A few simple methods later to retrieve the names of mice from the registry and update the mouse speed and the application was almost complete. I then wrote a little very simple UI so I could use my application:

Once added into the Startup folder in the start menu, I no longer needed to worry about changing the speed of my mouse. Everything would be done automatically 🙂

Feel free to download the application, it’s free to use for both personal and commercial use – currently hosted here.

Posted in C#, Events, Mouse, Tools | Tagged: , , | Leave a Comment »