Tech Writing

Hi, I'm Marc. Welcome to, a small collection of my thoughts on technology; programming, performance, infrastructure and cyber.

Brocade - Cannot upgrade directly to 6.4. Please upgrade to 6.3 first and then upgrade to 6.4.

11 Oct 2016 — Infrastructure

Brocade fiber channel switches are extremely robust over long periods of time, delivering solid performance with excellent mean time between failure (MTBF) ratings, but periodically require firmware upgrades. Unfortunatley finding the latest firmware versions from the HPE website can be less than straight forward, as I discovered recently when upgrading some B-Series SAN (8/12c) switches running an old version (v6.1.0_8e1) of the firmware, which proved to be quite time consuming…

Read More ...

Using the PowerShell cmdlet Get-WinEvent to search and filter event and diagnostic logs

28 Sep 2016 — Administration

Recently, a colleague wanted a way to search the body of Windows eventlogs – for instance if you wanted to count the occurances of a certain type of event where the traditional filtering fields are unable to differentiate between events.

The powershell cmdlet Get-WinEvent output can be piped into where-object to provide a set of events filtered by the search term in the eventlog body.

Get-WinEvent -FilterHashtable @{logname='application'; ProviderName='ASP.NET 4.0.30319.0'} | where-object  { $_.Message -like '*The timeout period elapsed prior to obtaining a connection from the pool*' }

Thanks Matt.

How to serialise classes which include IPAddress or IPEndPoint

16 Jul 2015 — csharp

The two most popular formats for text-based serialisation are Xml and Json, often using the built-in XmlSerializer and Json.Net library respectively. There are others of course, but many seem to have some objection to serialising IPAddress, or objects containing references to that class.

In the case of the XmlSerializer, during de-serialization an instance of the target class is created before the serialised fields and properties are populated. Without a public parameterless constructor (as is the case with System.Net.IPAddress) the XmlSerializer refuses to populate the values and throws an exception. This is actually a limitation of XmlSerializer, BinaryFormatter and DataContractSerializer do not require a parameterless constructors, they create uninitalised objects.

Talking of other serialisers, the BinaryFormatter is not without its quirks. It throws a SerializationException exception if classes have not been decorated with the [Serializable] attribute. Thankfully System.Net.IPAddress is decorated as [Serializable].

Read More ...

How to receive WndProc messages in WPF

22 Apr 2015 — csharp

Access to the WindowProc callback function in Windows Forms is achieved by overriding void WndProc(ref Message m), this registers the window class to receive Windows event messages. However, in WPF, most elements are drawn onto the WPF canvas, and it’s common to only have a single hWnd which represents everything inside the window. Conversely, in a normal Win32 application most controls will have their own hWnd handle.

When registering to receive WndProc messages using WPF it is the Window handle, rather than a control handle that must be registered. We can get the Window handle from the System.Windows.Interop namespace class HwndSource which exposes a static FromVisual() method.

var hwndSource = PresentationSource.FromVisual(this) as HwndSource;
var hWnd = hwndSource.Handle;

The above code will return the window handle associated with the WPF application to hWnd typed as IntPtr. The HwndSource class also exposes an AddHook() method which, when supplied with a method signature matching the HwndSourceHook delegate adds an event handler which will receive all window messages. By defining a method which matches the delegate signature in our code and supplying it to AddHook() on the HwndSource instance of our WPF window, we receive all window messages.

This has to be done in the overridden OnSourceInitialized() method. If we tried to register the WndProc callback in the constructor, it would fail because we wouldn’t have a valid window hWnd handle at that point.

A complete example is included below;

Read More ...

Backdoor in an RSA Public Key?

25 Jan 2015 — Security Cryptography RSA Backdoor

Sources: A github gist from ryan-c which inspired a technical write-up of the problem, and a c# proof of concept tool,

There seems to be a problem with RSA. In short, a specially crafted RSA key pair can expose your private key, through information embedded in the public key. This means that even if you lock, bury or incinerate your private key, it can still be recoverable from the public key component of the pair.

The problem centers around the modulus component (the product of the two prime numbers, p*q) of an RSA public key. The modulus can be manipulated to hold a pre-defined value without compromising its function in the algorithm. To that end, it is possible to embed pre-defined value covertly into an RSA public key without the key pair owner’s knowledge.

Building on this trait, by using a Curve25519 public key (more commonly used for key exchange between two parties) as a PRNG seed when generating a new RSA key pair, a small (relative to the size of the modulus) artefact can be knitted into the modulus of the resulting RSA public key. This embedded value allows an attacker to, at a later date, derive the RSA private key from the value embeded into the public key. That is without the RSA private key ever becoming directly compromised or exposed to an attacker.

Assuming you trust that the open-source, audited PRNG producing the random bits for your private keys is using trustworthy sources, then this isn’t a problem (i.e. /dev/urandom (urandom) on Mac and Linux, and the Crypto API on Windows).

But it does raise questions around the efficacy of closed-source crypto products responsible for generating and storing RSA private keys, particularly hardware security modules.

Any software or tool which generates an RSA private key is capable of exploiting this qwirk to produce a situation where the RSA private key stays completely isolated and secure, but the public key has embedded within the modulus a back door containing the information an attacker needs to obtain the private key.

Read More ...

Debian package for Mono on Beaglebone Black (ARMhf)

23 Oct 2014 — Programming Troubleshooting Hardware

It is frustrating to discover that at the time of writing Mono cannot be installed on Debian or Ubuntu using the standard package sources and the Beaglebone Black. It seems the only packages which exist are targeting ARMel architecture, rather than ARMhf (hard-float) of the BBB.

$ sudo apt-get install mono-complete
Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have requested an impossible situation or if you are using the unstable distribution that some required packages have not yet been created or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 mono-complete:armel : Depends: mono-runtime:armel (= but it is not going to be installed
                       Depends: mono-runtime-sgen:armel (= but it is not going to be installed
                       Depends: mono-utils:armel (= but it is not going to be installed
                       Depends: mono-devel:armel (= but it is not installable
                       Depends: mono-mcs:armel (= but it is not installable
                       Depends: mono-gmcs:armel (= but it is not installable
                       Depends: mono-dmcs:armel (= but it is not installable
                       Depends: mono-csharp-shell:armel (= but it is not installable
                       Depends: mono-2.0-gac:armel (= but it is not installable
                       Depends: mono-4.0-gac:armel (= but it is not installable
                       Depends: mono-2.0-service:armel (= but it is not installable
                       Depends: mono-4.0-service:armel (= but it is not installable
                       Depends: monodoc-base:armel (= but it is not installable
                       Depends: monodoc-manual:armel (= but it is not installable
                       Depends: libmono-cil-dev:armel (= but it is not installable
E: Unable to correct problems, you have held broken packages.

Compiling from source seemed to be the next sensible option. I started by downloading specific releases but the build failed each time (I tried versions 3.10.0, 3.8.0 and 3.6.0). It seems that unless you have the mono-devel package already installed on your system, the tarballs are missing dependencies required for a full build (see compiling mono on linux).

Read More ...

Cross domain communication with Ajax and JsonP

13 Jan 2014 — Programming Troubleshooting

I recently needed to find a way to display third party RSS content on a domain which wasn’t the content originator. The same-origin policy implemented in most browsers makes it awkward to directly consume content from a foreign domain, but the most common options are:

  • document.domain property - Setting this property to the same value between two different frames or windows instructs the browser to relax the same-origin policy for these windows, but this is mostly considered unreliable except in closed-loop systems, and of course requires the co-operation of both parties, something I did not have.

  • JSONP - Json, “with padding” enables Javascript to fetch data from another domain, circumventing the same-origin policy which typically prohibits web browsers from making sucessful cross-origin requests. JsonP turns Json from data into dynamic Javascript code, which the <script> tag is allowed to load from remote servers, which can be retrieved and then executed. Ideal if the remote host I needed to work with exposed a JsonP version of its RSS data feed, which it didn’t.

  • Cross-Origin Resource Sharing - CORS is a modern alternative to the JsonP pattern which enables cross-domain content sharing by adding new HTTP headers which the browser and server can use to determine whether or not to allow the cross-origin content request. Since I have no control over the far-side RSS content producer, this option won’t work for me.

  • Cross-document messaging / Web Messaging - Web Messaging is an API introduced as part of the HTML5 specification. window.postMessage enables the sending of data between two entities on domains which would usually be blocked by same-origin policy. It performs cross-domain AJAX without requiring server side shims. postMessage requires a receiver to be wired up using window.addEventListener('message', function(event) { ... }, false);. Again, impractical for my purposes where I have no control over the far-side content producer of the RSS document.

Read More ...

Beaglebone Driver Problem

07 Dec 2013 — Programming Troubleshooting Hardware

I’ll spare you the back story, but in brief installing the USB NIC driver for the beaglebone black is horribly annoying if you’re using a UK keyboard layout.

“The current language is not supported by the Device Driver Installation Wizard.”

Really? The same message from both \Drivers\Windows\BONE_D64.exe and \BONE_DRV.exe

My current system locale is English – so that doesn’t sound right. British English, that is. Crack open either of those binaries (I used 7-zip) and you’ll find dpinst.exe and dpinst.xml.

Investigating the XML file reveals several sets of language tags;

<language code="0x0409">.....</language>
<language code="0x0804"></language>
<language code="0x0401"></language>

Read More ...

Convert bytes to KB, MB, GB, TB or higher using c#

12 Apr 2013 — Programming

I’m a great believer in making the most of available compute resources, and I quite appreciate clean and optimised code.

Shailesh from has done an excellent job with this method to convert an integer representing a byte count in to a human-friendly string shown below with minor cosmetic modifications to reduce the character count.

/// <summary>
/// Returns a human-readable size discriptor for up 64-bit length fields
/// </summary>
/// <param name="bytes"></param>
/// <returns></returns>
private static string FormatBytes(Int64 bytes)
	if (bytes >= 0x1000000000000000) { return ((double)(bytes >> 50) / 1024).ToString("0.### EB"); }
	if (bytes >= 0x4000000000000) { return ((double)(bytes >> 40) / 1024).ToString("0.### PB"); }
	if (bytes >= 0x10000000000) { return ((double)(bytes >> 30) / 1024).ToString("0.### TB"); }
	if (bytes >= 0x40000000) { return ((double)(bytes >> 20) / 1024).ToString("0.### GB"); }
	if (bytes >= 0x100000) { return ((double)(bytes >> 10) / 1024).ToString("0.### MB"); }
	if (bytes >= 0x400) { return ((double)(bytes) / 1024).ToString("0.###") + " KB"; }
	return bytes.ToString("0 Bytes");

Here is the original snippet Shailesh posted. Expressions Overview

12 Jul 2012 — Programming Troubleshooting

ASPX in-page expressions are, if you don’t know what to call them, nearly impossible to search. So on the off chance that this helps somebody, here are some search-friendly terms that might one day get crawled; (less than percent hash), (less than percent equals), (in-page expressions), (data binding), (data bound), (bee strings), ( server tags), (code render blocks)

  • <% %> is for inline code (especially logic flow)
  • <%$ %> is for evaluating expressions (like resource variables)
  • <%@ %> is for Page directives, registering assemblies, importing namespaces, etc.
  • <%= %> is short-hand for Response.Write (discussed here)
  • <%# %> is used for data binding expressions.
  • <%: %> is short-hand for Response.Write(Server.HTMLEncode()) in 4.0+
  • <%-- --%> is for server-side comments

This information is replicated from the following sources StackOverflow post, Dan Crevier’s blog and in an MSDN article. No excuses then.

Get the current directory using C#

26 Mar 2012 — Performance

How should you get the “current” directory of the executing binary in C#? There are a couple of options expose the directory and name of executing application, but with subtle differences:

  1. AppDomain.BaseDirectory - Gets the base directory that the assembly resolver uses to probe for assemblies.
  2. Application.ExecutablePath - Includes the assembly name.
  3. Application.StartupPath - This is inside the Windows.System.Forms namespace.
  4. Directory.GetCurrentDirectory()- Executes a Windows API call to GetCurrentDirectory() in kernel32.dll.
  5. Environment.CurrentDirectory - This is an alias to Directory.GetCurrentDirectory() in System.IO.
  6. this.GetType().Assembly.Location - Includes the assembly name, or the base directory if you are calling a separate class library.
  7. Assembly.GetExecutingAssembly().Location - From the System.Reflection namespace.
  8. Assembly.GetAssembly(typeof(MyAssemblyType)).Location - Derive from a given type.

My prefered method is AppDomain.CurrentDomain.BaseDirectory, it works with ASP.Net, Forms, WPF, Console applications and Services. It will also return the correct base directory for class libraries too.

var path = AppDomain.CurrentDomain.BaseDirectory;

The string returned includes a trailing backslash; For example: C:\Project1\bin\Debug\

Converting IPv4 to decimal, and back

07 Sep 2011 — Programming

After reading this post by mrhinkydink I thought I’d share a c# way to accomplish the same thing; converting an IP address between dotted decimal notation and its numeric format. There are pre-written libraries and name spaces available everywhere to accomplish this task, but I’m going to show you the raw maths of the conversion process.

First, let’s construct a method to accept a string representation of an ipv4 address in dotted decimal notation (that’s and convert it into numeric, or “long” format (2,130,706,433):

public Double IpStringToLong( String ipString )
    var octets = ipString.Split('.');
    return Double.Parse( octets[3] ) 
         + Double.Parse( octets[2] ) * 256 
         + Double.Parse( octets[1] ) * 65536 
         + Double.Parse( octets[0] ) * 16777216;

Okay, and back the other way:

Read More ...

Creating a self installing windows service with c#

11 Aug 2011 — Programming

Services are not presented as a thing of beauty in .net - in fact, typically creating a service is gut wrenchingly awful. There are multiple design time components to drop in (and for some reason position as icons), and multiple classes for your Service, your ServiceInstaller, and ServiceBase. Then you meet InstallUtil.exe, so much example code which demonstrates installing services relies on the use of InstallUtil.exe. Finally, packaging it all together into an installer. Really, it’s all quite disgusting.

There is a better way. We can create a self installing Windows service using C# and pure code. In a single .cs file should we choose: two classes and managed code. Here’s how to do it. To demonstrate the simplicity of this we’re not going to use Visual Studio, we’ll use Notepad++ (or whichever your preferred editor of choice happens to be) and will compile by hand using the command line tool csc.exe.

No third party code to bundle or execute, no bloat.

Read More ...

Service “Must specify value for source” error.

10 Aug 2011 — Programming

Must specify value for source. at System.Configuration.Install.TransactedInstaller.Install(IDictionary savedState)

I found myself encountering this problem while preparing material for the next post on services and .NET. As I was calling the .Installers.Add() method from the instance of my TransactedInstaller object (called ti) I realised that while it expects you to pass a new instance of an object of type Installer, I was actually passing, “new ServiceInstaller”. This had at one point been the name of my class- but the problem turned out to be that this translates not to the name of my class, but to Service.ServiceProcess.ServiceInstaller.

Read More ...

Exchange 2003, 0xFFFFFD9A and EventID 1159

20 Jul 2011 — Troubleshooting

Problem: you regularly use BackupExec, or a comparable product to take backups of Exchange. Occasionally all of the Outlook clients throughout the organisation simultaneously start to crash, hang, or otherwise report failure in connecting to Exchange. In the Exchange server’s application event log you discover a series of errors (similar to those listed below and probably in an equally similar order) and find your Mailbox Store and Public Folder Store marked offline:

Type: Error
Source: MSExchangeIS
Event ID: 1159
Database error 0xfffffd9a occurred in function JTAB_BASE::EcUpdate while accessing the database "First Storage Group\Mailbox Store (localhost)".

followed by

Type: Error
Source: ESE
Event ID: 226
Information Store (5496) First Storage Group: The backup has been stopped prematurely (possibly because the instance is terminating).

followed by

Type: Error
Source: MSExchangeSA
Event ID: 9175
The MAPI call 'OpenMsgStore' failed with the following error: The attempt to log on to the Microsoft Exchange Server computer has failed. The MAPI provider failed. Microsoft Exchange Server Information Store ID no: 8004011d-0512-00000000

Read More ...


19 Jul 2011 — Security

Notable flags:

-i eth1       : Specify the interface
-c 10         : Limit capture to 10 packets
-s            : Snap length, how many bytes of the frame to capture
-v, -vv, -vvv : Level of verbosity
-n            : Don't resolve host names
-nn           : Don't resolve host names or port names
-S            : Display absolute sequence numbers
-e            : Display the Ethernet header
-q            : Display less protocol information
-E            : Decrypt IPSEC traffic using the supplied key
-X            : Display the packet payload in both hex and ASCII
-XX           : Same as -X, but includes the ethernet header

Basic decoded information: [email protected]:~# tcpdump -nnvvS

Full Ethernet frame using a full snaplen -s 1514: [email protected]:~# tcpdump -ennvvSXqs 1514 port 53

Capture to a file with -w: [email protected]:~# tcpdump -s 1514 port 53 -w capture_file

Grouping requires parenthesis: [email protected]:~# tcpdump ’dst and (dst port 80 or 53)’

Dump each packet in ASCII using -A, or in HEX and ASCII using -XX tcpdump -nqtA -s 1514 port 5060

Capture using -n to print packet IP addresses, and not resolve the hostnames tcpdump -n -i eth0

One of the most important lessons I’ve learnt using tcpdump is that the interface ‘lo’ is virtual. Packets sent to the localhost interface are not treated in the same way as packets sent to non-localhost interfaces such as eth0 by the kernel. That said, tcpdump will helpfully display such packets as if they were normal.

The lesson is that packet injection to localhost will fail, but tcpdump will make it look as if it is not failing. Instead, injecting packets onto the localhost interface is best achieved using raw sockets.

See here for more information.

Knock knock
Race condition
Who's there?