Howto turn Windows 8 UAC really off

27 02 2013

I found some valuable information about turning UAC in Windows 8 really off. By „really“ I mean that UAC is still partially active in Windows 8 even when move the slider to „Never notify“ in the „User Account Control Settings“ panel.

Essentially you have to change the following registry value and reboot:

HKLM\Software\Microsoft\Windows\CurrentVersion\Policies\System\EnableLUA=0 (DWORD)

Unfortunately this breaks accessibility to the Windows Store so a better solution is this:

HKLM\Software\Microsoft\Windows\CurrentVersion\Policies\System\EnableLUA=1 (back to default)
HKLM\Software\Microsoft\Windows\CurrentVersion\Policies\System\ConsentPromptBehaviorAdmin=0 (default is 2)
HKLM\Software\Microsoft\Windows\CurrentVersion\Policies\System\EnableUIADesktopToggle=1 (default is 0)

More information about Windows 8 UAC here:

TortoiseSVN Proxy Exceptions for Local Host

18 01 2013

Today I found some strange behavior in TortoiseSVN (1.7.11, Build 23600 – 64 Bit).

I tried to configure the proxy settings so that I can both access SVN repos hosted on the internet behind an HTTP proxy and also local repositories hosted on the dev machine. It was unclear what to enter into the „Exceptions“ field.

„localhost“ didn’t work. „“ as well as the local IPv4 or local IPv6 addresses didn’t work either. The hostname as printed by the „hostname“ command (here: „XPS15z“) in a command shell did also not work.

The only thing that worked was the hostname in lowercase letters (here: „xps15z“)!

TortoiseSVN Proxy Exceptions

Maybe this worked because the SVN URL for the local repo also used lowercase letter. Strange bug. Host names should be case insensitive.

UAC, Elevation and the default Administrator account

28 08 2012

These days I was struggling with Windows 7 UAC (User Account Control). We have an (.NET) app where we want to detect if we are running as an elevated process (if UAC is turned on), or if we are a member of the Administrators group (fallback solution when UAC is turned off). There is a lot of good information including C# sample code around (see e. g. here). They recommend to check the registry for the EnableLUA flag to determine if UAC is turned on, and then call OpenProcessToken and GetTokenInformation(…, TokenElevationType, …) to retrieve the elevation type of the current process.

The problem with all these solutions is that they assume that – when UAC is turned on – the elevation will be either TokenElevationTypeLimited (when not running elevated) or TokenElevationTypeFull (when running elevated). But this is not true! There are times when you receive TokenElevationTypeDefault even though you might expect the value to be TokenElevationTypeFull.

You will receive TokenElevationTypeDefault even when UAC is turned on when the following preconditions are met:

  1. The default Administrator account is enabled (default: disabled), and
  2. The security policy „User Account Control: Use Admin Approval Mode for the built-in Administrator account“ is disabled. This is the default.

You can use the Local Security Policy Editor (secpol.msc) and navigate to Security Settings – Local Policies – Security Options to verify this option.

When the above prerequisites are met, you will receive TokenElevationTypeDefault when one of the following conditions is true:

  1. You are running as the default Administrator, or
  2. You started the process through the „Run as administrator“ Explorer context menu and selected the default Administrator account.

In other words: When the security option „User Account Control: Use Admin Approval Mode for the built-in Administrator account“ is disabled, the default Administrator account behaves as if UAC was also disabled.

To make our app behave the same no matter which Administrator account is used (the default one, or any of the other existing accounts which are a member of the Administrators group), I enhanced the solution for determining process elevation as follows:

/// <summary>
/// Base on code found here:
/// </summary>
public static class UacHelper
  private const string uacRegistryKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System";
  private const string uacRegistryValue = "EnableLUA";

  private const uint STANDARD_RIGHTS_READ = 0x00020000;
  private const uint TOKEN_QUERY = 0x0008;

  [DllImport("advapi32.dll", SetLastError = true)]
  [return: MarshalAs(UnmanagedType.Bool)]
  static extern bool OpenProcessToken(IntPtr ProcessHandle, UInt32 DesiredAccess, out IntPtr TokenHandle);

  [DllImport("advapi32.dll", SetLastError = true)]
  public static extern bool GetTokenInformation(IntPtr TokenHandle, TOKEN_INFORMATION_CLASS TokenInformationClass, 
                                                IntPtr TokenInformation, uint TokenInformationLength, 
                                                out uint ReturnLength);

    TokenUser = 1,

    TokenElevationTypeDefault = 1,

  private static bool? _isUacEnabled;
  public static bool IsUacEnabled
    if (_isUacEnabled == null)
      var uacKey = Registry.LocalMachine.OpenSubKey(uacRegistryKey, false);
      if (uacKey == null)
      _isUacEnabled = false;
      var enableLua = uacKey.GetValue(uacRegistryValue);
      _isUacEnabled = enableLua.Equals(1);
    return _isUacEnabled.Value;

  private static bool? _isAdministrator;
  public static bool IsAdministrator
    if (_isAdministrator == null)
      var identity = WindowsIdentity.GetCurrent();
      Debug.Assert(identity != null);
      var principal = new WindowsPrincipal(identity);
      _isAdministrator = principal.IsInRole(WindowsBuiltInRole.Administrator);
    return _isAdministrator.Value;

  private static bool? _isProcessElevated; 
  public static bool IsProcessElevated
    if (_isProcessElevated == null)
      if (IsUacEnabled)
      var process = Process.GetCurrentProcess();

      IntPtr tokenHandle;
      if (!OpenProcessToken(process.Handle, TOKEN_READ, out tokenHandle))
        throw new ApplicationException("Could not get process token.  Win32 Error Code: " + Marshal.GetLastWin32Error());

      var elevationResult = TOKEN_ELEVATION_TYPE.TokenElevationTypeDefault;

      var elevationResultSize = Marshal.SizeOf((int)elevationResult);
      uint returnedSize;
      var elevationTypePtr = Marshal.AllocHGlobal(elevationResultSize);

      var success = GetTokenInformation(tokenHandle, TOKEN_INFORMATION_CLASS.TokenElevationType, elevationTypePtr, (uint)elevationResultSize, out returnedSize);
      if (!success)
        throw new ApplicationException("Unable to determine the current elevation.");

      elevationResult = (TOKEN_ELEVATION_TYPE)Marshal.ReadInt32(elevationTypePtr);

      // Special test for TokenElevationTypeDefault.
      // If the current user is the default Administrator, then the
      // process is also assumed to run elevated. This is assumed 
      // because by default the default Administrator (which is disabled by default) 
      //  gets all access rights even without showing a UAC prompt.
      switch (elevationResult)
        case TOKEN_ELEVATION_TYPE.TokenElevationTypeFull:
        _isProcessElevated = true;
        case TOKEN_ELEVATION_TYPE.TokenElevationTypeLimited:
        _isProcessElevated = false;
        // Will come here if either
        // 1. We are running as the default Administrator.
        // 2. We were started using "Run as administrator" from a non-admin
        //    account and logged on as the default Administrator account from
        //    the list of available Administrator accounts.
        // Note: By default the default Administrator account always behaves 
        //       as if UAC was turned off. 
        // This can be controlled through the Local Security Policy editor 
        // (secpol.msc) using the 
        // "User Account Control: Use Admin Approval Mode for the built-in Administrator account"
        // option of the Security Settings\Local Policies\Security Options branch.
        _isProcessElevated = IsAdministrator;
      _isProcessElevated = IsAdministrator;
      return _isProcessElevated.Value;

HOWTO: Uninstall broken Windows 8 apps

29 03 2012

I had a problem with a Windows 8 app (the „Flow“ game) which was partially broken. The app’s tile was no longer shown on the start screen, and no icon was shown when I searched for the app’s name, though Windows noted that there was „1 Application“ with a matching name – but no tiles where shown. For this reason, I couldn’t right-click the tile to uninstall it.

Thanks to MS support I learned that apps can be uninstalled manually through some PowerShell commands. They pointed me to this thread.

List all installed apps:

Get-AppxPackage –AllUsers

Remove a specific app:

Remove-AppxPackage FullPackageName

Hint: Windows 8 apps are placed in a hidden folder named C:\Program Files\WindowsApps. Simply deleting (or renaming) an app’s folder will not properly uninstall it.

WPF button in WPF Bing Maps MapItemsControl not reacting to touch events

15 03 2012

Today I a solved problem with buttons placed on a MapItemsControl inside a WPF Bing Maps control not reacting to touch events. The full description of the problem and also the solution (custom TouchButton class with OnTouchDown, OnTouchMove and OnTouchUp overrides) can be found in the Bing Maps support forum.

Here’s the code:

 public class TouchButton : Button
    protected override void OnTouchDown(TouchEventArgs e)
      if (e.TouchDevice.Capture(this))
        IsPressed = true;
        e.Handled = true;

    protected override void OnTouchMove(TouchEventArgs e)
      if (e.TouchDevice.Captured == this)
        // Update IsPressed property to indicate if the
        // current touch position is within the element's
        // visuals.
        IsPressed = IsHitTest(e.GetTouchPoint(this).Position);
        e.Handled = true;

    protected override void OnTouchUp(TouchEventArgs e)
      if (e.TouchDevice.Captured == this)
        IsPressed = false;

        // Raise Click event if touch up occurs within
        // the element's visuals.
        if (IsHitTest(e.GetTouchPoint(this).Position))

        e.Handled = true;

    private bool IsHitTest(Point point)
      var hitTestResult = VisualTreeHelper.HitTest(this, point);
      return hitTestResult != null && hitTestResult.VisualHit != null;

Windows 8 Beta („Consumer Preview“) Experiences

2 03 2012

I’d like to summarize my so far very positive experiences with the Windows 8 Beta („Consumer Preview“) here.

I downloaded and installed the 64-bit en-US version on my XPS15z laptop into a virtual disk (.vhd file). The download was very fast (on an average download rate of 6.2 MB/s!), so it took less than 10 minutes to get it from the Microsoft servers.

Installation was seemless despite the extra hops that need to be taken to get it installed into a .vhd file. I followed the Guide to Installing and Booting Windows 8 Developer Preview off a VHD (Virtual Hard Disk) by Scott Hanselman for the Windows 8 Developer Preview and it still works exactly as described with the Beta. The only thing you need to be aware off is that the drive letter where you created the .vhd file upfront might change from C: to D: (in my case).

Windows 8 benefits over Windows 7

1. Hardware Support

Windows 8 seamlessly recognized the most important of the XPS15z’s quite modern hardware components, namely the Intel WLAN adapter, the Atheros Ethernet adapter, and the USB 3.0 host controller. On Windows 7 it was a PITA to get the drivers installed if you have neither access to USB, nor to a network and you don’t have a driver DVD handy.

Also, my network enabled EPSON BX635FWD printer was automatically detected, and the EPSON driver software was automatically installed.

Very nice experience!

2. Out-of-the-box support for mounting .ISO images

No more need to download and install Virtual Clone Drive or alike.

3. Mouse Without Borders

Installation Mouse Without Borders (one of my favorite tools) was a bit bumpy because this software is dependent on the .NET framework 2.0. Windows 8 comes with .NET framework 4.5 preinstalled, but this does not include the older .NET framework 3.5.1 (which includes 2.0). Installation through the „Programs and Features“ applet failed, maybe because Internet was only available through the company proxy.

But I could get .NET framework 3.5.1 by mounting the downloaded Windows 8 installation .ISO image (which was a snap thanks to the integrated .ISO support) and executing the following command:

Dism.exe /online /enable-feature /featurename:NetFX3 /All /Source:F:\sources\sxs /LimitAccess

SQL Server 2008 R2 SP1 Express Edition Download

15 02 2012

Here’s the link to the most recent version of SQL Server Express Edition (at 2012-02-16, the time of this writing):

SQL Server 2008 R2 SP1 Express Edition (10.50.2500.0) Download

Download the file SQLEXPRWT_x64_ENU.exe (329.9 MB) for 64-bit editions of Windows. WT stands for with tools.

WPF Application Shutdown on Windows 7 x64

3 02 2012

In WPF applications, the Application.Exit event is not (reliably) called – at least on Windows 7 x64 – when the user logs off from or shuts down or restarts the Windows machine. I found that my Application_Exit handler which performs important cleanup was not called.

I tried to remedy this first by hooking into the SystemEvents.SessionEnding event and calling Application.Shutdown from there. After doing this, I found that my Application_Exit handler was called, but then the process seemed to be killed in the middle of the shutdown processing (log output stopped suddenly).

Then I removed the SystemEvents.SessionEnding event handler again and tried to override the Application.OnSessionEnding virtual method. This resulted in the same behavior. The Application_Exit handler was sometimes called, sometimes not, but when it was called, the process died during shutdown processing.

I finally solved this by overwriting the Application.OnSessionEnding method, calling the base class implementation first, then setting SessionEndingCancelEventArgs.Cancel=true to avoid my process being killed by the OS, and finally explicitly calling Application.Shutdown to initiate the shutdown process. The end result is a clean application shutdown while Windows shows the „Application not responding“ screen for several seconds while my application shuts down.

Here’s the code:

public partial class App : Application
  protected override void OnSessionEnding(SessionEndingCancelEventArgs e)

    // Cancel application shutdown to prevent Windows 7 killing
    // the process
    e.Cancel = true;

    // Terminate myself

Get row count from all tables

29 01 2012

The following T-SQL script generates a view of all table names and the number of rows contained in each table for the current SQL database.

SELECT 'TableName', p.rows 'Rows'
FROM sys.objects o
JOIN sys.partitions p ON o.object_id = p.object_id
WHERE (o.type = 'U')
AND (p.index_id IN (0,1))

I found this information here.

VS2010 Build and Debug Startup Project

4 11 2011

In large solutions, I often have the need to build and/or debug only the selected startup project.

The main benefit of this is that Visual Studio keeps from building the entire solution when you select Debug – Start new instance from a project’s context menu in the Solution Explorer view. This is different from the behavior when you select Debug – Start Debugging from the main menu. In the latter case, the whole solution is always built which might cause problems when one or more of the generated output artefacts are in use by the system (e. g. running executables).

Today I wrote the following two Visual Studio macros and assigned them to the hotkey Ctrl+B (BuildStartupProject) and Ctrl+D (DebugStartupProject) and it made me happier.

Option Strict Off
Option Explicit Off
Imports System
Imports EnvDTE
Imports EnvDTE80
Imports EnvDTE90
Imports EnvDTE90a
Imports EnvDTE100
Imports System.Diagnostics

Public Module StartupProjectCommands
Sub BuildStartupProject()
  ' Build startup project
  Dim sb As SolutionBuild = DTE.Solution.SolutionBuild
  Dim projName As String = sb.StartupProjects(0)
  sb.BuildProject(sb.ActiveConfiguration.Name, projName, False)
End Sub

Sub DebugStartupProject()
  ' Get startup project name
  Dim sb As SolutionBuild = DTE.Solution.SolutionBuild
  Dim projName As String = sb.StartupProjects(0)
  Dim index As Integer = projName.LastIndexOf(".")
  If (index > 0) Then
    projName = projName.Substring(0, index)
    ' Activate SolutionExplorer
    ' Select startup project
    ' Debug startup project
  End If
End Sub

End Module