VS Code as a Diff Tool

12. June 2017 11:07

Visual Studio Code is a popular (and free) editor. It can also be used as a GUI for viewing git repository differences.

1) Locate gitconfig. It will most likely be found at C:\Users\<YOU'RE USER NAME>\AppData\Local\GitHub\PortableGit_f02737a78695063deace08e96d5042710d3e32db\mingw32\etc. The following command can also be used to assist in locating gitconfig.

git config --list --show-origin

2) Edit the gitcongif file and add the diff and diff tool sections (VS Code is a good editor to use for this!)

[diff]
tool = default-difftool
[difftool "default-difftool"]
cmd = code --wait --diff $LOCAL $REMOTE

3) After others have checked changes into the remote repository which you have not pulled, run the following which will launch VS Code and highlight differences for each file (replacing sprintNN with the correct branch).

git difftool remotes/origin/sprintNN..sprintNN

Map and Slice–A good match

8. August 2016 10:50

Ever need to remove an object from an array (in JavaScript)? In the past I’ve done things like loop through the array check each item to see if a property matches a search condition and then try to remove it. Map to the rescue!

 

       
image

 

The magic of the map function is in returning an array of just the property you are searching on. Then its simply a matter of indexOf on that array to find the index to splice out!

 

Fiddle

JavaScript Closure

19. July 2016 10:24

 

I’ve heard a lot about closure in JavaScript but until recently didn’t see a good example that made sense to me. In the Pluralsight course Advanced JavaScript by Kyle Simpson I think I finally found it. It starts with a definition:

 

Closure is when a function “remembers” its lexical scope.

 

In this example, the inline function passed to set timeout “remembers” its lexical scope. It always refers to the variable declared outside of its definition. The value at the time the function executes is always 6 (the loop has completed before the first invocation).

 

for(var i = 1; i <= 5;i++) {
    setTimeout(function(){
      console.log("i = " + i);
  }, i*1000);
}

 

So, that led me to wonder how can we get the iterated value logged instead? Instead of an inline function, pass a function to set timeout. Now the value of the variable is passed to the log function and you get the iterated value (1, 2, 3, 4, 5).

 

for(var i = 1; i <= 5;i++) {
      setTimeout(log(i), i*1000);
}

function log(x){
    console.log("x = " + x);
}

 

Here is a fiddle.

Windows Server 2012 Terminal Services Manager Options

11. July 2016 15:04

 

Invariably with our development servers someone will forget they are logged on, get disconnected and leave an unused Terminal Services session. One two people have done this, no one else can get logged in via RDP. In the good old days there was a nice gui tool available under admin tools – Terminal Services Manager. It is not there in Server 2012. However there are some command line tools available.

qwinsta – can be used to display the current RDP sessions.

C:\WINDOWS\system32>qwinsta /server:oma01tstade06
SESSIONNAME       USERNAME                 ID  STATE   TYPE        DEVICE
services                                    0  Disc
console                                     1  Conn
rdp-tcp#48        htpham                    2  Active
rdp-tcp#49        costws                    3 Active
31c5ce94259d4...                        65536  Listen
rdp-tcp                                 65537  Listen

rwinsta – used to delete a session (specifying the ID number retrieved from the query).

C:\WINDOWS\system32>rwinsta /server:oma01tstade06 3

Lazy/Poor Man’s IOC

17. February 2016 11:47

There may be times where you need IOC for nothing more than the ability to mock something for testing. In these cases you may not want to bother with all the configuration of a real IOC implementation. This ‘poor man’s’ methodology I’ve used could probably be frowned upon but it does what I need it to do in most cases (there will be use cases where this will not work).

 

The basic idea is to have either a publicly settable property or a constructor param for the concrete implementation. Then in the property getter if the backing field is null, create the ‘real’ implementation.  This allows the test cases to either set the property to a mock or pass a mock into the constructor.

 

Given these members of a controller class:

 

 

        private IConfigAccess _configDatAccess;

        private IPciMasker _pciMasker;

        private object _lock = new object();

 

        public IConfigAccess ConfigDataAccess

        {

            get

            {

                lock(_lock)

                {

                    if (_configDatAccess == null) _configDatAccess = new ConfigAccessService();

                }

                return _configDatAccess;

            }

            set

            {

                _configDatAccess = value;

            }

        }

 

        public IPciMasker PciMasker

        {

            get

            {

                lock (_lock)

                {

                    if (_pciMasker == null) _pciMasker = new PciMasker();

                }

                return _pciMasker;

            }

            set

            {

                _pciMasker = value;

            }

        }

In the unit test where you want to mock the IConfigAccess member just set the ConfigDataAccess property to the mocked object and run the test:

 

            var dacMock = new Mock<IConfigAccess>();

            dacMock.Setup(x => x.GetPciMaskByEntryPointId(epId)).Returns(GetDefaultMaskList());

 

            var controller = new ChatConversationController();

            controller.ConfigDataAccess = dacMock.Object;

           

            controller.NewMessage(item);

           

            Assert.AreEqual(expected, item.Message);

 

You just have to make sure to use the property and not the backing field. But don’t worry. If you forget a null reference exception will remind you in a hurry!

Exploring the Strategy Pattern

19. August 2015 16:09

 

According to Wikipedia the strategy pattern “is a software design pattern that enables an algorithm’s behavior to be selected at runtime.” Hmm, what the heck does that mean?

 

Let’s explore how this is implemented in the .Net Framework’s Generic List class’s Sort method. For the examples let’s use a List<Vehicle> where the Vehicle class is defined as such:

 

   1: private class Vehicle : IComparable<Vehicle> 
   2: { 
   3:     public int NumberOfWheels { get; set; }
   4:  
   5:     public string Style { get; set; }
   6:  
   7:  
   8:     public override string ToString() 
   9:     { 
  10:         return string.Format("{0}, Wheel Count = {1}", this.Style, this.NumberOfWheels); 
  11:     }
  12:  
  13:     public int CompareTo(Vehicle other) 
  14:     { 
  15:         return this.Style.CompareTo(other.Style); 
  16:     } 
  17: } 
  18:  

 

This is the collection of vehicles we’ll use:

 

   1:  
   2: private IList<Vehicle> _vehicleList = new List<Vehicle> 
   3: { 
   4:  
   5:  new Vehicle() {NumberOfWheels = 2, Style= "Motorcycle"}, 
   6:  
   7:  new Vehicle() {NumberOfWheels = 4, Style= "Sedan"}, 
   8:  
   9:  new Vehicle() {NumberOfWheels = 4, Style= "Truck"}, 
  10:  
  11:  new Vehicle() {NumberOfWheels = 3, Style= "Trike"}, 
  12:  
  13: };

 

So, calling Sort with no parameters does a default sort. In this case using the Vehicle class’s IComparable interface.

 

   1: public void SortTest()
   2: {
   3:     List<Vehicle> testList = new List<Vehicle>(_vehicleList);
   4:     testList.Sort();
   5:     foreach(var item in testList)
   6:     {
   7:         Console.WriteLine(item.ToString());
   8:     }
   9: }

 

As you expect, this sorts the list by the Style property:

 

Motorcycle, Wheel Count = 2
Sedan, Wheel Count = 4
Trike, Wheel Count = 3
Truck, Wheel Count = 4

 

Wait, where is the strategy pattern? It comes into play with the Sort method’s overloads. Let’s say we want to sort the list by the NumberOfWheels property instead. We’ll start by creating a comparer:

 

   1: private class VehicleWheelCountComparer : IComparer<Vehicle>
   2: {
   3:     public int Compare(Vehicle x, Vehicle y)
   4:     {
   5:         if (x.NumberOfWheels.Equals(y.NumberOfWheels))
   6:         {
   7:             return x.Style.CompareTo(y.Style);
   8:         }
   9:         else { return x.NumberOfWheels.CompareTo(y.NumberOfWheels); }
  10:     }
  11: }

 

Then we can pass a new instance of the comparer to the Sort method. This allows us to change the Sort method’s behavior at runtime. The Sort method doesn’t need to know anything about the Vehicle class or how to sort instances of it. It can just use the ‘strategy’ passed into it.

 

   1: public void SortTestWheelCount()
   2: {
   3:     List<Vehicle> testList = new List<Vehicle>(_vehicleList);
   4:     testList.Sort(new VehicleWheelCountComparer());
   5:     foreach (var item in testList)
   6:     {
   7:         Console.WriteLine(item.ToString());
   8:     }
   9: }

 

Now our list is sorted by Wheel Count:

 

Motorcycle, Wheel Count = 2
Trike, Wheel Count = 3
Sedan, Wheel Count = 4
Truck, Wheel Count = 4

Unlock a file in TFS someone else has locked

31. July 2015 16:27

 

Open a Visual Studio cmmand prompt (Start –> Microsoft Visual Studio nnnn –> Visual Studio Tools)

Navigate to a directory mapped in TFS (i.e. C:\Users\username\Documents\BWPrd\Scripts>)

The command to run is:

tf undo <path to file>/workspace:<workspace name>;<user name>

You can get a list of workspaces with this command:

tf workspaces /owner: <username> /computer:*

SqlDataReader Contains Column Extension Method

30. July 2015 16:59

It seems I have to look this up a lot.  Maybe if I write it down I’ll remember! This is a slick extension method to determine if a SqlDataReader contains a column. The code is originally from this SO post.

public static class DataRecordExtensions
{
    public static bool HasColumn(this System.Data.IDataRecord dr, string columnName)
    {
        for (int i = 0; i < dr.FieldCount; i++)
        {
            if (dr.GetName(i).Equals(columnName, StringComparison.InvariantCultureIgnoreCase))
                return true;
        }
        return false;
    }

PowerShell and IIS–Get Application in an App Pool

10. February 2015 08:30

 

 

Getting information out of IIS with PoSH is fairly straight forward thanks to the WebAdministration module. Here are commands to get the applications running in a given application pool. Note that because these commands interact with IIS they need to be run from an elevated session (right click PoSH and runas administrator).

You may need to set the execution policy before being able to run these commands.

Set-ExecutionPolicy RemoteSigned

Import the Web Administration module

Import-Module WebAdministration

Now you can run commands against the IIS namespace (or run IIS cmdlets).

Get-Item IIS:\AppPools\Default40AppPool2

Chutzpah Test Runner for Jasmine JavaScript tests

30. December 2014 16:43

 

I’ve been using Jasmine to write unit tests for JavaScript code and just using the built in browser test runner to the tests. The phase is to incorporate these tests from a command line, build or from within Visual Studio. Running the tests in the browser is pretty straight forward, you just include the necessary Jasmine scripts along with your unit tests and away you go.

image

image

So, nice. We can run our tests and see that they all pass. Except now the c# tests run in Test Explorer in Visual Studio. And to run the JavaScript tests you have open a browser. Chutzpah to the rescue! You can install Chutzpah via NuGet and run it from a command line (which I’m sure will work great with builds, and I’ll test that out when we get a build server set up). There is also a very cool extension to allow you to run the JavaScript tests in the Visual Studio test Explorer!  This is where I ran into some confusing problems. The tests all run and pass in the browser. But running them in Visual Studio they were failing! Some poking around and googling pointed me to the cause. When the tests run in the browser all of the references (angular, etc.) are added in the html page that hosts the tests. When running them in Visual Studio there is no wrapper and nothing including the referenced libraries. Luckily Chutzpah has an answer and Chutzpah.json is it. Add this file and configure your references in it.

image

Now, like magic your Jasmine JavaScript tests show up right along your c# tests in Test Explorer.

image

About the author

I'm a .NET developer, a husband and a father of three beautiful girls.

Month List