Learning Git – some links

About six months ago at we work we started to look into migrating from TFS to Git.  This migration was put on hold for my team until we had finished work on an important project that needed to be delivered in March.  Now that the project is live we have started to look at migrating again.

Before we can make the move we wanted to up skill our team as a lot of us hadn’t really worked with GIT before.  When we first looked at Git I collated a list of links with useful learning material, which I have now discovered again and thought I’d share on my blog.

Pluralsight

I created a Channel on Pluralsight that includes a selection of the Git courses that they offer.  So if you are lucky enough to have a Pluralsight account you can view the channel here 

The channel includes the following courses:

Gitflow

Other Resources

Implicit Types (C#)

Although there is nothing wrong with giving a local variable an explicit type, such as int or string,  I more than often use the var keyword to implicitly type a local variable.  When you do this the compiler provides the type at compile time.  It does this by inferring the type of the variable from the expression on the right side of the initialization statement.
You can also use the var keyword in forforeach and using statements.

Benefits

I feel that using var keyword in my code makes it quicker to write and easier to read.  It is certainly my preference when the type is obvious.

Restrictions

  • You can not implicitly type class members (i.e. Fields).
  • You can only use var when declaring and initializing variable in the same statement
  • You can not initialize with a null value
  • You can not initialize with a method group
  • You can not initialize with an anonymous function
  • You can not initialize multiple variables in the same statement

Local variables examples

int example

var j = 17;

string example

var firstName = "Fred";

List example

var employees = new List<string> { "Fred Blogs", "James Kane", "Jon Jones"};

anonymous type example

var employee = new { Name = "Fred Bloggs", Age = 23 };

IEnumerable example

This example is for the type IEnumerable

var customers = new CustomerQuery().FindAll();

var customersNamedFred = from c in customers
                         where c.FirstName == "Fred"
                         select c;

This example is for the type IEnumerable

var customers = new List<Customer>
{
   new Customer { FirstName = "Fred", LastName = "Bloggs" },
   new Customer { FirstName = "Jacon", LastName = "Creaker" }
};

var customersNamedFred = from c in customers
                         where c.FirstName == "Fred"
                         select c;

This example is for the type IEnumerable<‘a> (anonymous type)

 var customerTuple = new List<Tuple<string, string>>
 {
     new Tuple<string, string>("Fred", "Bloggs"),
     new Tuple<string, string>("Jacon", "Creaker")
 };

 var customers = customerTuple.Select(t => new { 
                              FirstName = t.Item1, 
                              LastName = t.Item2 }).ToList();

 var customersNamedFred = from c in customers
                          where c.FirstName == "Fred"
                          select c;

for and foreach initialization statement examples

 

for initialization statement example

for (var i = 0; i < 100; i++)
{
   Console.WriteLine(i);
}

foreach initialization statement example

var customers = new List<string> { "Fred Blogs", "James Kane", "Jon Jones"};
foreach (var customer in customers)
{
   Console.WriteLine(customer);
}

using statement example

using (var httpClient = new HttpClient())
{
   var response = httpClient.GetStringAsync("http://www.google.com").Result;               
}

Git Hub Repository

I have created a repository on GitHub that included the code examples of Implicit Types. The examples were written as NUnit tests to showcase that the expected type is created.

https://github.com/JonathanWelch/Implicit-Types

Useful links

Implicitly Typed Local Variables (C# Programming Guide)

Testing roles in Authorize attribute on a ASP.NET Web API Controller

Recently at work we had to restrict access to a ASP.NET Web API Controller to users in two specific Active Directory groups.  We also wanted to create a test that verified this change and I thought it would be nice to share the approach we took to add some coverage.

The Employee Controller

[Authorize(Roles = @"MYDOMAIN\HR,MYDOMAIN\Admin")]
public class EmployeeController : ApiController
{
....

}

The Test

The test we came up with used reflection and ensured that the expected roles were set-up to be authorized.

    [TestFixture]
    public class EmployeeControllerShould
    {
        [TestCase(@"MYDOMAIN\HR")]
        [TestCase(@"MYDOMAIN\Admin")]
        public void Authorize_for_users_in_role(string role)
        {
            var controllerType = typeof(EmployeeController);
            var attribute = (AuthorizeAttribute)controllerType.GetCustomAttribute(typeof(AuthorizeAttribute), false);

            Assert.That(attribute.Roles, Is.StringContaining(role));
        }        
    }

Pluralsight @ ASOS

I recently got interviewed at my work, ASOS.com, as part of an initiative to encourage more colleagues to use Pluralsight as an on-line tool to improve their skill-set.

Everyone in the IT department can obtain a licence and I personally have found it to be an extremely useful and informative resource of quality training material.  It also allows you to view videos offline, which I find great for the commute into work!

You can view the video on YouTube.  You can see me at 1:22, 2:19 and 5:13.

Further PowerShell scripts to manage Windows Services

Following on from the previous post I published on remotely managing Windows Services with PowerShell I thought it would be useful to add some extra scripts that you can use to work with Windows Services.

GET DETAILS FOR A WINDOWS SERVICE
Get-Service -Name [INSERT_SERVICE_NAME]  -ComputerName [INSERT_COMPUTER_NAME]  | Format-Table –AutoSize

Example:

Get-Service -Name Jonathan.Welch.Test.Service  -ComputerName jon-app-01 | Format-Table –AutoSize
GET DETAILS FOR WINDOWS SERVICE THAT MATCH SUPPLIED NAME CRITERIA
Get-Service -Name [INSERT_PART_OF_SERVICE_NAME]*  -ComputerName [INSERT_COMPUTER_NAME]  | Format-Table –AutoSize

Example:
This script will find all services that start with Jonathan.Welch

Get-Service -Name Jonathan.Welch*  -ComputerName jon-app-01 | Format-Table –AutoSize
GET DETAILS FOR A WINDOWS SERVICE ON MULTIPLE SERVERS
$computers = @("[INSERT_COMPUTER_NAME_1]", "[INSERT_COMPUTER_NAME_2]")
Get-Service -Name [INSERT_SERVICE_NAME]  -ComputerName $computers | Select MachineName, Name, Status | Sort MachineName, Name | Format-Table –AutoSize

Example:

$computers = @("jon-app-01", "jon-app-02")
Get-Service -Name Jonathan.Welch.Test.Service  -ComputerName $computers | Select MachineName, Name, Status | Sort MachineName, Name | Format-Table –AutoSize
WRITE A COMMENT TO CONSOLE
#Hello World!

SQL Server – Discover tables that are replicated

Here are some useful SQL Scripts to get the details of what tables are included in replication in the database the query is connected to.

SELECT		*
FROM		sys.tables
WHERE		is_replicated = 1
ORDER BY	name

The script below will provide extra details on the subscriptions.

SELECT		publisher=sysservers.srvname, 
		subscriber_db=dest_db, 
		Subscriber=syssubscriptions.srvname, 
		article_name=sysarticles.name,
		syspublications.name AS PublicationName
FROM		syssubscriptions 
JOIN		sysarticles 
ON		syssubscriptions.artid=sysarticles.artid
JOIN		master.dbo.sysservers 
ON		syssubscriptions.srvid =sysservers.srvid
JOIN		syspublications 
ON		syspublications.PubId = sysarticles.pubid
ORDER BY	article_name

Additionally you could use the query below to find replication details for a specific table. The example is checking the Customer table

SELECT		P.name Publication,
		A.name TableName,
		A.dest_table DestinationTable 
FROM		syspublications P 
INNER JOIN	sysarticles A ON P.pubid = A.pubid
WHERE		A.name ='Customer'

Write code that is easy to read – Clean Code Post 4

Writing code is relatively easy, but reading it can be hard if care has not been taken by the Author of the code. Taking the time to write clean code pays off as you are not just making your live easier, if you have to revisit code, but you are also making future readers of your code lives easier too.

Writing sloppy code injects technical debt into your code base and as you may know technical debt is depressing. Technical debt de-motivates people and will potentially drive people away from your organisation.

Being sloppy slows you down in the long run as your code is likely to have bugs and need tidying up in the future.

One thing you can do to improve the quality of you code you are writing is to follow the TED rule:

Terse
Your code should not be excessively wordy

Expressive:
It is clear what your code is trying to do

Do one thing
Your code should have a clear responsibility. It should do that one thing well

Make use of Enums – Clean Code Post 3

It is better to make use of an Enum than to use hardcoded strings in your code. I have heard the use of hardcoded strings be referred to as Stringly Typed rather than Strongly Typed. Using an Enum would make your code Strongly Typed.

Here is an example of some bad Stringly Typed code:

if (customerType == "Premier")
{
                
}

Here is an example of how you can improve this code by making use of an Enum called CustomerType:

if (customer.Type == CustomerType.Premier)
{
               
}

The code to define the CustomerType Enum is below.

public enum CustomerType
{
   Standard, Elevated, Premier
}

By default, the first enumerator has the value 0, and the value of each successive enumerator is increased by 1. In the CustomerType enumeration above, Standard is 0, Elevated is 1 and Premier is 2. If you wanted to assign different values you can do something like the code below:

public enum CustomerType
{
   Standard = 100, 
   Elevated = 200, 
   Premier = 300
}

If you want to retrieve the integral value from an Enum you can use the code below:

   var customerType = (int)customer.Type;

Make use of Ternary (Conditional) Operator – Clean Code Post 2

It is more elegant in code to use the Ternary Operator than an IF statement. The Ternary Operator is also commonly known as the Conditional Operator.

Here is a C# example of a Ternary Operator in use:

int bonus = employee.Age < 50 ? 20 : 40;

You can see that it takes up less lines of code then the IF statement below:

int bonus;

if (employee.Age < 50)
{
  bonus = 20;
}
else
{
  bonus = 50;
}

You can see that it is much cleaner to use the Ternary Operator and results in using one line of code rather than ten.