Tuesday, 21 October 2014

ReSharper Type Members Layout

Here's the custom layout I use with ReSharper to keep StyleCop (and me) happy.

Update the custom layout (ReSharper | Options | Code Editing | C# | Type Members Layout | Custom Layout) with the following and 'ReSharper | Tools | Cleanup Code...' to use it:

TeamCity NUnit + App.Config

WCF is hard enough without the NUnit tests in TeamCity throwing up:

SetUp method failed. SetUp : System.InvalidOperationException : Could not find endpoint element with name 'selfHostingClientEndpointFormat' and contract 'TestModelServerServiceReference.IModelServerService' in the ServiceModel client configuration section. This might be because no configuration file was found for your application, or because no endpoint element matching this name could be found in the client element.

I wouldn't mind so much but the tests work fine within Visual Studio and using NUnit console/GUI.

It turns out that the JetBrains.BuildServer.NUnitLauncher.exe uses a different strategy to find the application config files to NUnit.

Throw a test Assembly at NUnit and it uses the assembly's config file (*.dll.config) BUT the JetBrains NUnitLauncher assumes an App.Config in the same folder instead ... why???

Monday, 8 September 2014

Get public string property names/values


/// <summary>Gets a list of all public string property names and values.</summary>
/// <returns>A list of all public string property names and values.</returns>
public NameValueCollection Details()
{
  var result = new NameValueCollection();

  foreach (var property in GetType()
    .GetProperties(BindingFlags.Instance | BindingFlags.Public)
    .Where(x => x.PropertyType == typeof(string)
      && x.GetGetMethod(false!= null))
  {
    result.Add(property.Name, (string)property.GetValue(this));
  }

  return result;
}

Friday, 29 August 2014

PowerShell strings can't be $null (step in NullString)

I'd assumed that $[string]$arg = $null would set $arg to $null if no argument was specified ... but we all know what assumption makes :(

Summary

[string]$x = $null
$x -eq $null  # False !!!

[NullString]$x = $null
$x -eq $null  # True


Thursday, 17 July 2014

Multiple project configurations

Problem

  1. I want different 'app.config's for debug and release builds.
  2. I want to be able to define a boiler-plate app.config and 'tweak' it depending on the project's configuration
  3. I want to have some global (solution-wide) configuration parameters (e.g. WCF addresses which need to match up between my servers and various client apps).

Thursday, 10 July 2014

Factory methods within a class can access private members.

There are times when I want to hide construction details and provide a factory method within the class to create objects.

I've found it handy for dependency injection, test classes, etc

Here's one of the patterns I've been using:

Dispose

Here's an insight into my 'Dispose' pattern -- so I can copy/paste into my next class :)

Thursday, 26 June 2014

Setting a file's date/time to be the current date/time

I'd always used any app I had to hand or created one in my favourite programming language at the time.

I've just come across http://technet.microsoft.com/en-us/library/bb490886.aspx and needed to share:

  • Changing the time and date of a file
    If you want to assign the current time and date to a file without modifying the file, use the following syntax:
    copy /b Source+,,
    The commas indicate the omission of the Destination parameter.

Tuesday, 24 June 2014

Where's my .asmx debugging gone?

I wanted to simplify the deployment of a web service and provide the client with the source so that we could do some fault analysis.

I'd already supplied a .asmx with (some of) the code behind.
e.g.
  <%@ WebService Language="C#" Class="Foo.Bar.DoStuff" %>


with the class Foo.Bar.DoStuff in a Foo.Bar assembly xcopy's to the web service's 'bin' folder.

All well and good...

Thursday, 19 June 2014

PRE tags in HTML copy confuses other HTML editors

I use Microsoft's Productivity Power Tools in Visual Studio and one of the features it gives me is the ability to copy my code out as HTML - so I can paste it to sites such as this.

This is usually great, but the default PRE tag that surrounds each code snippet can confuse other sites where the PRE tag is interpreted as 'any text before the next </pre> is literal'.

Fortunately the HTML Copy options allow me to specify the markup before/after each code snippet.


With the default 'BeforeCodeSnippet' being:

  <pre style="{font-family}{font-size}{font-weight}{font-style}{color}{background}">

I can now change this from PRE to SPAN and all seems well with the world.


Wednesday, 18 June 2014

Asynchronous http handlers

I had a synchronous Http Handler, let's call it 'GenericHandler'.
It was timing out in production, but not under development.
It seems that if you set debug="true" in your web.config it's designed not to time out (you wouldn't want timeouts while you're debugging now would you).

So to test this I turned off debugging and set a short timeout

e.g.

<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="false">
    <httpRuntime executionTimeout="5"/>



There aren't enough TraceListener's in the world...

... so here's one of mine.

I got fed up with the process information polluting my console window so here's my ConsoleTraceListener which displays the Date/Time in the header (if you specify TraceOptions.DateTime) and only displays the event type if it's not TraceEventType.Information.

File name lengths can't reliably exceed 260 characters

It's astonishing to think that the developers of C# didn't take the opportunity to remove this arcane restriction especially since (most of) the underlying Windows APIs CAN!

Most Unicode Windows file-based APIs accept a canonicalised filename with the prefix '\\?\' or '\\?\UNC\' thus allowing file names of (approximately) 32,767 characters.

See: http://msdn.microsoft.com/en-gb/library/windows/desktop/aa365247(v=vs.85).aspx for details.

Here's a simple example of a replacement for File.Copy which uses this prefix and the relevant APIs.

Friday, 13 June 2014

Manipulating WriteableBitmap's back buffer

Things I've found about WriteableBitmap's back buffer;
  • It's at a fixed location in memory for the lifetime of the object
  • Some of the methods take byte arrays, others will take struct arrays
I wanted to 'pan' the image.  I didn't want to use a Transform because I wanted the Image to remain at the same location, but the bitmap being displayed to appear to move about so that I could have the appearance of an infinite canvas to work with as I was working on a simple Mandelbrot viewer.

Friday, 30 May 2014

Caliburn Micro and UserControls

The things that took me a while to understand were:
  • The UserControl library needs a bootstrapper
  • How to bind the view-model to the view
  • How to reference the view-model  in XAML instead of the view

Wednesday, 28 May 2014

Expanding PowerShell variables

I had the situation where I wanted to include an environment variable in my configuration .xml.
Rather than inventing a substitution scheme I decided to use $ExecutionContext.InvokeCommand.ExpandString instead

e.g.
  $sourceString = "This is my computername: `${env:COMPUTERNAME}"
  $ExecutionContext.InvokeCommand.ExpandString($sourceString) 

Update the PowerShell Execution Policy to allow the running of remote scripts

Open a PowerShell window as an Administrator and run the command below on the target machine(enter ‘y’ at the prompt):

Set-ExecutionPolicy RemoteSigned

This will set the machine to require signing for remote scripts only.

Note that the user running the scripts must be a member of the Administrators Group on the remote machines.

This can be laborious if you're managing many servers so a quick ProcMon suggests that all this is doing is setting the registry entry:

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell]
"ExecutionPolicy"="RemoteSigned"

This allowed me to update my servers using:

PowerShell pre 3.0: Where does this script live?

Before PowerShell 3.0's $PSCommandPath which holds the full path to the file and $PSScriptRoot which contains the path to the file's directory we had to hand-craft it.
e.g.

$private:PSCommandPath = $MyInvocation.MyCommand.Path
$private:PSScriptRoot = (Split-Path -Parent $PSCommandPath)

# echo $private:PSCommandPath 
# echo $private:PSScriptRoot
# Call MyOtherScript.ps1 which is in the same directory as this & (Join-Path -Path $private:PSScriptRoot -ChildPath "MyOtherScript.ps1")

See also: Which version of PowerShell am I running?

Which version of PowerShell am I running?

To find which version of PowerShell you are running, start a PowerShell window and type
Get-Host.

The resulting output includes a 'Version : #.#' line.

Set the memory limit on remotely invoked jobs to 4Gb

Powershell with WinRM

Windows 7 and Windows Server 2008 R2 should have these installed by default. For earlier versions of Windows, select the appropriate download from this article: http://support.microsoft.com/kb/968929.

WinRM requires at least PowerShell 2.0.

To find which version of PowerShell you are running, start a PowerShell window and type Get-Host – the resulting output includes a 'Version : #.#' line.

WinRM Configuration

Both the source and target machines must be configured for remote operations.
This requires the 'Windows Remote Management' service to be installed and started, for the WinRM listener to accept WS-Man requests and for the Firewall to include an exception for WinRM.
The simplest way to accomplish this is to get winrm to do it all for you.

Open a PowerShell window as an Administrator and run the command below on the target machine (enter ‘y’ at the prompts):
winrm quickconfig

Example script

Friday, 16 May 2014

This type of CollectionView does not support changes to its SourceCollection from a thread different from the Dispatcher thread

This System.NotSupportedException exception is raised when we attempt to modify (e.g. add to) a collection (e.g. an ObservableCollection) on a thread which isn't the same thread that created the collection (e.g. the UI thread).

In short: An ObservableCollection, for example, can only be modified in the thread that created it.

In WPF this thread affinity is handled by System.Windows.Threading.Dispatcher -- hence it's reference in the error message.

Typically a WPF project has a single Dispatcher instance so to modify the collection we'd have to invoke the modification while we're running in the UI (Dispatcher) thread.

We could use Dispatcher.CurrentDispatcher.Invoke (or BeginInvoke) to do the addition, however, with .Net 4.5 we now have System.Windows.Data.BindingOperations.EnableCollectionSynchronization.

EnableCollectionSynchronization 'Enables a collection to be accessed across multiple threads and specifies the lock object that should be used to synchronize access to the collection.'.

For example, I had a TraceListener which I wanted to be invoked from any number of threads.

The basis of it now looks like this: