From Coding to Optics with the Sony a7R II

I feel its time to take a short break from blogging about code, so here are some photos. I took them recently on my Sony a7R II (man, what a camera). I shot them quite exclusively with either the Tamron SP 150-600MM F/5-6.3 Di VC USD lens using the LA-EA3 35mm Full-Frame A-Mount Adapter or via the Sony Vario-Tessar T* FE 16–35 mm F4 ZA OSS lens. Note that some of these Jay’s baseball game shots were literally up in the nosebleeds. I don’t think we could have gotten seats any further from the action.

Leveraging Func<Task> and Getting Funky

Asynchronous programming is a bit nightmarish, but hopefully this sheds some light upon how you can leverage certain delegate types. Take this example, where you want an abstraction layer for calling a block of code up to a set number of attempts until it succeeds, otherwise having it delegate back the exception you’ve obtained on the very last attempt:

class Program
{
	static void Main(string[] args)
	{
		// Since this is a console application, I just ran everything inside of an async task.
		Task.Run(async () => {
			bool throwException = true;
			var firstResult = await AttemptBlock.Run(async () => {
				Console.WriteLine("X called.");
				if (throwException)
				{
					throwException = false;
					throw new Exception();
				}
				await AttemptBlock.Run(async () =>
				{
					Console.WriteLine("Y called.");
					await Z();
					Console.WriteLine("Y finished.");
				}, 3, async (exception) =>
				{
					await Task.Run(() =>
					{
						Console.WriteLine("Y exception handler called.");
					});
				});
				Console.WriteLine("X finished.");
			}, 3, async (exception) =>
			{
				await Task.Run(() =>
				{
					Console.WriteLine("X exception handler called.");
				});
			});
			Console.WriteLine("Finished the first block with {0}.", firstResult);
			var secondResult = await AttemptBlock.Run(async () =>
			{
				Console.WriteLine("O called.");
				await Z();
				throw new Exception();
			}, 3, async (exception) =>
			{
				await Task.Run(() =>
				{
					Console.WriteLine("O exception handler called.");
					throw new Exception();
				});
			});
			Console.WriteLine("Finished the second block with {0}.", secondResult);
		});
		Console.ReadLine();
	}

	private async static Task<bool> Z()
	{
		Console.WriteLine("Z called.");
		await Task.Delay(1000);
		Console.WriteLine("Z finished.");
		return true;
	}
}

class AttemptBlock
{
	public async static Task<bool> Run(Func<Task> function, int attempts, Func<Exception, Task> handler = null)
	{
		while (attempts > 0)
		{
			var candidate = (Exception)null;
			try {
				await function();
				return true;
			} // If this try-catch block was not here, the function could deadlock if it threw an exception.
			catch (Exception exception) {
				candidate = exception;
			}
			attempts--;
			if (attempts <= 0 && handler != null && candidate != null)
				try {
					await handler(candidate);
				}
				catch { } // If this try-catch block was not here, the handler could deadlock if it threw an exception.
		}
		return false;
	}
}

The output is as follows:

X called.
X called.
Y called.
Z called.
Z finished.
Y finished.
X finished.
Finished the first block with True.
O called.
Z called.
Z finished.
O called.
Z called.
Z finished.
O called.
Z called.
Z finished.
O exception handler called.
Finished the second block with False.

You may also want to check out this post on Synchronous and Asynchronous Delegate Types.

Using Google’s reCAPTCHA Version 2.0 on ASP.NET MVC with AJAX

So, you want to add the latest reCAPTCHA Version 2.0 to your existing MVC website, you want to make it secure with server-side validation, and you want to make it asynchronous and have a rich user experience with AJAX? No problem. Start by adding div’s into the forms you need. Their ID’s will indicate where we want to place CAPTCHA elements. Note for all intents and purposes I am using two different CAPTCHA elements on the same page, just to illustrate it can be done, and done nicely:

<form id="register-form">
    <div id="register-captcha"></div>
    <button id="register-button" type="button" class="btn btn-default">Register</button>
</form>
<form id="contact-form">
    <div id="contact-captcha"></div>
    <button id="contact-button" type="button" class="btn btn-default">Send</button>
</form>

Then wire these up. Take note of how the reCAPTCHA API allows us to tell it what loading method to use and what type of rendering we want (explicit, in this case). This is very important, as it allows us to control the CAPTCHA in JavaScript. Also, make sure to include your site key in the rendering calls:

@section Scripts
{
    <script type='text/javascript'>
        // CAPTCHA loading methods.
        var registrationCaptchaID = null;
        var contactCaptchaID = null;
        var loadCaptcha = function () {
            registrationCaptchaID = grecaptcha.render('register-captcha', {
                'sitekey': '1234567890123456789012345678901234567890',
                'callback': function (response) {
                    registrationCaptchaResponse = response;
                }
            });
            contactCaptchaID = grecaptcha.render('contact-captcha', {
                'sitekey': '1234567890123456789012345678901234567890',
                'callback': function (response) {
                    contactCaptchaResponse = response;
                }
            });
        };
        // Register CAPTCHA section.
        var registrationCaptchaResponse = null;
        $('#register-button').click(function () {
            if (registrationCaptchaResponse == null)
                return;
            $.ajax({
                url: '@Url.Action("Register", "Home")',
                type: 'POST',
                data: {
                    recaptchaResponse: registrationCaptchaResponse
                },
                success: function (data, textStatus, jqXHR) {
                    registrationCaptchaResponse = null;
                    grecaptcha.reset(registrationCaptchaID);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    registrationCaptchaResponse = null;
                    grecaptcha.reset(registrationCaptchaID);
                }
            });
        });
        // Contact CAPTCHA section.
        var contactCaptchaResponse = null;
        $('#contact-button').click(function () {
            if (contactCaptchaResponse == null)
                return;
            $.ajax({
                url: '@Url.Action("Contact", "Home")',
                type: 'POST',
                data: {
                    recaptchaResponse: contactCaptchaResponse
                },
                success: function (data, textStatus, jqXHR) {
                    contactCaptchaResponse = null;
                    grecaptcha.reset(contactCaptchaID);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    contactCaptchaResponse = null;
                    grecaptcha.reset(contactCaptchaID);
                }
            });
        });
    </script>
    <script src="https://www.google.com/recaptcha/api.js?onload=loadCaptcha&render=explicit" async defer></script>
}

To validate this on the server-side, first set up the secret key in your configuration’s application settings section so you can quickly modify on the fly later on when you need to:

<configuration>
  <appSettings>
    <add key="reCAPTCHASecret" value="1234567890123456789012345678901234567890" />
  </appSettings>
</configuration>

Make use of it on an action post, and call the reCAPTCHA service to manually verify the user-obtained results:

public class reCAPTCHAResponse
{
    public bool Success { get; set; }
}

[HttpPost]
public ActionResult Register(string recaptchaResponse)
{
    if (String.IsNullOrEmpty(recaptchaResponse))
        throw new InvalidOperationException("Missing CAPTCHA response.");
    var client = new WebClient();
    var secret = ConfigurationManager.AppSettings["reCAPTCHASecret"];
    if (String.IsNullOrWhiteSpace(secret))
        throw new InvalidOperationException("Missing CAPTCHA configuration.");
    var response = client.DownloadString(String.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", secret, recaptchaResponse));
    var serializer = new JavaScriptSerializer();
    var reCAPTCHA = serializer.Deserialize<reCAPTCHAResponse>(response);
    if (!reCAPTCHA.Success)
        throw new InvalidOperationException("Incorrect CAPTCHA response.");
    return Json(true); // At this point, the request is valid, and you can do whatever you wish.
}

That’s another case closed.

Client-Side File Generation and File Downloads on Modern Browsers

Sometimes, you just need an extension method to generate and download files from the client-side of most modern browsers. The only real takeaway from the code below is that Internet Explorer browser agents like to behave differently and require a different function call to provide this type of functionality. Other than that its pretty clear-cut, with most other modern browsers supporting the download attribute.

$(document).ready(function() {
    saveFile("Example.txt", "data:attachment/text", "Hello, world.");
});

function saveFile (name, type, data) {
    if (data != null && navigator.msSaveBlob)
        return navigator.msSaveBlob(new Blob([data], { type: type }), name);
    var a = $("<a style='display: none;'/>");
    var url = window.URL.createObjectURL(new Blob([data], {type: type}));
    a.attr("href", url);
    a.attr("download", name);
    $("body").append(a);
    a[0].click();
    window.URL.revokeObjectURL(url);
    a.remove();
}

Generating Self-Signed X509 Certificates in Vanilla .NET and C#

To generate a self-signed X509 certificate out of the box with vanilla .NET and C#, you will need to Platform Invoke the Cryptography library in Windows. You don’t need to use any third party libraries for this, Windows is perfectly capable of tackling this task for you. Wired up for using the SHA512 hashing algorithm, here is the code to make the magic happen:

public struct SystemTime
{
	public Int16 Year;
	public Int16 Month;
	public Int16 DayOfWeek;
	public Int16 Day;
	public Int16 Hour;
	public Int16 Minute;
	public Int16 Second;
	public Int16 Milliseconds;
}

public static class MarshalHelper
{
	public static void CheckReturnValue(Boolean nativeCallSucceeded)
	{
		if (!nativeCallSucceeded)
			Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
	}
}

public static class DateTimeExtensions
{
	[DllImport("kernel32.dll", SetLastError = true)]
	static extern Boolean FileTimeToSystemTime(ref Int64 fileTime, out SystemTime systemTime);

	public static SystemTime ToSystemTime(this DateTime dateTime)
	{
		Int64 fileTime = dateTime.ToFileTime();
		SystemTime systemTime;
		MarshalHelper.CheckReturnValue(FileTimeToSystemTime(ref fileTime, out systemTime));
		return systemTime;
	}
}

class X509Certificate2Helper
{
	[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
	static extern Boolean CryptAcquireContextW(out IntPtr providerContext, String container, String provider, UInt32 providerType, UInt32 flags);
	
	[DllImport("advapi32.dll", SetLastError = true)]
	static extern Boolean CryptReleaseContext(IntPtr providerContext, Int32 flags);
	
	[DllImport("advapi32.dll", SetLastError = true)]
	static extern Boolean CryptGenKey(IntPtr providerContext, Int32 algorithmId, Int32 flags, out IntPtr cryptKeyHandle);
	
	[DllImport("advapi32.dll", SetLastError = true)]
	static extern Boolean CryptDestroyKey(IntPtr cryptKeyHandle);
	
	[DllImport("crypt32.dll", SetLastError = true)]
	static extern Boolean CertStrToNameW(Int32 certificateEncodingType, IntPtr x500, Int32 strType, IntPtr reserved, Byte[] encoded, ref Int32 encodedLength, out IntPtr errorString);
	
	[DllImport("crypt32.dll", SetLastError = true)]
	static extern IntPtr CertCreateSelfSignCertificate(IntPtr providerHandle, ref CryptoApiBlob subjectIssuerBlob, Int32 flags, ref CryptKeyProviderInformation keyProviderInformation, IntPtr signatureAlgorithm, ref SystemTime startTime, ref SystemTime endTime, IntPtr extensions);
	
	[DllImport("crypt32.dll", SetLastError = true)]
	static extern Boolean CertFreeCertificateContext(IntPtr certificateContext);
	
	[DllImport("crypt32.dll", SetLastError = true)]
	static extern Boolean CertSetCertificateContextProperty(IntPtr certificateContext, Int32 propertyId, Int32 flags, ref CryptKeyProviderInformation data);

	public static X509Certificate2 GenerateSelfSignedCertificate(String name = "", DateTime? startTime = null, DateTime? endTime = null)
	{
		if (startTime == null || (DateTime)startTime < DateTime.FromFileTimeUtc(0))
			startTime = DateTime.FromFileTimeUtc(0);
		var startSystemTime = ((DateTime)startTime).ToSystemTime();
		if (endTime == null)
			endTime = DateTime.MaxValue;
		var endSystemTime = ((DateTime)endTime).ToSystemTime();
		String containerName = Guid.NewGuid().ToString();
		GCHandle dataHandle = new GCHandle();
		IntPtr providerContext = IntPtr.Zero;
		IntPtr cryptKey = IntPtr.Zero;
		IntPtr certificateContext = IntPtr.Zero;
		IntPtr algorithmPoInt32er = IntPtr.Zero;
		RuntimeHelpers.PrepareConstrainedRegions();
		try
		{
			MarshalHelper.CheckReturnValue(CryptAcquireContextW(out providerContext, containerName, null, 0x1, 0x8));
			MarshalHelper.CheckReturnValue(CryptGenKey(providerContext, 0x1, 0x20000001, out cryptKey));
			IntPtr errorStringPtr;
			Int32 nameDataLength = 0;
			Byte[] nameData;
			dataHandle = GCHandle.Alloc(name, GCHandleType.Pinned);
			if (!CertStrToNameW(0x10001, dataHandle.AddrOfPinnedObject(), 3, IntPtr.Zero, null, ref nameDataLength, out errorStringPtr))
			{
				String error = Marshal.PtrToStringUni(errorStringPtr);
				throw new ArgumentException(error);
			}
			nameData = new Byte[nameDataLength];
			if (!CertStrToNameW(0x10001, dataHandle.AddrOfPinnedObject(), 3, IntPtr.Zero, nameData, ref nameDataLength, out errorStringPtr))
			{
				String error = Marshal.PtrToStringUni(errorStringPtr);
				throw new ArgumentException(error);
			}
			dataHandle.Free();
			dataHandle = GCHandle.Alloc(nameData, GCHandleType.Pinned);
			CryptoApiBlob nameBlob = new CryptoApiBlob { cbData = (UInt32)nameData.Length, pbData = dataHandle.AddrOfPinnedObject() };
			dataHandle.Free();
			CryptKeyProviderInformation keyProvider = new CryptKeyProviderInformation { pwszContainerName = containerName, dwProvType = 1, dwKeySpec = 1 };
			CryptAlgorithmIdentifier algorithm = new CryptAlgorithmIdentifier { pszObjId = "1.2.840.113549.1.1.13", Parameters = new CryptoApiBlob() };
			algorithmPoInt32er = Marshal.AllocHGlobal(Marshal.SizeOf(algorithm));
			Marshal.StructureToPtr(algorithm, algorithmPoInt32er, false);
			certificateContext = CertCreateSelfSignCertificate(providerContext, ref nameBlob, 0, ref keyProvider, algorithmPoInt32er, ref startSystemTime, ref endSystemTime, IntPtr.Zero);
			MarshalHelper.CheckReturnValue(certificateContext != IntPtr.Zero);
			return new X509Certificate2(certificateContext);
		}
		finally
		{
			if (dataHandle.IsAllocated)
				dataHandle.Free();
			if (certificateContext != IntPtr.Zero)
				CertFreeCertificateContext(certificateContext);
			if (cryptKey != IntPtr.Zero)
				CryptDestroyKey(cryptKey);
			if (providerContext != IntPtr.Zero)
				CryptReleaseContext(providerContext, 0);
			if (algorithmPoInt32er != IntPtr.Zero)
			{
				Marshal.DestroyStructure(algorithmPoInt32er, typeof(CryptAlgorithmIdentifier));
				Marshal.FreeHGlobal(algorithmPoInt32er);
			}
		}
   	}

	struct CryptoApiBlob
	{
		public UInt32 cbData;
		public IntPtr pbData;
	}
	
	struct CryptAlgorithmIdentifier {
		[MarshalAs(UnmanagedType.LPStr)]
		public String pszObjId;
		public CryptoApiBlob Parameters;
	}
	
	struct CryptKeyProviderInformation
	{
		[MarshalAs(UnmanagedType.LPWStr)]
		public String pwszContainerName;
		[MarshalAs(UnmanagedType.LPWStr)]
		public String pwszProvName;
		public UInt32 dwProvType;
		public UInt32 dwFlags;
		public UInt32 cProvParam;
		public IntPtr rgProvParam;
		public UInt32 dwKeySpec;
	}
}

To call this class, specify the common name to your self-signed certificate, and actually get a certificate out of it (in PFX format with a simple password for it’s private key):

var certificate = X509Certificate2Helper.GenerateSelfSignedCertificate("CN = localhost");
File.WriteAllBytes(@"C:\Users\User\Desktop\Certificate.pfx", certificate.Export(X509ContentType.Pfx, "password"));

How to Bypass SSL Security Checks in Firefox

In Firefox, you can bypass SSL security checks in order to do local development on machines you trust the identity of. To do this:

  • Type about:config into the URL field of Firefox and hit the enter key.
  • Find security.tls.insecure_fallback_hosts, double click its value and type your domain(s) there. For example: localhost,dev.local.

This should resolve any Secure Connection Failed errors if you are seeing these on your development machines, but also, its not something you should do for any website out there, because it can easily compromise security.

How to Center an Image Vertically and Horizontally in HTML

It all depends on the size of the image. You need to set your top edge and left edge to 50%, then subtract half of the content size. So for example, my image below has a width of 300px, so I subtract 150px from the left edge by setting the left margin and do the same operation on the top margin.

<!DOCTYPE html>
<html>
<body>
	<div style="position:absolute;top:50%;margin-top:-179px;left:50%;margin-left:-150px;">
		<img src="image.png" width="300" height="358">
	</div>
</body>
</html>

How to Draw and Scale an XNA Sprite to Fit the Entire Screen of an iOS MonoGame Project

This example may be a little bit overboard for most intents and purposes, but this example shows you how you can draw a sprite such that it gets scaled to exactly fit the entire screen of the device you are using for simulation. I tested this using Xamarin Studio 5.9.1 and the latest MonoGame NuGet package available for iOS at the time.

void DrawToFitScreen(Texture2D texture)
{
	var destinationRectangle = new Rectangle (0, 0, GraphicsDevice.PresentationParameters.Bounds.Width, GraphicsDevice.PresentationParameters.Bounds.Height);
	var scale = new Vector2(texture.Width >= GraphicsDevice.PresentationParameters.Bounds.Width ? (float)GraphicsDevice.PresentationParameters.Bounds.Width / texture.Width : (float)texture.Width / GraphicsDevice.PresentationParameters.Bounds.Width,
		texture.Height >= GraphicsDevice.PresentationParameters.Bounds.Height ? (float)GraphicsDevice.PresentationParameters.Bounds.Height / texture.Height : (float)texture.Height / GraphicsDevice.PresentationParameters.Bounds.Height); 
	spriteBatch.Draw(texture, 
		null, 
		destinationRectangle,
		texture.Bounds,
		Vector2.Zero, 
		0, 
		scale,
		Color.White,
		SpriteEffects.None, 
		0);
}

It can easily be called within the Draw method:

spriteBatch.Begin();
DrawToFitScreen(someTexture);
spriteBatch.End();

How to Style a MenuItem with no Icon or Separator in WPF

First of all, you should be using Microsoft Expression Blend to do any sort of control styling in WPF. It’s probably already installed on your system as it comes with different flavors of Visual Studio. I created a copy of the default MenuItemStyle template and started surgery on the hideous icon and separator that normally gets packaged with the simple MenuItem control.

I had to set the following line (found in two separate places):

<ColumnDefinition MinWidth="22" SharedSizeGroup="MenuItemIconColumnGroup" Width="Auto"/>

To a column with zero width:

<ColumnDefinition SharedSizeGroup="MenuItemIconColumnGroup" Width="0"/>

I also had to remove rectangles which normally fill with the separator. So for example, this line:

<Rectangle Fill="{StaticResource Menu.Static.Separator}" HorizontalAlignment="Left" Margin="29,2,0,2" Width="1"/>

Had to be collapsed as follows:

<Rectangle Visibility="Collapsed" Fill="{StaticResource Menu.Static.Separator}" HorizontalAlignment="Left" Margin="29,2,0,2" Width="1"/>

This line:

<Rectangle Fill="{DynamicResource {x:Static SystemColors.ControlDarkBrushKey}}" HorizontalAlignment="Left" Margin="29,2,0,2" Width="1"/>

It also had to be collapsed:

<Rectangle Visibility="Collapsed" Fill="{DynamicResource {x:Static SystemColors.ControlDarkBrushKey}}" HorizontalAlignment="Left" Margin="29,2,0,2" Width="1"/>

In the end, you get a set of resources as follows (its a heavy control, so it has a lot of markup):

<SolidColorBrush x:Key="MenuItem.Highlight.Background" Color="#3D26A0DA"/>
<SolidColorBrush x:Key="MenuItem.Highlight.Border" Color="#FF26A0DA"/>
<SolidColorBrush x:Key="Menu.Disabled.Foreground" Color="#FF707070"/>
<SolidColorBrush x:Key="MenuItem.Highlight.Disabled.Background" Color="#0A000000"/>
<SolidColorBrush x:Key="MenuItem.Highlight.Disabled.Border" Color="#21000000"/>
<SolidColorBrush x:Key="MenuItem.Selected.Border" Color="#FF26A0DA"/>
<SolidColorBrush x:Key="MenuItem.Selected.Background" Color="#3D26A0DA"/>
<Geometry x:Key="Checkmark">F1 M 10.0,1.2 L 4.7,9.1 L 4.5,9.1 L 0,5.2 L 1.3,3.5 L 4.3,6.1L 8.3,0 L 10.0,1.2 Z</Geometry>
<SolidColorBrush x:Key="Menu.Static.Foreground" Color="#FF212121"/>
<ControlTemplate x:Key="{ComponentResourceKey ResourceId=SubmenuItemTemplateKey, TypeInTargetAssembly={x:Type MenuItem}}" TargetType="{x:Type MenuItem}">
	<Border x:Name="templateRoot" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" Height="22" SnapsToDevicePixels="true">
		<Grid Margin="-1">
			<Grid.ColumnDefinitions>
				<ColumnDefinition SharedSizeGroup="MenuItemIconColumnGroup" Width="0"/>
				<ColumnDefinition Width="13"/>
				<ColumnDefinition Width="*"/>
				<ColumnDefinition Width="30"/>
				<ColumnDefinition SharedSizeGroup="MenuItemIGTColumnGroup" Width="Auto"/>
				<ColumnDefinition Width="20"/>
			</Grid.ColumnDefinitions>
			<ContentPresenter x:Name="Icon" ContentSource="Icon" HorizontalAlignment="Center" Height="16" Margin="3" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="Center" Width="16"/>
			<Border x:Name="GlyphPanel" BorderBrush="{StaticResource MenuItem.Selected.Border}" BorderThickness="1" Background="{StaticResource MenuItem.Selected.Background}" ClipToBounds="False" HorizontalAlignment="Center" Height="22" Margin="-1,0,0,0" Visibility="Hidden" VerticalAlignment="Center" Width="22">
				<Path x:Name="Glyph" Data="{StaticResource Checkmark}" Fill="{StaticResource Menu.Static.Foreground}" FlowDirection="LeftToRight" Height="11" Width="10"/>
			</Border>
			<ContentPresenter x:Name="menuHeaderContainer" Grid.Column="2" ContentSource="Header" HorizontalAlignment="Left" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="Center"/>
			<TextBlock x:Name="menuGestureText" Grid.Column="4" Margin="{TemplateBinding Padding}" Opacity="0.7" Text="{TemplateBinding InputGestureText}" VerticalAlignment="Center"/>
		</Grid>
	</Border>
	<ControlTemplate.Triggers>
		<Trigger Property="Icon" Value="{x:Null}">
			<Setter Property="Visibility" TargetName="Icon" Value="Collapsed"/>
		</Trigger>
		<Trigger Property="IsChecked" Value="True">
			<Setter Property="Visibility" TargetName="GlyphPanel" Value="Visible"/>
			<Setter Property="Visibility" TargetName="Icon" Value="Collapsed"/>
		</Trigger>
		<Trigger Property="IsHighlighted" Value="True">
			<Setter Property="Background" TargetName="templateRoot" Value="{StaticResource MenuItem.Highlight.Background}"/>
			<Setter Property="BorderBrush" TargetName="templateRoot" Value="{StaticResource MenuItem.Highlight.Border}"/>
		</Trigger>
		<Trigger Property="IsEnabled" Value="False">
			<Setter Property="TextElement.Foreground" TargetName="templateRoot" Value="{StaticResource Menu.Disabled.Foreground}"/>
			<Setter Property="Fill" TargetName="Glyph" Value="{StaticResource Menu.Disabled.Foreground}"/>
		</Trigger>
		<MultiTrigger>
			<MultiTrigger.Conditions>
				<Condition Property="IsHighlighted" Value="True"/>
				<Condition Property="IsEnabled" Value="False"/>
			</MultiTrigger.Conditions>
			<Setter Property="Background" TargetName="templateRoot" Value="{StaticResource MenuItem.Highlight.Disabled.Background}"/>
			<Setter Property="BorderBrush" TargetName="templateRoot" Value="{StaticResource MenuItem.Highlight.Disabled.Border}"/>
		</MultiTrigger>
	</ControlTemplate.Triggers>
</ControlTemplate>
<SolidColorBrush x:Key="Menu.Static.Border" Color="#FF999999"/>
<SolidColorBrush x:Key="Menu.Static.Background" Color="#FFF0F0F0"/>
<SolidColorBrush x:Key="Menu.Static.Separator" Color="#FFD7D7D7"/>
<Geometry x:Key="UpArrow">M 0,4 L 3.5,0 L 7,4 Z</Geometry>
<Style x:Key="MenuScrollButton" BasedOn="{x:Null}" TargetType="{x:Type RepeatButton}">
	<Setter Property="ClickMode" Value="Hover"/>
	<Setter Property="Template">
		<Setter.Value>
			<ControlTemplate TargetType="{x:Type RepeatButton}">
				<Border x:Name="templateRoot" BorderBrush="Transparent" BorderThickness="1" Background="Transparent" SnapsToDevicePixels="true">
					<ContentPresenter HorizontalAlignment="Center" Margin="6" VerticalAlignment="Center"/>
				</Border>
			</ControlTemplate>
		</Setter.Value>
	</Setter>
</Style>
<MenuScrollingVisibilityConverter x:Key="MenuScrollingVisibilityConverter"/>
<Geometry x:Key="DownArrow">M 0,0 L 3.5,4 L 7,0 Z</Geometry>
<Style x:Key="{ComponentResourceKey ResourceId=MenuScrollViewer, TypeInTargetAssembly={x:Type FrameworkElement}}" BasedOn="{x:Null}" TargetType="{x:Type ScrollViewer}">
	<Setter Property="HorizontalScrollBarVisibility" Value="Hidden"/>
	<Setter Property="VerticalScrollBarVisibility" Value="Auto"/>
	<Setter Property="Template">
		<Setter.Value>
			<ControlTemplate TargetType="{x:Type ScrollViewer}">
				<Grid SnapsToDevicePixels="true">
					<Grid.ColumnDefinitions>
						<ColumnDefinition Width="*"/>
					</Grid.ColumnDefinitions>
					<Grid.RowDefinitions>
						<RowDefinition Height="Auto"/>
						<RowDefinition Height="*"/>
						<RowDefinition Height="Auto"/>
					</Grid.RowDefinitions>
					<Border Grid.Column="0" Grid.Row="1">
						<ScrollContentPresenter CanContentScroll="{TemplateBinding CanContentScroll}" Margin="{TemplateBinding Padding}"/>
					</Border>
					<RepeatButton Grid.Column="0" CommandTarget="{Binding RelativeSource={RelativeSource TemplatedParent}}" Command="{x:Static ScrollBar.LineUpCommand}" Focusable="false" Grid.Row="0" Style="{StaticResource MenuScrollButton}">
						<RepeatButton.Visibility>
							<MultiBinding ConverterParameter="0" Converter="{StaticResource MenuScrollingVisibilityConverter}" FallbackValue="Visibility.Collapsed">
								<Binding Path="ComputedVerticalScrollBarVisibility" RelativeSource="{RelativeSource TemplatedParent}"/>
								<Binding Path="VerticalOffset" RelativeSource="{RelativeSource TemplatedParent}"/>
								<Binding Path="ExtentHeight" RelativeSource="{RelativeSource TemplatedParent}"/>
								<Binding Path="ViewportHeight" RelativeSource="{RelativeSource TemplatedParent}"/>
							</MultiBinding>
						</RepeatButton.Visibility>
						<Path Data="{StaticResource UpArrow}" Fill="{StaticResource Menu.Static.Foreground}"/>
					</RepeatButton>
					<RepeatButton Grid.Column="0" CommandTarget="{Binding RelativeSource={RelativeSource TemplatedParent}}" Command="{x:Static ScrollBar.LineDownCommand}" Focusable="false" Grid.Row="2" Style="{StaticResource MenuScrollButton}">
						<RepeatButton.Visibility>
							<MultiBinding ConverterParameter="100" Converter="{StaticResource MenuScrollingVisibilityConverter}" FallbackValue="Visibility.Collapsed">
								<Binding Path="ComputedVerticalScrollBarVisibility" RelativeSource="{RelativeSource TemplatedParent}"/>
								<Binding Path="VerticalOffset" RelativeSource="{RelativeSource TemplatedParent}"/>
								<Binding Path="ExtentHeight" RelativeSource="{RelativeSource TemplatedParent}"/>
								<Binding Path="ViewportHeight" RelativeSource="{RelativeSource TemplatedParent}"/>
							</MultiBinding>
						</RepeatButton.Visibility>
						<Path Data="{StaticResource DownArrow}" Fill="{StaticResource Menu.Static.Foreground}"/>
					</RepeatButton>
				</Grid>
			</ControlTemplate>
		</Setter.Value>
	</Setter>
</Style>
<ControlTemplate x:Key="{ComponentResourceKey ResourceId=TopLevelHeaderTemplateKey, TypeInTargetAssembly={x:Type MenuItem}}" TargetType="{x:Type MenuItem}">
	<Border x:Name="templateRoot" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="true">
		<Grid VerticalAlignment="Center">
			<Grid.ColumnDefinitions>
				<ColumnDefinition Width="Auto"/>
				<ColumnDefinition Width="Auto"/>
			</Grid.ColumnDefinitions>
			<ContentPresenter x:Name="Icon" ContentSource="Icon" HorizontalAlignment="Center" Height="16" Margin="3" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="Center" Width="16"/>
			<Path x:Name="GlyphPanel" Data="{StaticResource Checkmark}" Fill="{TemplateBinding Foreground}" FlowDirection="LeftToRight" Margin="3" Visibility="Collapsed" VerticalAlignment="Center"/>
			<ContentPresenter Grid.Column="1" ContentSource="Header" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
			<Popup x:Name="PART_Popup" AllowsTransparency="true" Focusable="false" IsOpen="{Binding IsSubmenuOpen, RelativeSource={RelativeSource TemplatedParent}}" PopupAnimation="{DynamicResource {x:Static SystemParameters.MenuPopupAnimationKey}}" Placement="Bottom" PlacementTarget="{Binding ElementName=templateRoot}">
				<Border x:Name="SubMenuBorder" BorderBrush="{StaticResource Menu.Static.Border}" BorderThickness="1" Background="{StaticResource Menu.Static.Background}" Padding="2">
					<ScrollViewer x:Name="SubMenuScrollViewer" Style="{DynamicResource {ComponentResourceKey ResourceId=MenuScrollViewer, TypeInTargetAssembly={x:Type FrameworkElement}}}">
						<Grid RenderOptions.ClearTypeHint="Enabled">
							<Canvas HorizontalAlignment="Left" Height="0" VerticalAlignment="Top" Width="0">
								<Rectangle x:Name="OpaqueRect" Fill="{Binding Background, ElementName=SubMenuBorder}" Height="{Binding ActualHeight, ElementName=SubMenuBorder}" Width="{Binding ActualWidth, ElementName=SubMenuBorder}"/>
							</Canvas>
							<Rectangle Visibility="Collapsed" Fill="{StaticResource Menu.Static.Separator}" HorizontalAlignment="Left" Margin="29,2,0,2" Width="1"/>
							<ItemsPresenter x:Name="ItemsPresenter" KeyboardNavigation.DirectionalNavigation="Cycle" Grid.IsSharedSizeScope="true" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" KeyboardNavigation.TabNavigation="Cycle"/>
						</Grid>
					</ScrollViewer>
				</Border>
			</Popup>
		</Grid>
	</Border>
	<ControlTemplate.Triggers>
		<Trigger Property="IsSuspendingPopupAnimation" Value="true">
			<Setter Property="PopupAnimation" TargetName="PART_Popup" Value="None"/>
		</Trigger>
		<Trigger Property="Icon" Value="{x:Null}">
			<Setter Property="Visibility" TargetName="Icon" Value="Collapsed"/>
		</Trigger>
		<Trigger Property="IsChecked" Value="true">
			<Setter Property="Visibility" TargetName="GlyphPanel" Value="Visible"/>
			<Setter Property="Visibility" TargetName="Icon" Value="Collapsed"/>
		</Trigger>
		<Trigger Property="IsHighlighted" Value="True">
			<Setter Property="Background" TargetName="templateRoot" Value="{StaticResource MenuItem.Highlight.Background}"/>
			<Setter Property="BorderBrush" TargetName="templateRoot" Value="{StaticResource MenuItem.Highlight.Border}"/>
		</Trigger>
		<Trigger Property="IsEnabled" Value="False">
			<Setter Property="TextElement.Foreground" TargetName="templateRoot" Value="{StaticResource Menu.Disabled.Foreground}"/>
			<Setter Property="Fill" TargetName="GlyphPanel" Value="{StaticResource Menu.Disabled.Foreground}"/>
		</Trigger>
		<Trigger Property="ScrollViewer.CanContentScroll" SourceName="SubMenuScrollViewer" Value="false">
			<Setter Property="Canvas.Top" TargetName="OpaqueRect" Value="{Binding VerticalOffset, ElementName=SubMenuScrollViewer}"/>
			<Setter Property="Canvas.Left" TargetName="OpaqueRect" Value="{Binding HorizontalOffset, ElementName=SubMenuScrollViewer}"/>
		</Trigger>
	</ControlTemplate.Triggers>
</ControlTemplate>
<ControlTemplate x:Key="{ComponentResourceKey ResourceId=TopLevelItemTemplateKey, TypeInTargetAssembly={x:Type MenuItem}}" TargetType="{x:Type MenuItem}">
	<Border x:Name="templateRoot" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="true">
		<Grid VerticalAlignment="Center">
			<Grid.ColumnDefinitions>
				<ColumnDefinition Width="Auto"/>
				<ColumnDefinition Width="Auto"/>
			</Grid.ColumnDefinitions>
			<ContentPresenter x:Name="Icon" ContentSource="Icon" HorizontalAlignment="Center" Height="16" Margin="3" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="Center" Width="16"/>
			<Path x:Name="GlyphPanel" Data="{StaticResource Checkmark}" Fill="{StaticResource Menu.Static.Foreground}" FlowDirection="LeftToRight" Margin="3" Visibility="Collapsed" VerticalAlignment="Center"/>
			<ContentPresenter Grid.Column="1" ContentSource="Header" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
		</Grid>
	</Border>
	<ControlTemplate.Triggers>
		<Trigger Property="Icon" Value="{x:Null}">
			<Setter Property="Visibility" TargetName="Icon" Value="Collapsed"/>
		</Trigger>
		<Trigger Property="IsChecked" Value="true">
			<Setter Property="Visibility" TargetName="GlyphPanel" Value="Visible"/>
			<Setter Property="Visibility" TargetName="Icon" Value="Collapsed"/>
		</Trigger>
		<Trigger Property="IsHighlighted" Value="True">
			<Setter Property="Background" TargetName="templateRoot" Value="{StaticResource MenuItem.Highlight.Background}"/>
			<Setter Property="BorderBrush" TargetName="templateRoot" Value="{StaticResource MenuItem.Highlight.Border}"/>
		</Trigger>
		<Trigger Property="IsEnabled" Value="False">
			<Setter Property="TextElement.Foreground" TargetName="templateRoot" Value="{StaticResource Menu.Disabled.Foreground}"/>
			<Setter Property="Fill" TargetName="GlyphPanel" Value="{StaticResource Menu.Disabled.Foreground}"/>
		</Trigger>
		<MultiTrigger>
			<MultiTrigger.Conditions>
				<Condition Property="IsHighlighted" Value="True"/>
				<Condition Property="IsEnabled" Value="False"/>
			</MultiTrigger.Conditions>
			<Setter Property="Background" TargetName="templateRoot" Value="{StaticResource MenuItem.Highlight.Disabled.Background}"/>
			<Setter Property="BorderBrush" TargetName="templateRoot" Value="{StaticResource MenuItem.Highlight.Disabled.Border}"/>
		</MultiTrigger>
	</ControlTemplate.Triggers>
</ControlTemplate>
<Geometry x:Key="RightArrow">M 0,0 L 4,3.5 L 0,7 Z</Geometry>
<ControlTemplate x:Key="{ComponentResourceKey ResourceId=SubmenuHeaderTemplateKey, TypeInTargetAssembly={x:Type MenuItem}}" TargetType="{x:Type MenuItem}">
	<Border x:Name="templateRoot" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" Height="22" SnapsToDevicePixels="true">
		<Grid Margin="-1">
			<Grid.ColumnDefinitions>
				<ColumnDefinition SharedSizeGroup="MenuItemIconColumnGroup" Width="0"/>
				<ColumnDefinition Width="13"/>
				<ColumnDefinition Width="*"/>
				<ColumnDefinition Width="30"/>
				<ColumnDefinition SharedSizeGroup="MenuItemIGTColumnGroup" Width="Auto"/>
				<ColumnDefinition Width="20"/>
			</Grid.ColumnDefinitions>
			<ContentPresenter x:Name="Icon" ContentSource="Icon" HorizontalAlignment="Center" Height="16" Margin="3" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="Center" Width="16"/>
			<Border x:Name="GlyphPanel" BorderBrush="{StaticResource MenuItem.Highlight.Border}" BorderThickness="1" Background="{StaticResource MenuItem.Highlight.Background}" Height="22" Margin="-1,0,0,0" Visibility="Hidden" VerticalAlignment="Center" Width="22">
				<Path x:Name="Glyph" Data="{DynamicResource Checkmark}" Fill="{StaticResource Menu.Static.Foreground}" FlowDirection="LeftToRight" Height="11" Width="9"/>
			</Border>
			<ContentPresenter Grid.Column="2" ContentSource="Header" HorizontalAlignment="Left" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="Center"/>
			<TextBlock Grid.Column="4" Margin="{TemplateBinding Padding}" Opacity="0.7" Text="{TemplateBinding InputGestureText}" VerticalAlignment="Center"/>
			<Path x:Name="RightArrow" Grid.Column="5" Data="{StaticResource RightArrow}" Fill="{StaticResource Menu.Static.Foreground}" HorizontalAlignment="Left" Margin="10,0,0,0" VerticalAlignment="Center"/>
			<Popup x:Name="PART_Popup" AllowsTransparency="true" Focusable="false" HorizontalOffset="-2" IsOpen="{Binding IsSubmenuOpen, RelativeSource={RelativeSource TemplatedParent}}" PopupAnimation="{DynamicResource {x:Static SystemParameters.MenuPopupAnimationKey}}" Placement="Right" VerticalOffset="-3">
				<Border x:Name="SubMenuBorder" BorderBrush="{StaticResource Menu.Static.Border}" BorderThickness="1" Background="{StaticResource Menu.Static.Background}" Padding="2">
					<ScrollViewer x:Name="SubMenuScrollViewer" Style="{DynamicResource {ComponentResourceKey ResourceId=MenuScrollViewer, TypeInTargetAssembly={x:Type FrameworkElement}}}">
						<Grid RenderOptions.ClearTypeHint="Enabled">
							<Canvas HorizontalAlignment="Left" Height="0" VerticalAlignment="Top" Width="0">
								<Rectangle x:Name="OpaqueRect" Fill="{Binding Background, ElementName=SubMenuBorder}" Height="{Binding ActualHeight, ElementName=SubMenuBorder}" Width="{Binding ActualWidth, ElementName=SubMenuBorder}"/>
							</Canvas>
							<Rectangle Visibility="Collapsed" Fill="{DynamicResource {x:Static SystemColors.ControlDarkBrushKey}}" HorizontalAlignment="Left" Margin="29,2,0,2" Width="1"/>
							<ItemsPresenter x:Name="ItemsPresenter" KeyboardNavigation.DirectionalNavigation="Cycle" Grid.IsSharedSizeScope="true" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" KeyboardNavigation.TabNavigation="Cycle"/>
						</Grid>
					</ScrollViewer>
				</Border>
			</Popup>
		</Grid>
	</Border>
	<ControlTemplate.Triggers>
		<Trigger Property="IsSuspendingPopupAnimation" Value="true">
			<Setter Property="PopupAnimation" TargetName="PART_Popup" Value="None"/>
		</Trigger>
		<Trigger Property="Icon" Value="{x:Null}">
			<Setter Property="Visibility" TargetName="Icon" Value="Collapsed"/>
		</Trigger>
		<Trigger Property="IsChecked" Value="True">
			<Setter Property="Visibility" TargetName="GlyphPanel" Value="Visible"/>
			<Setter Property="Visibility" TargetName="Icon" Value="Collapsed"/>
		</Trigger>
		<Trigger Property="IsHighlighted" Value="True">
			<Setter Property="Background" TargetName="templateRoot" Value="Transparent"/>
			<Setter Property="BorderBrush" TargetName="templateRoot" Value="{StaticResource MenuItem.Highlight.Border}"/>
		</Trigger>
		<Trigger Property="IsEnabled" Value="False">
			<Setter Property="TextElement.Foreground" TargetName="templateRoot" Value="{StaticResource Menu.Disabled.Foreground}"/>
			<Setter Property="Fill" TargetName="Glyph" Value="{StaticResource Menu.Disabled.Foreground}"/>
			<Setter Property="Fill" TargetName="RightArrow" Value="{StaticResource Menu.Disabled.Foreground}"/>
		</Trigger>
		<Trigger Property="ScrollViewer.CanContentScroll" SourceName="SubMenuScrollViewer" Value="false">
			<Setter Property="Canvas.Top" TargetName="OpaqueRect" Value="{Binding VerticalOffset, ElementName=SubMenuScrollViewer}"/>
			<Setter Property="Canvas.Left" TargetName="OpaqueRect" Value="{Binding HorizontalOffset, ElementName=SubMenuScrollViewer}"/>
		</Trigger>
	</ControlTemplate.Triggers>
</ControlTemplate>
<Style x:Key="MenuItemStyle1" TargetType="{x:Type MenuItem}">
	<Setter Property="HorizontalContentAlignment" Value="{Binding HorizontalContentAlignment, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}"/>
	<Setter Property="VerticalContentAlignment" Value="{Binding VerticalContentAlignment, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}"/>
	<Setter Property="Background" Value="Transparent"/>
	<Setter Property="BorderBrush" Value="Transparent"/>
	<Setter Property="BorderThickness" Value="1"/>
	<Setter Property="ScrollViewer.PanningMode" Value="Both"/>
	<Setter Property="Stylus.IsFlicksEnabled" Value="False"/>
	<Setter Property="Template" Value="{DynamicResource {ComponentResourceKey ResourceId=SubmenuItemTemplateKey, TypeInTargetAssembly={x:Type MenuItem}}}"/>
	<Style.Triggers>
		<Trigger Property="Role" Value="TopLevelHeader">
			<Setter Property="Background" Value="Transparent"/>
			<Setter Property="BorderBrush" Value="Transparent"/>
			<Setter Property="Foreground" Value="{StaticResource Menu.Static.Foreground}"/>
			<Setter Property="Template" Value="{DynamicResource {ComponentResourceKey ResourceId=TopLevelHeaderTemplateKey, TypeInTargetAssembly={x:Type MenuItem}}}"/>
			<Setter Property="Padding" Value="6,0"/>
		</Trigger>
		<Trigger Property="Role" Value="TopLevelItem">
			<Setter Property="Background" Value="{StaticResource Menu.Static.Background}"/>
			<Setter Property="BorderBrush" Value="{StaticResource Menu.Static.Border}"/>
			<Setter Property="Foreground" Value="{StaticResource Menu.Static.Foreground}"/>
			<Setter Property="Template" Value="{DynamicResource {ComponentResourceKey ResourceId=TopLevelItemTemplateKey, TypeInTargetAssembly={x:Type MenuItem}}}"/>
			<Setter Property="Padding" Value="6,0"/>
		</Trigger>
		<Trigger Property="Role" Value="SubmenuHeader">
			<Setter Property="Template" Value="{DynamicResource {ComponentResourceKey ResourceId=SubmenuHeaderTemplateKey, TypeInTargetAssembly={x:Type MenuItem}}}"/>
		</Trigger>
	</Style.Triggers>
</Style>

You can add the above into your window’s resources and set the style on each menu item:

<Menu>
	<MenuItem Header="File" Style="{DynamicResource MenuItemStyle1}">
		<MenuItem Header="Open" Style="{DynamicResource MenuItemStyle1}"/>
		<MenuItem Header="Save" Style="{DynamicResource MenuItemStyle1}"/>
		<MenuItem Header="Close" Style="{DynamicResource MenuItemStyle1}"/>
	</MenuItem>
	<MenuItem Header="Tools" Style="{DynamicResource MenuItemStyle1}">
		<MenuItem Header="Settings" Style="{DynamicResource MenuItemStyle1}">
			<MenuItem Header="Local" Style="{DynamicResource MenuItemStyle1}"/>
			<MenuItem Header="Remote" Style="{DynamicResource MenuItemStyle1}"/>
		</MenuItem>
	</MenuItem>
</Menu>

Environment.Is64BitOperatingSystem Alternative for Older .NET Versions

If you are using a version of .NET older than .NET 4, you can use the following logic to check if the current environment is x64 or x86 (this method works almost the same way the .NET framework getter for the Is64BitOperatingSystem flag works; if you don’t believe me, you can use dotPeek to find out for yourself):

public static class EnvironmentHelper
{
    [DllImport("kernel32.dll")]
    static extern IntPtr GetCurrentProcess();

    [DllImport("kernel32.dll")]
    static extern IntPtr GetModuleHandle(string moduleName);

    [DllImport("kernel32.dll")]
    static extern IntPtr GetProcAddress(IntPtr hModule, string procName);

    [DllImport("kernel32.dll")]
    static extern bool IsWow64Process(IntPtr hProcess, out bool wow64Process);

    public static bool Is64BitOperatingSystem()
    {
        // Check if this process is natively an x64 process. If it is, it will only run on x64 environments, thus, the environment must be x64.
        if (IntPtr.Size == 8)
            return true;
        // Check if this process is an x86 process running on an x64 environment.
        IntPtr moduleHandle = GetModuleHandle("kernel32");
        if (moduleHandle != IntPtr.Zero)
        {
            IntPtr processAddress = GetProcAddress(moduleHandle, "IsWow64Process");
            if (processAddress != IntPtr.Zero)
            {
                bool result;
                if (IsWow64Process(GetCurrentProcess(), out result))
                    return result;
            }
        }
        // The environment must be an x86 environment.
        return false;
    }
}

Example usage:

EnvironmentHelper.Is64BitOperatingSystem();