Send mail to the author(s) E-mail

# Friday, 02 September 2016
( Azure | Git )

Git reset --hard asdf

Git clean –xfd


to make sure the azure web app is clear:


or better (Advanced Tools from just below Console above)..debug console CMD


| | # 
# Tuesday, 21 June 2016
# Wednesday, 06 April 2016
( Git )

I’ve come across a situation where the only way to have git is to install it locally, then push to a safe backed up fileshare.

Setup a bare repo on the fileshare

git init –bare

Add a remote

git init
git add .
git commit –m “initial commit”
git remote add origin file://j:\git\test  -- add a remote called origin…  note file://h:\\git\\booktech notice escapes in gitbash
git push --set-upstream origin master

Clone test

git clone j:\git\test .

| | # 
# Friday, 21 August 2015
( Chrome | Git | Notepad++ | SSMS )

Show bookmarks in Chrome – Ctrl Shift B

Delete line SSMS – Shift Delete

Notepad++ in shell (npp) -

Git difftool setup
cd ~ 
which is c:\Users\Dave\.gitconfig

    tool = vsdiffmerge
      prompt = false
[difftool "vsdiffmerge"]
      cmd = '"C:/Program Files (x86)/Microsoft Visual Studio 14.0/Common7/IDE/vsdiffmerge.exe"' "$LOCAL" "$REMOTE" //t
      keepbackup = false
      trustexitcode = true
      tool = vsdiffmerge
      prompt = false
[mergetool "vsdiffmerge"]
      cmd = '"C:/Program Files (x86)/Microsoft Visual Studio 14.0/Common7/IDE/vsdiffmerge.exe"' "$REMOTE" "$LOCAL" "$BASE" "$MERGED" //m
      keepbackup = false
      trustexitcode = true

| | # 
# Friday, 12 June 2015
( Git )

ssh-keygen and save to C:\Users\David\.ssh\id_bitbucket

create a file named config in C:\Users\David\.ssh

Put SSH key into Bitbucket

IdentityFile ~/.ssh/id_bitbucket

The indent is important

| | # 
# Thursday, 11 June 2015
( Git )
  • Work on own repo pushing up to GitHub (masterbranch workflow)
  • Work stuff / opensource Featurebranch

Master branch (create repo)

mkdir GitTest2 
Git init
copy .gitignore
npp README.txt  - have setup notepad++ to this shortcut
git add .
git commit –m “Adding first README”
git lga – shortcut for git log --graph --oneline --all –decorate
git commit –am “Second README message”  - shortcut for commit if file already there

git remote –v  - view remotes
git remote add origin
git remote set-url origin new_url  - for updating the url
git checkout – readme.txt – throw away any changes (file not in staging or committed)git push –u origin master

git checkout – readme.txt – throw away any changes (file not in staging or committed)
git reset head readme.txt – bring out of staging

git reset –hard – throws away any uncommitted changes
git reset –hard HEAD~1  -- goes back to second last commit

Feature branch

git checkout -b feature1
git checkout master
git merge feature1
git branch -d feature1

git mergetool  --for when there are merge conflicts (I use vs difftool)

git commit --amend file2 – when you’ve made a commit, and want to add something to it or change the message
git commit --amend  -- just gets the last commit in text editor

Remote branches
git branch  -shows local branches
git branch --r  -shows remote branches

git push origin feature3  - push the local branch to the remote

Feature Branch (clone)

git clone
git push origin feature3
git remote update - check to see if any changes on the remote branch

When you stage files, then realise the .gitignore file needs updating

| | # 
# Friday, 29 May 2015
( Git )

git log -1 
This gives the latest SHA1

git diff
See the latest diffs

| | # 
# Thursday, 05 February 2015
( Git )

git config --global core.autocrlf false

“The warning "LF will be replaced by CRLF" says that you (having autocrlf=true) will lose your unix-style LF after commit-checkout cycle (it will be replaced by windows-style CRLF). Git doesn't expect you to use unix-style LF under windows”

So ‘true’  might be better because Git will eventually fix (after commit and then checkout) any files that for some reason end up having LF in them

The down side of it is that we will sometimes get this warning if we’ve got some weird tools that keep putting LFs in

| | # 
# Tuesday, 07 October 2014
( Git )

To get this working easily, install GitHub for Windows!


execute these lines in the console:

git config --global color.status.changed "cyan normal bold"
git config --global color.status.untracked "cyan normal bold"

$profile – couldn’t get this working, so hacked in the version of GitPrompt.ps1 which will get overwritten on updates


    # WorkingForegroundColor    = [ConsoleColor]::DarkRed
    WorkingForegroundColor    = [ConsoleColor]::Yellow
    WorkingBackgroundColor    = $Host.UI.RawUI.BackgroundColor

    UntrackedText             = ' !'
    # UntrackedForegroundColor  = [ConsoleColor]::DarkRed
    UntrackedForegroundColor  = [ConsoleColor]::Yellow
    UntrackedBackgroundColor  = $Host.UI.RawUI.BackgroundColor


Setting defaults:

Consolas 16 worked (run powershell as admin to make stick)

| | # 
# Sunday, 28 September 2014
( Git )

Branching and Committing

git branch recb
git checkout recb
git checkout –b recb

git add test.txt
git commit test.txt –m “add test.txt”

git checkout master  - file is gone
git checkout recb


git checkout master
git merge recb

Push to Github/Remote

git push origin master
git push -u origin recc  (so that future pulls can work.)

Delete Locally and Remote

git branch -D recc
git push origin --delete recc

Clone Locally

To see what is actually in the repo

mkdir test (anywhere in filesystem)
git clone c:\dev\solidjokes

Discard Uncommitted Changes

git checkout – .  (minus minus space dot)

git clean –xfdn  (get rid of any untracked files..warning
   n – dry run
   x – directories

Preview Changes of a Merge

git log ..nameOfBranch

Edit a Commit Message

git commit --amend -m "New commit message"

Rename a Branch

git branch –m CC_7_6_DM

Stash - Error changing Branch

After working on a branch, and wanting to leave it (in probably a dirty state)

error: Your local changes to the following files would be overwritten by  checkout
Please, commit your changes or stash them before you can switch branches

git stash list

git stash apply

**this didn’t work well for me.  Would have been better to commit the changes… or just do git checkout – . (discard uncommitted changes)

List Untracked Files

git ls-files . –exclude-standard –others (minus minus)

git ls-files . –exclude-standard –others –ignored

Ignore Web.Config

git update-index --assume-unchanged path_to_file/web.config

| | # 
# Friday, 25 July 2014
( Git )

This solves the problem in VS2013 git - it can get confused and seemingly ignore the gitignore file.

Take an existing solution eg:

Already compiled, and has NuGet packages

Do a git init from the command line.

Make a  .gitignore.   (otherwise windows wont let you name it), a good community example is from

Add all files to git

Open up the solution, and now we have everything excluded that we want

Push to GitHub

Then do a clone in VS as a sanity check


NuGet getting packages as it should.  Cloned solution works.

| | # 
# Tuesday, 10 June 2014
( Git | TFS )

Create Team Project in

Connect to it, in VS

Clone the repo

New solution (in team explorer)

Ahh - then gitignore doesn't work for packages

| | # 
# Monday, 09 June 2014
( Git | TFS )

Watch out for branches on the remote which you may not have brought down to your local

if using MINGGW32 terminal watch out for slashes:

git pull e:/dev/oldRepo

If I wanted all the branches then:

| | # 
# Friday, 06 June 2014
( Git | TFS )

Git Design Goals:

  • Speed
  • Simplicity
  • Strong branch/merge
  • Distributed
  • Scales well

Git with TFS

Signed up to tfsonline in

A Project can contain multiple solutions (repositories)


Made a new repo up there.

Open VS, connect to TFS Online, then clone this blank repo to e:\dev\test\DavesJokes


But then dll's in projects folder.  So switched to this .gitignore file:

image  - yes, this is a bug

Right click and just exclude the Packages folder.

Committed using SourceTree so don't put in packages folder.

Interestingly VS doesn't use the staging part of Git (mostly).

Work Items

Click New Work Item in blue on RHS.

Did some changes on HomeController.cs

Can do a simple compare between 2 versions.

Add a Work Item to a Checkin

Drag the work item over to RHS.

Can see the work item related to the commit.

Commit and Sync - means do a pull/push

Branching and Merging

TFS Projects

Project level dashboard



A TFS Team Project can contain multiple git repositories :-) But this seems like a bad idea..maybe good with a scratch demo directory.

TFS Team Project is DavesJokes3 (top of screen in blue) and repository is DavesJokes3

Adding a new Git repository to this team project.  However this will break work item tracking: **actually it may be fixed now.

| | # 
# Friday, 02 May 2014
( Git )

Garbage collect (not totally necessary)

git count-objects -v
git gc

Maybe --aggressive

Branching strategy

For a 2 person team with a central remote (windows fileshare)

  • Don't push broken stuff to the remote
  • Use feature branches
    • merge into master then push
    • can push feature branch (other dev could pull that feature branch?)
| | # 
# Thursday, 10 April 2014
( Git )

Using Staging to try to only commit important bits

Not using branches yet

pushing to a named shared directory on remote server

| | # 
# Wednesday, 05 March 2014
( Git )

Make sure git working locally to start with:

used Cygwin (GitBash).. powershell crashed.

to change drives use cd o:

  • make a new directory on remote called O:\myrepo.git
  • inside O:/myrepo.git/git init –bare
  • locally: git remote add edin O:/myrepo.git
  • git remote –v (to view remotes)
  • git push edin master (pushing to the master branch of the origin)

edin here is Edinburgh.  Usually origin

  • git clone z:/test.git (to setup)
  • do changes
  • git push origin master
  • git pull origin master - to make sure am up to date
  • git status - to see if ahead or behind
| | # 
# Thursday, 20 February 2014
( Git )

When deleting a large number of files

git commit –a –m “deleting”


| | # 
# Thursday, 09 January 2014
( Git )

Didn’t put up packages folder.  Nor Web\Properties\PublishProfiles\britishhumour.pubxml

Used this:

| | # 
# Thursday, 24 October 2013
( Git )


Then went to add solution to source control


Followed these, but no key.. just using password in command prompt.  Pushed up there.

| | # 
# Monday, 02 September 2013
# Tuesday, 05 June 2012
( Euler | Git | Resharper )

Am trying out using git now on every project - mainly so I can easily revert if I mess things up.  Good practice.

git init

git add .

git commit -m "first commit of Euler 15"

git checkout -b firsttry

git branch (to see branches)



R# – Move to another file with same name


The formula is n! / r! (n-r)!

Where n is 40 and r is 20…  so 40!/(20! * 20!)

Which gives us:    137846528820 ways to get there!

In fact Google’s online calculator can do this for you….

Just type 40 choose 20 into Google!!


Discrete Mathematics

– on a 2*2 square it takes 4 steps to reach the end. So on a 20*20 square it takes 40 steps.

20 increases in x and 20 increases in y

how many different ways can you choose 20 elements out of a set of 40 elements.

We can use a formula to solve this. “n choose r formula”: N!/r!(n-r)


N = number of elements (40)

r = how many we want to choose


Dynamic Programming

How many routes are there through a 20×20 grid? or.. total number of ways to arrive at a node?

dynamic programming is a method for solving complex problems by breaking them down into simpler subproblems

We find the total number of ways to arrive at a node:

“Sum of the count from above and to the left”

public class DynamicProgrammingTests
    private DynamicProgramming dynamicProgramming;

    public void DoFirst()
        this.dynamicProgramming = new DynamicProgramming();

    public void Four_DynamicProgrammingSolver_GivesAnswerOf70()
        var result = dynamicProgramming.Solve(4);
        Assert.AreEqual(70, result);

    public void Five_DynamicProgrammingSolver_GivesAnswerOf252()
        var result = dynamicProgramming.Solve(5);
        Assert.AreEqual(252, result);

    public void Twenty_DynamicProgrammingSolver_GivesAnswerOf252()
        var result = dynamicProgramming.Solve(20);
        Assert.AreEqual(137846528820, result);

//using property of problem that
//total number of ways to arrive at a node
//is count from left and above
//so we build an array with total number of ways to arrive at a node
public class DynamicProgramming
    public double Solve(int sizeOfGrid)
        var array = new double[sizeOfGrid+2, sizeOfGrid+2];

        int i, j;
        array[1, 1] = 1;
        for (i = 1; i <= sizeOfGrid+1; i++)
            for (j = 1; j <= sizeOfGrid+1; j++)
                //count from left, then count from above
                array[i, j] += array[i - 1, j] + array[i, j - 1];
        double result = array[sizeOfGrid+1, sizeOfGrid+1];
        return result;

put in photo here of array with answers in it.

Brute Force – Recursive

public class SolverTests
    private BruteForceRecursionSolver bruteForceRecursionSolver;
    public void DoThisAtStart()
        this.bruteForceRecursionSolver = new BruteForceRecursionSolver();
    public void TwoGivesAnswerOf6()
        bruteForceRecursionSolver.gridSize = 2;
        var result = bruteForceRecursionSolver.Progress(0, 0);
        Assert.AreEqual(6, result);

    public void ThreeGivesAnswerOf20()
        bruteForceRecursionSolver.gridSize = 3;
        var result = bruteForceRecursionSolver.Progress(0, 0);
        Assert.AreEqual(20, result);

    public void FourGivesAnswerOf70()
        bruteForceRecursionSolver.gridSize = 4;
        var result = bruteForceRecursionSolver.Progress(0, 0);
        Assert.AreEqual(70, result);

    public void FiveGivesAnswerOf252()
        bruteForceRecursionSolver.gridSize = 5;
        var result = bruteForceRecursionSolver.Progress(0, 0);
        Assert.AreEqual(252, result);

    public void TenGivesAnswerOf184756()
        bruteForceRecursionSolver.gridSize = 10;
        var result = bruteForceRecursionSolver.Progress(0, 0);
        Assert.AreEqual(184756, result);

    public void ElevenGivesAnswerOf705432()
        bruteForceRecursionSolver.gridSize = 11;
        var result = bruteForceRecursionSolver.Progress(0, 0);
        Assert.AreEqual(705432, result);

public class BruteForceRecursionSolver
    public int gridSize;

    // top left is 0,0
    public int Progress(int x, int y)
        int i = 0;

        if (x < gridSize)
            //favours going right
            i += Progress(x + 1, y);
        if (y < gridSize)
            i += Progress(x, y + 1);

        //reached bottom right
        if (x == gridSize && y == gridSize)
            return 1;
        return i;

This is very much brute force..

This took about 1.5 hours:

public class SolveRecursion
        public long Combination = 0;
        public int GridSize;

        public void CalculateCombination(int x = 0, int y = 0)
            if (x < GridSize)
                CalculateCombination(x + 1, y);
            if (y < GridSize)
                CalculateCombination(x, y + 1);
            if (x == GridSize && y == GridSize)
static void Main(string[] args)
            //gives correct answer: 137,846,528,820
            Stopwatch stopWatch = new Stopwatch();
            var solveRecursion2 = new SolveRecursion { GridSize = 20 };
            var result = solveRecursion2.Combination;
            TimeSpan ts = stopWatch.Elapsed;
            Console.WriteLine("Result is: {0}, time was {1} seconds", result, ts.ToString());

and non recursive thoughts on:

| | # 
# Tuesday, 25 October 2011
( Git )



I did all this (using an existing repo)


follow instructions here!

| | # 
# Wednesday, 21 September 2011
( Code Snippets | Git | TekPub | VidPub )

Custom Membership..forms.

Don’t advocate roll own membership

ASP.NET Membership works if

  • SQL Server forever
  • Forms auth
  • Can login multiple times


TDD/BDD do this.

  • NUnit

Code Snippets

To help with mundane writing code in unit tests.

Ctrl K Ctrl B  Kevin Dentes Blogs and nunit snippets **not imported yet as wasn’t in .snippet format

Libraries\Documents\Visual Studio 2010\Code Snippets\Visual C#\My Code Snippets

Git console in VS

Tools/External menu.


which then appears in the Tools menu as git.  Change to &g for keyboard accelerator.


Feature branch in Git

Master is for finalised and deployed (?) code

git branch (to see current branches)

git checkout –b membership












git add .

Global GitIgnore

git config –global core.excludesfile c:/dev/Global.gitignore

Test 1 – Not Accept Email with < 6 Chars


Alt + T  reassigned for run tests in TestDriven.Net

Alt + D run tests in debug

Code Snippet
public class TestBase {
        public void Describes(string description) {

        public void isPending() {
            Console.WriteLine(GetCaller() + " -- PENDING --");

        public string GetCaller() {
            StackTrace stack = new StackTrace();
            return stack.GetFrame(2).GetMethod().Name.Replace("_", " ");

So can get a bit of nice debug in output window:


YAGNI – writing smallest amount of code to make test pass.. weird but good.


Code Snippet
    public class MembershipSpecs : TestBase{
        public MembershipSpecs() {
            this.Describes("User Registration");

        public void registration_should_not_accept_email_with_lt_6_chars() {
            var membership = new Membership();
            var result = membership.Register("", "password", "password");

and simplest possible implementation (not really, but Rob has an end in mind)

used Ctrl . in VS to make Membership class and file, and method.

Code Snippet
public class Membership {
        public dynamic Register(string email, string password, string confirm) {
            dynamic result = new ExpandoObject();
            result.Success = false;
            return result;


Code Snippet
      public void registration_should_not_accept_email_with_lt_6_chars() {
          var result = _membership.Register("e", "password", "password");

      public void registration_should_not_accept_password_with_lt_6_chars() {
          var result = _membership.Register("", "x", "x");

      public void registration_should_not_accept_mismatched_passwords() {
          var result = _membership.Register("", "password1", "password2");

testing the False cases

Code Snippet
public dynamic Register(string email, string password, string confirm) {
            dynamic result = new ExpandoObject();
            result.Success = false;
            if (email.Length >= 6 && password.Length >=6 && password.Equals(confirm))
                result.Success = true;
            return result;

Persist Information to DB – Massive

Rails doesn’t matter to goto db..can be fast enough.

SQL CE4 in App_Data in Test project.  **This didn’t work.. am using SQL Server**


Seed on ID the PK.  getdate() on 3 date fields as default.

How to persist data?  Simplest possible for now is Massive.. a Dynamic ORM in 500lines or do.


Test 2 – Registration Should Not Accept Duplicate Emails

Test is something like:

        public void registration_should_not_accept_duplicate_emails() {
            var result = _membership.Register("", "password", "password");
            var result2 = _membership.Register("", "password", "password");

so need persistence to test this:

Going to clean the db before each test!

Massive works by translating the properties of the anonymous object into column names:

Problem:  Couldn’t get Massive to connect to SQLServerCompact4.0 database with connection string:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>   <connectionStrings>     <add name="Membership"      connectionString="Data Source=C:\Dev\VidPub\Source\VidPub.Tests\App_Data\Membership_Test.sdf"      providerName="System.Data.SqlServerCE.4.0" />   </connectionStrings>

installed classic 2000 Northwind sample:   then look in C:\SQL Server 2000 Sample Databases – Interesting talk from Norway on Data access history.

Now I can get a console App to talk to SQL Server Compact 4.0 :

string connectionString = ConfigurationManager.ConnectionStrings["southwind"].ConnectionString;

            //SqlCeConnection connection = new SqlCeConnection(@"Data Source=SouthWind.sdf");
            SqlCeConnection connection = new SqlCeConnection(connectionString);

            SqlCeCommand command = new SqlCeCommand("SELECT * FROM People", connection);
            SqlCeDataAdapter dataAdapter = new SqlCeDataAdapter(command);
            DataSet ds = new DataSet();

now I need to get Massive talking to that db.

I can kind of get it working by changing the _providerName to

            var _providerName = "System.Data.SqlServerCE.4.0"; here is a fix by pulling from the App.config.

Getting strange errors!

Reverting to SQL Server

    <!--<add name="Membership" providerName="System.Data.SqlServerCE.4.0" connectionString="Data Source=C:\Dev\VidPub\Source\VidPub.Tests\Membership_Test.sdf" />-->
    <add name="Membership" providerName="System.Data.SqlClient" connectionString="Data Source=.\;Initial Catalog=Membership_Test;Integrated Security=SSPI;" />

and change provider name back to:

var _providerName = "System.Data.SqlClient";
and to put a unique constrant on SQL Server column:

Code Snippets


testn is setup for me to produce:

 [Test]         public void MyTestMethod() {                      }
| | # 
# Tuesday, 20 September 2011
( Git | Glimpse | MVC | Ninject | NLog | VidPub )

Notes from TekPub ASP.NET MVC3 series of tutorials.

  • Startup – big idea.. charge people money for
  • Good idea, well executed
  • Get site out there and pay the bills!

Why MVC3 in this Fast Paced Startup?

  • Good stable version of MVC
  • I know C#

What are we doing (Elevator pitch) and when are we going to do it?

1 sentence!

Platform and Tools


Unfuddle for project mgt


or agilezen (kanban)

Source is on

Setup a new MVC3 solution called VidPub.Web


Lib is for external dlls.  Docs are for docs.  Everything is under git

git init in \dev\VidPub

git add .

git commit –am “Initial load”


mkdir e:\dropbox\repositories\vpub


in e:\dropbox\repositories\vpub

git init –bare

from \dev folder  git push origin master


So other people can then pull from that repository… it is the whole repo up there, not just source.

Test Project

Have just created a container.


Don’t want concurrent authentcation.. ie users sharing accounts.  Could use token based.

Now, 1 Year, 3 Years

ASP.NET Membership – complicated..

Consistency of FileNames



no more content directory

Model\AccountModels.cs to AccountModel

change CSS path in _Layout.cshtml



make faster for user as they may have this cached in their browser.  Also save us a bit of bandwidth.  Cache up to a year.

If using Azure to host MSDN have got some benefits.


NLog using NuGet

Code Snippet
<nlog xmlns="" xmlns:xsi="" >

    <!--Useful for debugging-->
    <target name="console" xsi:type="ColoredConsole"
     layout="${date:format=HH\:mm\:ss}|${level}|${stacktrace}|${message}" />

    <target name="file" xsi:type="File" fileName="${basedir}/App_Data//logs/site.log"
     layout="${date}: ${message}" />

    <target name="eventlog" xsi:type="EventLog" source="My App" log="Application"
    layout="${date}: ${message} ${stacktrace}" />



    <logger name="*" minlevel="Info" writeTo="file" />
    <logger name="*" minlevel="Fatal" writeTo="eventlog" />



in dev we’re going to log everything to a file in App_Data/logs

In \Infrastructure we’ve got some code to help us log with an interface extracted.

Code Snippet
public class NLogger : VidPub.Web.Infrastructure.Logging.ILogger {
        Logger _logger;
        public NLogger() {
            _logger = LogManager.GetCurrentClassLogger();
        public void LogInfo(string message) {

        public void LogWarning(string message) {

        public void LogDebug(string message) {

        public void LogError(string message) {
        public void LogError(Exception x) {
        public void LogFatal(string message) {
        public void LogFatal(Exception x) {
        string BuildExceptionMessage(Exception x) {

            Exception logException = x;
            if (x.InnerException != null)
                logException = x.InnerException;

            string strErrorMsg = Environment.NewLine + "Error in Path :" + System.Web.HttpContext.Current.Request.Path;

            // Get the QueryString along with the Virtual Path
            strErrorMsg += Environment.NewLine + "Raw Url :" + System.Web.HttpContext.Current.Request.RawUrl;

            // Get the error message
            strErrorMsg += Environment.NewLine + "Message :" + logException.Message;

            // Source of the message
            strErrorMsg += Environment.NewLine + "Source :" + logException.Source;

            // Stack Trace of the error

            strErrorMsg += Environment.NewLine + "Stack Trace :" + logException.StackTrace;

            // Method where the error occurred
            strErrorMsg += Environment.NewLine + "TargetSite :" + logException.TargetSite;
            return strErrorMsg;


So we don’t have anything coupled tightly right from the start (eg logging which we’re doing next).. lets use IoC


Wire up in global.asax

 public class MvcApplication : NinjectHttpApplication  {

**NO this is not correct as in MVC3 it is bootstrapped, so just leave as:

public class MvcApplication : System.Web.HttpApplication {

Setting up logging in App_Start bootstrapper file.

“Every time you see a request for ILogger interface in a controller, return a new NLogger class”



added in Logs/Site.log into our project.


Added in bookmarks into bar to turn on and off.


git add .

git commit –am “Added logging, IoC and rearranged stuff”

git push origin master (to save to dropbox)


current state of play of our filesystem.


| | #