Thursday, January 30, 2014

Narrowing down high CPU usage in svchost.exe

I recently had a machine with high CPU usage in a shared service (svchost.exe). Xperf pointed at hardware interrupts being processed by ACPI.SYS, but I still wasn't sure which service was causing the ACPI.SYS calls because the DLL is loaded into svchost.exe, which hosts more than 10 services. This is the technique I used to temporarily split those services into their own service processes.

The following steps need to be run from within a PowerShell console with administrative privileges.
  1. Save a list of all running shared services:

    Get-Service | ? ServiceType -eq Win32ShareProcess | ? Status -eq Running | select -expand Name > SharedServices.txt

  2. Configure those shared services to launch into their own processes:

    cat SharedServices.txt | % { sc.exe config $_ type=own }

  3. Reboot to restart all services

  4. Have a look at the services to see which is using the CPU (in my case, it was the Windows Management Instrumentation service).

  5. Restore the original state:

    cat SharedServices.txt | % { sc.exe config $_ type=share }

Tuesday, December 24, 2013

Running Ubuntu full screen under Hyper V 2012

There is no way through the GUI to configure the screen resolution of an Ubuntu guest to run full screen when running under Hyper V 2012 (on Server 2012 / 2012 R2 or Windows 8 / 8.1).

One way to get Ubuntu running full screen is to hard-code the resolution of your monitor as a Linux kernel parameter. My monitor runs at 1680x1050, so I made the following changes to my Ubuntu 13.10 guest:


  1. Edit the grub configuration file, for example:
    sudo vi /etc/default/grub
     
  2. Find the line starting with GRUB_CMDLINE_LINUX_DEFAULT, and add "video=hyperv_fb:1680x1050" (or your custom resolution) in between the quotes. For example: 
    GRUB_CMDLINE_LINUX_DEFAULT="quiet splash video=hyperv_fb:1680x1050"
  3. Save and exit 
  4. Run 
    sudo update-grub
  5. Restart your computer


If you get an error dialog warning about not being able to apply the video mode when logging into the GUI, use the Ubuntu control panel to change the screen resolution to your chosen custom resolution.

Wednesday, November 20, 2013

System.Xml.XmlException: Data at the root level is invalid. Line 1, position 1

I ran into a problem recently that seemed very familiar because I am sure I have had encountered it before. So, once I re-solved it, I decided I would write a blog entry in the hope that I will find this post when I next run into the issue in a few years' time.

The problem manifested itself in the simple scenario below: I serialised a simple object into UTF-8 XML and then tried to parse the result using XDocument.Parse.

    public class SimpleClass
    {
        public string SomeProperty { get; set; }
        public int AnotherProperty { get; set; }
    }

    [TestMethod]
    public void Given_a_simple_object_When_serialised_to_XML_and_deserialised_Then_it_should_not_throw_an_exception()
    {
        var someObject = new SimpleClass  { SomeProperty = "Abc", AnotherProperty = 42 };

        using (var memoryStream = new MemoryStream())
        using (var xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8))
        {
            var serialiser = new XmlSerializer(someObject.GetType());
            serialiser.Serialize(xmlTextWriter, someObject);

            var utf8Xml = Encoding.UTF8.GetString(memoryStream.ToArray());
            XDocument.Parse(utf8Xml);   //fails at this point with exception System.Xml.XmlException: Data at the root level is invalid. Line 1, position 1
        }
    }

The document in utf8Xml seems fine:

<?xml version="1.0" encoding="utf-8"?><SimpleClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><SomeProperty>Abc</SomeProperty><AnotherProperty>42</AnotherProperty></SimpleClass>
However, the test fails when trying to parse the XML.

I found the cause of the problem to be the byte order mark (BOM) added to the start of the UTF-8 string. The solution was to construct a new instance of UTF8Encoding rather than using the static Encoding.UTF8. One of the the UTF8Encoding constructor overloads takes a parameter encoderShouldEmitUTF8Identifier. Set this to false, and everything works!

This is the passing test:

    public class SimpleClass
    {
        public string SomeProperty { get; set; }
        public int AnotherProperty { get; set; }
    }

    [TestMethod]
    public void Given_a_simple_object_When_serialised_to_XML_and_deserialised_Then_it_should_not_throw_an_exception()
    {
        var someObject = new SimpleClass  { SomeProperty = "Abc", AnotherProperty = 42 };

        using (var memoryStream = new MemoryStream())
        using (var xmlTextWriter = new XmlTextWriter(memoryStream, new UTF8Encoding(false, true)))
        {
            var serialiser = new XmlSerializer(someObject.GetType());
            serialiser.Serialize(xmlTextWriter, someObject);

            var utf8Xml = Encoding.UTF8.GetString(memoryStream.ToArray());
            XDocument.Parse(utf8Xml);
        }
    }

Thursday, November 14, 2013

Get a list of missing updates on Server Core

If you want to get a list of Windows Updates that haven't been installed on Windows Core (or any machine for that matter where you may want to use the command line), the following PowerShell one-liner will work:
(New-Object -ComObject Microsoft.Update.Searcher).Search("IsInstalled=0 and Type='Software'").Updates | select LastDeploymentChangeTime, Title | ft -AutoSize

Friday, November 8, 2013

Installing Jekyll on Windows

Installing Jekyll on Windows is trivially easy if you already have Chocolatey on your machine. Run the following PowerShell one-liner and you’ll be set up in no time!
cup python; cup ruby1.9; cup ruby.devkit.ruby193; gem install jekyll; gem install wdm; gem uninstall pygments.rb; gem install pygments.rb --version "=0.5.0"
Now you just need to learn Jekyll by starting here: http://jekyllrb.com/docs/usage/. Bear in mind that there are some issues with Jekyll on Windows because it is not an officially supported platform.

Saturday, October 26, 2013

Angularjs directive documentation

It looks like the Angular documentation for directives has changed, but unfortunately a lot of valuable information has been lost in the process. I reproduce part of the original documentation below:
(source: http://code.angularjs.org/1.0.7/docs/guide/directive)



Directive Definition Object

The directive definition object provides instructions to the compiler. The attributes are:
  • name - Name of the current scope. Optional and defaults to the name at registration.
  • priority - When there are multiple directives defined on a single DOM element, sometimes it is necessary to specify the order in which the directives are applied. The priority is used to sort the directives before theircompile functions get called. Higher priority goes first. The order of directives within the same priority is undefined.
  • terminal - If set to true then the current priority will be the last set of directives which will execute (any directives at the current priority will still execute as the order of execution on same priority is undefined).
  • scope - If set to:
    • true - then a new scope will be created for this directive. If multiple directives on the same element request a new scope, only one new scope is created. The new scope rule does not apply for the root of the template since the root of the template always gets a new scope.
    • {} (object hash) - then a new 'isolate' scope is created. The 'isolate' scope differs from normal scope in that it does not prototypically inherit from the parent scope. This is useful when creating reusable components, which should not accidentally read or modify data in the parent scope.
      The 'isolate' scope takes an object hash which defines a set of local scope properties derived from the parent scope. These local properties are useful for aliasing values for templates. Locals definition is a hash of local scope property to its source:
      • @ or @attr - bind a local scope property to the value of DOM attribute. The result is always a string since DOM attributes are strings. If no attr name is specified then the attribute name is assumed to be the same as the local name. Given  and widget definition ofscope: { localName:'@myAttr' }, then widget scope property localName will reflect the interpolated value of hello {{name}}. As the name attribute changes so will the localName property on the widget scope. The name is read from the parent scope (not component scope).
      • = or =attr - set up bi-directional binding between a local scope property and the parent scope property of name defined via the value of the attr attribute. If no attr name is specified then the attribute name is assumed to be the same as the local name. Given  and widget definition of scope: { localModel:'=myAttr' }, then widget scope property localModel will reflect the value of parentModel on the parent scope. Any changes to parentModel will be reflected inlocalModel and any changes in localModel will reflect in parentModel.
      • & or &attr - provides a way to execute an expression in the context of the parent scope. If no attr name is specified then the attribute name is assumed to be the same as the local name. Given  and widget definition of scope: { localFn:'&myAttr' }, then isolate scope property localFn will point to a function wrapper for the count = count + valueexpression. Often it's desirable to pass data from the isolated scope via an expression and to the parent scope, this can be done by passing a map of local variable names and values into the expression wrapper fn. For example, if the expression is increment(amount) then we can specify the amount value by calling the localFn as localFn({amount: 22}).
  • controller - Controller constructor function. The controller is instantiated before the pre-linking phase and it is shared with other directives if they request it by name (see require attribute). This allows the directives to communicate with each other and augment each other's behavior. The controller is injectable with the following locals:
    • $scope - Current scope associated with the element
    • $element - Current element
    • $attrs - Current attributes object for the element
    • $transclude - A transclude linking function pre-bound to the correct transclusion scope:function(cloneLinkingFn).
    To avoid errors after minification the bracket notation should be used:
    1. controller: ['$scope', '$element', '$attrs', '$transclude', function($scope, $element, $attrs, $transclude) { ... }]
  • require - Require another controller be passed into current directive linking function. The require takes a name of the directive controller to pass in. If no such controller can be found an error is raised. The name can be prefixed with:
    • ? - Don't raise an error. This makes the require dependency optional.
    • ^ - Look for the controller on parent elements as well.
  • restrict - String of subset of EACM which restricts the directive to a specific directive declaration style. If omitted directives are allowed on attributes only.
    • E - Element name: 
    • A - Attribute: 
    • C - Class: 
    • M - Comment: 
  • template - replace the current element with the contents of the HTML. The replacement process migrates all of the attributes / classes from the old element to the new one. See the Creating Components section below for more information.
  • templateUrl - Same as template but the template is loaded from the specified URL. Because the template loading is asynchronous the compilation/linking is suspended until the template is loaded.
  • replace - if set to true then the template will replace the current element, rather than append the template to the element.
  • transclude - compile the content of the element and make it available to the directive. Typically used withngTransclude. The advantage of transclusion is that the linking function receives a transclusion function which is pre-bound to the correct scope. In a typical setup the widget creates an isolate scope, but the transclusion is not a child, but a sibling of the isolate scope. This makes it possible for the widget to have private state, and the transclusion to be bound to the parent (pre-isolate) scope.
    • true - transclude the content of the directive.
    • 'element' - transclude the whole element including any directives defined at lower priority.
  • compile: This is the compile function described in the section below.
  • link: This is the link function described in the section below. This property is used only if the compile property is not defined.

Tuesday, August 20, 2013

Installing meld or p4merge as diff / merge tool for Git on Windows

Meld

The following PowerShell uses Chocolatey to install meld and configures it as the diff and merge tool for Git. Note that meld is an officially supported diff tool in Git for Windows.
cinst meld

git config --global diff.tool meld
git config --global merge.tool meld

git config --global mergetool.meld.keeptemporaries false
git config --global mergetool.meld.trustExitCode false
git config --global mergetool.meld.keepbackup false

P4Merge (Perforce Merge)

The following PowerShell uses Chocolatey to install p4merge and configures it as the diff and merge tool for Git. Note that p4merge is an officially supported diff tool in Git for Windows.
cinst p4merge

git config --global diff.tool p4merge
git config --global merge.tool p4merge

git config --global mergetool.p4merge.keeptemporaries false
git config --global mergetool.p4merge.trustExitCode false
git config --global mergetool.p4merge.keepbackup false

Semantic Merge

If you're coding in C#, it may be worth using Semantic Merge (also installable via Chocolatey). Note that this set of commands sets up the PlasticSCM merge tool as the fall-back when not merging C#.
cinst SemanticMerge

git config --global diff.tool semantic
git config --global merge.tool semantic

$semanticMergeUserPath = Resolve-Path ~\AppData\local\PlasticSCM4\semanticmerge\semanticmergetool.exe
git config --global difftool.semantic.cmd ('''' + $semanticMergeUserPath + ''' -d=\"$LOCAL\" -s=\"$REMOTE\" -edt=\"mergetool.exe -d=\"\"@sourcefile\"\" -dn=\"\"@sourcesymbolic\"\" -s=\"\"@destinationfile\"\" -sn=\"\"@destinationsymbolic\"\" -t=\"\"@filetype\"\" -i=\"\"@comparationmethod\"\" -e=\"\"@fileencoding\"\"\"')
git config --global mergetool.semantic.cmd ('''' + $semanticMergeUserPath + ''' -b=\"$BASE\" -d=\"$LOCAL\" -s=\"$REMOTE\" -r=\"$MERGED\" -l=csharp -emt=\"mergetool.exe -b=\"\"@basefile\"\" -bn=\"\"@basesymbolic\"\" -s=\"\"@sourcefile\"\" -sn=\"\"@sourcesymbolic\"\" -d=\"\"@destinationfile\"\" -dn=\"\"@destinationsymbolic\"\" -r=\"\"@output\"\" -t=\"\"@filetype\"\" -i=\"\"@comparationmethod\"\" -e=\"\"@fileencoding\"\"\" -edt=\"mergetool.exe  -s=\"\"@sourcefile\"\" -sn=\"\"@sourcesymbolic\"\" -d=\"\"@destinationfile\"\" -dn=\"\"@destinationsymbolic\"\" -t=\"\"@filetype\"\" -i=\"\"@comparationmethod\"\" -e=\"\"@fileencoding\"\"\"')

git config --global mergetool.semantic.keeptemporaries false
git config --global mergetool.semantic.trustExitCode false
git config --global mergetool.semantic.keepbackup false

Other merge tools

You can see which diff tools are supported natively by git by running the following command:

git difftool --tool-help

You'll see something like the following result:

'git difftool --tool-<tool>' may be set to one of the following:
  gvimdiff
  gvimdiff2
  vimdiff
  vimdiff2

The following tools are valid, but not currently available:
  araxis
  bc3
  codecompare
  defaults
  deltawalker
  diffuse
  ecmerge
  emerge
  kdiff3
  kompare
  meld
  opendiff
  p4merge
  tkdiff
  vim
  xxdiff

Some of the tools listed above only work in a windowed
environment. If run in a terminal-only session, they will fail.