Positive Conditionals – Clean Code Post 1

This is the first of my Clean Code posts and it is to do with the use of Conditionals in code.  It is better to use a Positive Conditional over a Negative Conditional.

An example of using a Positive Conditional in code is shown below:

if (LoggedIn)
{

}

The example above is far better to use over the Negative Conditional example below:

if (!IsNotLoggedIn)
{

}

Writing Clean Code

I recently watched a very good course on Pluralsight on writing Clean Code.  It is called Clean Code: Writing Code for Humans and is authored by Cory House.  I highly recommend it if you are lucky to have a Pluralsight subscription.

After watching the course I thought it would be good to write a few posts on writing Clean Code, which is what I plan to do over the coming weeks.  I will be including some tips I have picked up over the years.

Other Resources
There are various other resources already available on writing clean code and on how to improve as a Software Engineer.

Robert C Martin (Uncle Bob) has a collection of videos that you can pay to watch on Clean Code on the website https://cleancoders.com.

Below are a few books that are also well known in the industry

  • Clean code by Robert C Martin (Uncle Bob)
  • Code complete by Steve McConnell
  • The pragmatic programmer by Andrew Hunt and David Thomas

If you are reading this and have any other suggestions please feel free to leave a comment with the details.

Install a Windows Service with PowerShell

Here is a snippet of code that you can use to install a Windows Service using PowerShell:

new-service -Name [INSERT SERVICE NAME] -DisplayName "[INSERT DISPLAY NAME]" -Description "[INSERT DESCRIPTION]" -BinaryPathName "[INSERT BINARY PATH]" -StartupType Manual -Credential [INSERT CREDENTIALS]

Here is an example for a pretend service:

new-service -Name Jonathan.Welch.Test.Service -DisplayName "Jonathan Welch Test Service" -Description "Test Service that does some stuff" -BinaryPathName "C:\Jon\Jonathan.Welch.Test.Service.exe" -StartupType Manual -Credential JonDomain\Jon.Welch

To install a service with startup type Automatic just change -StartupType Manual to be -StartupType Automatic as shown below:

new-service -Name Jonathan.Welch.Test.Service -DisplayName "Jonathan Welch Test Service" -Description "Test Service that does some stuff" -BinaryPathName "C:\Jon\Jonathan.Welch.Test.Service.exe" -StartupType Automatic -Credential JonDomain\Jon.Welch

The located assembly’s manifest definition does not match the assembly reference

I came across the error below earlier when debugging an MVC website in Visual Studio 2012. 

Could not load file or assembly ” or one of its dependencies. The located assembly’s manifest definition does not match the assembly reference. HRESULT: 0x80131040

This puzzled me for a little while until I came across the post below.  It basically said to just delete the offending dll from the bin folder. I then rebuilt the solution and everything worked ok.  My error was with the Newtonsoft.Json.dll, Unfortunately I didn’t catch the full error hence the empty quotes in my error message above.

 

http://articles.runtings.co.uk/2010/04/solved-located-assemblys-manifest.html

 

NUnit & Moq – Setting a return value for a method call

Following on from my last post NUnit & Moq – Asserting a method is called I am now going to detail, in an example, how you can set-up a Mocked object to have a particular value returned when you execute a particular method on the Mocked object.

Program code

This is the main program code that you implement in a console app, if you wish to play around with this code before implementing it.

using PlayConsole.Processor;

namespace PlayConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            var service = new CustomerService(new RetreiveCustomerQuery());
            var customerFullName = service.GetCustomerFullName(1);          
        }
    }
}

IRetreiveCustomerQuery Interface code

This is the interface for the database query class that we will be Mocking in our test so that it returns a known Customer object when the CustomerService’s GetCustomerFullName() method executes the query class’s Run() method.

namespace PlayConsole.Processor
{
    public interface IRetreiveCustomerQuery
    {
        Customer Run(int id);
    }
}

Retreive Customer Query implementation code

This is the implementation for the IRetreiveCustomerQuery interface.

namespace PlayConsole.Processor
{
    public class RetreiveCustomerQuery : IRetreiveCustomerQuery
    {
        public Customer Run(int id)
        {
            //Some code could be here to query database for this data
            return new Customer { Id = id, FirstName = "Fred", LastName = "Bloggs" };
        }
    }
}

CustomerService code

This is the service code. Later in our test class we will be verifying that it’s GetCustomerFullName() method returns the expected FullName of the given Customer. We are testing this by seting up a Mocked instance of IRetreiveCustomerQuery and having it return a know Customer object when it’s Run() method is executed.

namespace PlayConsole.Processor
{
    public class CustomerService
    {
        private readonly IRetreiveCustomerQuery _query;
        public CustomerService(IRetreiveCustomerQuery query)
        {
            _query = query;
        }
        public string GetCustomerFullName(int id)
        {
            var customer = _query.Run(id);
            return string.Format("{0} {1}", customer.FirstName, customer.LastName);
        }
    }
}

CustomerServiceTests

This test class is where you can see the Mocking in place. You will see that a known Customer object is returned when the Run() method is called on the Mocked Object Mock<IRetreiveCustomerQuery. You can also see that we can then assert that the expected full name for the customer is returned when executing the GetCustomerFullName() method on CustomerService.

using Moq;
using NUnit.Framework;
using PlayConsole.Processor;

namespace PlayConsoleUnitTests.Processor
{
    [TestFixture]
    public class CustomerServiceTests
    {
        private Mock _query;
        private CustomerService _service;
        private readonly Customer _customer = new Customer
        {
            Id = 1,
            FirstName = "John",
            LastName = "Jones"
        };

        [SetUp]
        public void Setup()
        {
            _query = new Mock();

            _query.Setup(x => x.Run(It.IsAny()))
                  .Returns(_customer);

            _service = new CustomerService(_query.Object);
        }

        [Test]
        public void Succesfully_retreive_customers_fullname()
        {
            var fullName = _service.GetCustomerFullName(1);
            var expectedFullName = string.Format("{0} {1}", _customer.FirstName, _customer.LastName);
            Assert.That(fullName, Is.EqualTo(expectedFullName));
        }

    }
}

NUnit & Moq – Asserting a method is called

Some people can find using a Mocking framework when writing unit tests tricky when they first start to do this so I thought I’d create some posts with examples.  I will be using Moq and NUnit. You can find the version of Moq I am using on NuGet

In this post I will show how to create a Mock and then assert that a method is called on the Mock.

Program code

This is the main program code that you implement in a console app if you wish to play around with this code before implementing it.

using PlayConsole.Processor;

namespace PlayConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            var processor = new MyProcessor(new LogWriter());
            processor.Start();                
        }
    }
}

ILogWrite Interface code

This is the interface for the log writer that we will be verifying in our test that it’s write method is called by MyProcessor’s Start() method.

namespace PlayConsole.Processor
{
    public interface ILogWriter
    {
        void Write();
    }
}

LogWriter implementation code

This is the implementation for the log writer.

using System;

namespace PlayConsole.Processor
{
    public class LogWriter : ILogWriter
    {
        public void Write(string message)
        {
            Console.WriteLine(message);
        }
    }
}

MyProcessor code

This is the processor code. Later in our test class we will be verifying that it’s Start() method calls the Write() method on it’s implementation of ILogWriter

using System;

namespace PlayConsole.Processor
{
    public class MyProcessor
    {
        private readonly ILogWriter _writer;
        
        public MyProcessor(ILogWriter writer)
        {
            _writer = writer;
        }

        public void Start()
        {
            _writer.Write("Processor has started");
            Console.WriteLine("Hello World");
        }
    }
}

MyProcessorTests

This test class is where you can see the Mocking in place. The simple test verifies that the Write() method is called on ILogWriter once when the Start() method on MyProcessor is executed.

using Moq;
using NUnit.Framework;
using PlayConsole.Processor;
 
namespace PlayConsoleUnitTests.Processor
{
    [TestFixture]
    public class MyProcessorTests
    {
        private MyProcessor _processor;
        private Mock<ILogWriter> _writer;
 
        [SetUp]
        public void Setup()
        {
            _writer = new Mock<ILogWriter>();
            _writer.Setup(x => x.Write(It.IsAny<string>()));
            _processor = new MyProcessor(_writer.Object);
        }
 
        [Test]
        public void Succesfully_write_to_log()
        {
            _processor.Start();
            _writer.Verify(x => x.Write("Processor has started"), Times.Once());
        }
    }
}

Creating User-Defined Table Types in SQL Server

Here is a script that will create a user-defined table type in SQL Server. I was using 2008 R2.

In my type I am adding a primary key (Sku) column and a CHECK constraint on the Quantity column to state that the value must be greater than zero.

CREATE TYPE [dbo].[SkuListWithQuantity] AS TABLE(
[Sku] [CHAR](64) NOT NULL,
[Quantity] [INT] NOT NULL CHECK (Quantity > 0),
PRIMARY KEY CLUSTERED ([Sku] ASC)
);

You can test it works for valid values using the following SQL:

DECLARE @Skus SkuListWithQuantity
INSERT INTO @Skus (Sku, Quantity) VALUES ('FBIUN140095', 21), ('KLIJJ146314', 10)
SELECT * FROM @Skus

You can test it with an invalid Quantity value using the following SQL:

DECLARE @Skus SkuListWithQuantity
INSERT INTO @Skus (Sku, Quantity) VALUES ('FBIUN140095', 0), ('FBIUN140095', 10)
SELECT * FROM @Skus

You will receive an error like:

Msg 547, Level 16, State 0, Line 2
The INSERT statement conflicted with the CHECK constraint “CK__#5165187F__Quant__52593CB8”. The conflict occurred in database “tempdb”, table “@Skus”.
The statement has been terminated.

You can test it with a duplicate Primary Key value using the following SQL:

DECLARE @Skus SkuListWithQuantity
INSERT INTO @Skus (Sku, Quantity) VALUES ('FBIUN140095', 21), ('FBIUN140095', 10)
SELECT * FROM @Skus

You will receive an error like:

Msg 2627, Level 14, State 1, Line 4
Violation of PRIMARY KEY constraint ‘PK__#5CD6CB2__CA1FD3C45EBF139D’. Cannot insert duplicate key in object ‘dbo.@Skus’. The duplicate key value is (FBIUN140095 ).
The statement has been terminated.

Resolving issue with website not running locally on port 443

I recently had issue an issue with a website not working locally on port 443. I figured out that another service was using this port, which was Skype.

I figured this out by following the steps below that I discovered on the the webpage http://www.tonerdesign.biz/web-design/46-learning-about-netstat.html

  • Run the following command on Command prompt:
    netstat -aon
  • Read through the result to see what is listening to port 443 and take a note of the PID
  • Finally open task manager and view processes. Sort processed by PID and locate PID in question. If PID column isnt shown you will need to add it

PowerShell scripts to remotely manage Windows Services

Following on from a previous post I published on how to remotely manage IIS via PowerShell scripts I thought it would be useful to detail how to also manage Windows Services remotely.

RESTART A WINDOWS SERVICE
Get-Service -Name [INSERT_SERVICE_NAME]  -ComputerName [INSERT_COMPUTER_NAME] | Restart-service

Example:

Get-Service -Name Jonathan.Welch.Test.Service  -ComputerName jon-app-01 | Restart-service
STOP A WINDOWS SERVICE
Get-Service -Name [INSERT_SERVICE_NAME]  -ComputerName [INSERT_COMPUTER_NAME] | Stop-service

Example:

Get-Service -Name Jonathan.Welch.Test.Service  -ComputerName jon-app-01 | Stop-service
START A WINDOWS SERVICE
Get-Service -Name [INSERT_SERVICE_NAME]  -ComputerName [INSERT_COMPUTER_NAME] | Start-service

Example:

Get-Service -Name Jonathan.Welch.Test.Service  -ComputerName jon-app-01 | Start-service
START A DISABLED WINDOWS SERVICE
Get-WmiObject Win32_Service -ComputerName [INSERT_COMPUTER_NAME] | ? { $_.Name -Match '[INSERT_SERVICE_NAME]' -and $_.StartMode -ne 'Disabled' } | % { $_.StartService() }

Example:

Get-WmiObject Win32_Service -ComputerName jon-app-01 | ? { $_.Name -Match 'Jonathan.Welch.Test.Service' -and $_.StartMode -ne 'Disabled' } | % { $_.StartService() }

Note that in the examples above you can append a * to the end of service name to find services that match that name. So you could shorten the name to Jonathan.Welch* to find all services with names that start with Jonathan.Welch