• I have switched to FunnelWeb. Please visit my new blog

Automatically Wrap BeginInvoke (dispatch)

C# supports implicit/explicit conversions to Delegates.

Yes, big news. I was very surprised when I gave this a shot. It’s really just one of those things you really don’t expect to work. So how does this help us? I am sure you are quite sick of writing the following code (the same stuff applies to WPF, you just need to access it via the Dispatch member):

void _items_CollectionChanged(object sender, CollectionChangedEventArgs<ConnectionListItem> e)
{
    if (InvokeRequired)
    {
        Invoke(new EventHandler<CollectionChangedEventArgs<ConnectionListItem>>( _items_CollectionChanged ), sender, e);
        return;
    }

}

The ‘big news’ allows us to do all the heavy lifting for the dispatch BeginInvoke in one simple class (this is a first try – I’ll get round to reviewing it later on).

    /// <summary>
    /// Represent a wrapper for a delegate.
    /// </summary>
    /// <typeparam name="T">The type of event args.</typeparam>
    public class InvokeEventWrapper<T>
        where T : EventArgs
    {
        private EventHandler<T> _apparantHandler;
        private EventHandler<T> _rawHandler;
        private Control _parent;

        /// <summary>
        /// Initializes a new instance of the <see cref="InvokeDelegateWrapper<T>"/> class.
        /// </summary>
        /// <param name="parent">The parent.</param>
        /// <param name="handler">The handler.</param>
        public InvokeEventWrapper(EventHandler<T> handler)
            : this(null, handler)
        {

        }

        /// <summary>
        /// Initializes a new instance of the <see cref="InvokeDelegateWrapper<T>"/> class.
        /// </summary>
        /// <param name="parent">The parent.</param>
        /// <param name="handler">The handler.</param>
        public InvokeEventWrapper(Control parent, EventHandler<T> handler)
        {
            if (handler == null)
                throw new ArgumentNullException("handler");
            if (parent == null)
                parent = (Control)handler.Target;

            _parent = parent;
            _rawHandler = handler;
            _apparantHandler = new EventHandler<T>(Raise);
        }

        /// <summary>
        /// Performs an implicit conversion from <see cref="SharedTerminals.InvokeDelegateWrapper<T>"/> to <see cref="System.EventHandler<T>"/>.
        /// </summary>
        /// <param name="wrapper">The wrapper.</param>
        /// <returns>The result of the conversion.</returns>
        public static implicit operator EventHandler<T>(InvokeEventWrapper<T> wrapper)
        {
            return wrapper._apparantHandler;
        }

        /// <summary>
        /// Raises the event.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The e.</param>
        private void Raise(object sender, T e)
        {
            if (_parent.InvokeRequired)
                _parent.BeginInvoke(_rawHandler, sender, e);
            else
                _rawHandler(sender, e);
        }
    }

Using it is pretty simple:

  1. Navigate to the event in Intellisense.
  2. Type +=.
  3. Press Tab.
  4. Replace EventHandler with InvokeEventWrapper.

So in the end all of that ugly code becomes:

_items.CollectionChanged += new InvokeEventWrapper<CollectionChangedEventArgs<ConnectionListItem>>( _items_CollectionChanged );

You will need to hold onto a reference for that wrapper if you wish to unsubscribe from the event (one of the things I need to look at).

Posted in C#, Programming, Tricks | Leave a comment

SSRS Timeout on SSL 443 – Resolved

Manifestation of the Error

If you attempt to connect to SSRS via the deployment webservice; when SSRS is running in SSL mode (specifically on port 443), you may get one of the following exceptions (which do not occur intermittently):

  • The underlying connection was closed: An unexpected error occurred on a send.
  • The operation has timed-out.

You might get it for other “The underlying connection was closed” errors, but I have not confirmed that. The issue occurs mainly when you try to upload report definitions that are over approximately 100kb.

The Solution

Let me tell you straight up – there is no reason to disable SSL or alter timeouts. The first thing you want to do is to add a new class to your project; I called mine SslReportService. Implement ReportingService2005 from your WebService reference. You can then override GetWebRequest(Uri) without worrying about your changes being lost of you update your web reference.

Then, in a nutshell:

class SslReportService : ReportService.ReportingService2005
{
  protected override System.Net.WebRequest GetWebRequest(Uri uri)
  {
    var res = (HttpWebRequest)base.GetWebRequest(uri);
    res.SendChunked = true;
    return res;
  }
}

Your mileage may vary; so if this turns up nothing Engels Rajangam has another helpful post on this issue. You might want to read up on this property on MSDN and a pretty good blog post.

Posted in C#, Programming, SSRS | 2 Comments

Direct to MSDN Chrome Search Tag

If you ever need to get directly to the documentation for a specific type in MSDN (which Bing routinely fails to give me) here is a search provider for Chrome that will do the trick:

http://msdn.microsoft.com/en-us/library/%s.aspx

You can obviously also do something like:

http://msdn.microsoft.com/en-us/library/%s(loband).aspx

In case you need a refresher, here is how you add it:

  1. Click the wrench (top right).
  2. Options
  3. Basics (top)
  4. Manage (alongside “Default Search”)
  5. Add
  6. Give it a name and keyword (the keyword is important).
  7. Paste in my URL.

To use it go to your address bar and type the keyword, tab and then the full type name. So for example (my keyword was msdnd):

msdnd : [TAB] : system.xml.serialization.xmlelementattribute : [RETURN]
Posted in Chrome, Programming, Short, Tricks | 2 Comments

XLinQ Serialization

Just found out that Microsoft actually had the foresight to support the following scenario:

/// <summary>
/// Gets the unknown elements as a <see cref="List{XElement}"/>.
/// </summary>
[XmlAnyElement]
public List<XElement> UnknownElements
{
    get;
    set;
}

Fantastic (undocumented) news.

Posted in C#, Programming, Short | 1 Comment

Constructive RTFM

I present to you, an improvement on support ticket forms:

New Support Request Form

New Support Request Form

“You need massive cajones to put that up!” I hear you say, but hear me out.

Firstly there is the obvious advantage of users realising that there is, in actual fact, documentation available that will assist them with simple things like this. Notice the inline help even at this point – some users might not use the documentation because they don’t know how to reach it.

You now have a compounded situation. If the user actually decides to click the submit button with a reason and the validation passes (140 characters minimum is probably a good bet) you really do have a problem – they did RTFM and got no answers. In this situation you have already solved your problem; you now know what areas of your documentation you need to address. The next customer who comes across this page with the same problem won’t be submitting a ticket.

You could always even provide a group of radio buttons so that the user has quick answers – and at the same time you will have data that can be graphed.

It is important to remember – you are not being rude at all. Referring to the documentation will mean that the turnaround time for an answer will be orders of magnitudes faster than relying on a limited amount of human resources.

Posted in Brutal, Ideas | 3 Comments

TFS Server 2008 – Fail

It’s an amazing server. The installer needs A LOT of work. Here is what happened to me:

  1. Followed the pre-setup instructions to the T.
  2. Run the installer; health check fails. SQL Server is the wrong version (2008 RTM); can’t find analysis services, NOTHING.
  3. Hmm… must need SQL 2008 SP1. Install it via Windows Update.
  4. Try again; health check fails. Wrong version of SQL Server, again.
  5. Google – get a solution.
  6. Follow those instructions to the T.
  7. Installer CRASHES. Each time it does this I need to reboot.
  8. Eventually just delete the SQL Server version check from hcpackages.xml
  9. It looks like it’s installing now.

16 hours later. TFS Server 2005 took me merely 4-5 hours (did it twice). Considering it’s a test-bed server where I am going to continue working on integrating K2 with TFS Server (we are going to be using K2 to automate our builds) this was just plain ridiculous.

It’s clever, and that’s about it, to use Sharepoint. It seems as though TFS might have started off as a Sharepoint extensibility test. Things would be far easier were it not for the whole Sharepoint dependency (and analysis and reporting – I don’t need this).

These guys need to take a hint from the ASP.net team.

Posted in Fail, K2, Software, TFS Server | 2 Comments

VMWare vSphere Client Under Windows 7

This is a patch to get the client tools working.

  1. Extract it over VMWare folder in Program Files which should be one of:
    • C:\Program Files\VMWare
    • C:\Program Files (x86)\VMware
  2. Update each shortcut by:
    1. Right click the shortcut.
    2. Click properties.
    3. Click Shortcut (at the top).
    4. In the target box change the .exe at the end to .cmd
    5. Click Ok.

VMWare vSphere Client Patch

Clearly, I take no responsibility for any ill effects that this patch may cause – whatsoever.

Posted in Software, VMWare, Windows 7 | 3 Comments

It Works on My Virtual Machine

Origin

After reading Joseph Cooney’s post on “Works on My Machine” I was inspired to integrate this prestigious certification program into my company’s typical workflow.

Introduction

The program applies only to developers and QA specialists who use virtual environments (VMWare, VPC, VirtualBox, etc.) for primary development and/or quality assurance. If the application meets the strict requirements stipulated below it may be branded with the “It Works on My Virtual Machine” logo.

Click for a high-res version.

Click for a high-res version.

Compatibility with other Certification Programs

This certification is compatible with “It Works on My Machine”. It will not qualify and application under “It Works on My Machine” automatically, nor will “It Works on My Machine” automatically qualify an application under “It Works on My Virtual Machine”. Each certification program needs to be met independently.

Technical Certification Requirements

  1. Compile your latest application code with the relevant compiler. This should include changes from other developers.
  2. Launch the application/site that has just been compiled.
  3. Set a breakpoint in the code and reach it. Use any means possible to ensure the path to the breakpoint executes, this may include (but is not limited to):
    • Changing CPU registers (typically the instruction pointer) by manipulating the virtual machine host.
    • Using the snapshot feature of the virtual machine host to return to a previous snapshot where the code path executed successfully. Depending on your virtual machine software you may have to take a snapshot before navigating to alternates.
    • Manipulating the operating system and supplementary services (e.g. SQL) to ensure the path executes correctly.
  4. Check the code changes into your version control system.
    • If the snapshot feature was used, ensure you return to the original state before checking the code in.

Notification Requirements

Customer and partners need not be informed of the branding; however, it is a preferable to place this logo in a clear location to indicate the quality of the software. Typical examples include:

  • Splash screen on rich clients.
  • Click-through interstitial landing page on websites.
  • Ascii art in terminals.
  • Using it to xor-encrypt sensitive data:
    • The character string “It Works On My Virtual Machine” (without quotes) repeated for the duration of the plaintext.
    • The byte stream of the logo image repeated for the duration of the plaintext.
Posted in Ideas, Software, Top Hacks | 1 Comment

Remove System Menu Icon in WPF

I am entering the Code7 Contest and part of my project is to mimic the network notification icon.

Windows 7 Network Menu

Windows 7 Network Menu

The trick to this is to set the caption of the window to null (not empty string) and remove the system menu – at least as far as Windows Forms goes. WPF doesn’t let you do this. I had a few options:

  • Implement a template to mimic the real window template. Not too sure how glass would work here.
  • Use API calls to do it instead.

The second option seemed to be more sensible. As it turns out Windows Forms is doing quite a bit of heavy lifting under the covers – you don’t set the title to null; you actually need to remove the caption (Windows Forms does this for you). In the end it’s as simple as clearing two style flags for the Window.

Remove Caption in WPF
private class NativeMethods
{
  [DllImport("user32.dll", EntryPoint = "SetWindowLong")]
  static extern IntPtr SetWindowLongPtr32(IntPtr hWnd, int nIndex, IntPtr dwNewLong);
  [DllImport("user32.dll", EntryPoint = "SetWindowLongPtr")]
  static extern IntPtr SetWindowLongPtr64(IntPtr hWnd, int nIndex, IntPtr dwNewLong);
  public static IntPtr SetWindowLong(IntPtr hWnd, int nIndex, IntPtr dwNewLong)
  {
      if (IntPtr.Size == 8)
          return SetWindowLongPtr64(hWnd, nIndex, dwNewLong);
      else
          return SetWindowLongPtr32(hWnd, nIndex, dwNewLong);
  }

  [DllImport("user32.dll", EntryPoint = "GetWindowLong")]
  private static extern IntPtr GetWindowLongPtr32(IntPtr hWnd, int nIndex);
  [DllImport("user32.dll", EntryPoint = "GetWindowLongPtr")]
  private static extern IntPtr GetWindowLongPtr64(IntPtr hWnd, int nIndex);
  public static IntPtr GetWindowLong(IntPtr hWnd, int nIndex)
  {
      if (IntPtr.Size == 8)
          return GetWindowLongPtr64(hWnd, nIndex);
      else
          return GetWindowLongPtr32(hWnd, nIndex);
  }

  const int GWL_STYLE = (-16);
  const int WS_SYSMENU = 0x00080000;
  const int WS_CAPTION = 0x00C00000;

  public static void RemoveMenu(IntPtr hwnd)
  {
      int currentStyle = GetWindowLong(hwnd, GWL_STYLE).ToInt32();
      currentStyle &= ~WS_SYSMENU;
      currentStyle &= ~WS_CAPTION;
      int ret = SetWindowLong(hwnd, GWL_STYLE, new IntPtr(currentStyle)).ToInt32();
  }

}

You simply call that from OnSourceInitialized.

How to use the method
protected override void OnSourceInitialized(EventArgs e)
{
  base.OnSourceInitialized(e);
  WindowInteropHelper wih = new WindowInteropHelper(this);
  NativeMethods.RemoveMenu(wih.Handle);
}

And you will get the following result:

Windows 7 Mimic'ed Menu

Windows 7 Mimic'ed Menu

Posted in C#, Code 7 Contest, Programming, Top Hacks | 1 Comment

VMWare Headaches

One of the teams here uses build scripts with hardcoded paths; and while I was on that team I needed to fit in (when you are in Rome be a Roman). In a nutshell I needed a second (D) hard-disk.

That’s long gone now; so today I did some file pruning and deleted the VMDKs I used for that drive; VMWare refused to boot my machine because there was a snapshot with that file somewhere in the hierarchy.

As it turns out the snapshot was a sibling of my current one – which seems odd; logic dictates that the VMDK should only be needed for the descendants of that snapshot. In any case I had to kill nearly every snapshot to be able to boot the VM (Murphy made sure that it was the last snapshot I deleted); on top of that I needed to remove the drive and RAM file locks.

This is the first time I have had a gripe with VMWare. It wasn’t really a train smash but inconvenient at best. My snapshot nesting was getting ridiculous, so I shouldn’t really complain.

Posted in Software | Leave a comment

Switch to our mobile site