Search

Categories

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Send mail to the author(s) E-mail

# Friday, 02 September 2016
( Azure | Git )

Git reset --hard asdf

Git clean –xfd

Azure

to make sure the azure web app is clear:

image

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

image

| | # 
# 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

j:\git\test
git init –bare

Add a remote

c:\dev\test
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

c:\dev\test2
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) - http://superuser.com/a/802913/12214

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

[diff]
    tool = vsdiffmerge
[difftool]
      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
[merge]
      tool = vsdiffmerge
[mergetool]
      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

Host bitbucket.org
IdentityFile ~/.ssh/id_bitbucket

The indent is important https://confluence.atlassian.com/display/BITBUCKET/Set+up+SSH+for+Git

| | # 
# 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@github.com:djhmateer/GitTest2.git
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@github.com:djhmateer/GitTest2.git
git push origin feature3
git remote update - check to see if any changes on the remote branch

GitIgnore

http://www.kickasslabs.com/2010/02/06/quick-hits-when-your-gitignore-file-gets-ignored/
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

http://stackoverflow.com/questions/17628305/windows-git-warning-lf-will-be-replaced-by-crlf-is-that-warning-tail-backwar

“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”

http://stackoverflow.com/a/20653073/5351

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!

image

http://sedodream.com/2012/05/05/GitCustomizingColorsForWindowsIncludingPoshgit.aspx

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

C:\Users\davidma\AppData\Local\GitHub\PoshGit_3874a02de8ce2b7d4908a8c0cb302294358b972c\GitPrompt.ps1

    # 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:

http://superuser.com/questions/685810/powershell-font-too-small-on-windows-8-1-how-to-adjust

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

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

Branching and Committing

git branch recb
git checkout recb
OR
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

Merge

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.)

http://stackoverflow.com/questions/1519006/how-do-you-create-a-remote-git-branch

Delete Locally and Remote

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

http://stackoverflow.com/questions/2003505/how-to-delete-a-git-branch-both-locally-and-remotely

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..warninghttp://stackoverflow.com/questions/61212/how-do-i-remove-local-untracked-files-from-my-current-git-branch)..
   n – dry run
   x – directories

Preview Changes of a Merge

git log ..nameOfBranch

Edit a Commit Message

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

http://stackoverflow.com/questions/179123/edit-an-incorrect-commit-message-in-git

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
https://gist.github.com/tqheel/3144984

| | # 
# 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:

image
Already compiled, and has NuGet packages

image
Do a git init from the command line.

image
Make a  .gitignore.   (otherwise windows wont let you name it), a good community example is from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
 

image
Add all files to git

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

image
Push to GitHub

image
Then do a clone in VS as a sanity check

image

image
NuGet getting packages as it should.  Cloned solution works.

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

Create Team Project in VS.com

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 )

http://stackoverflow.com/questions/15128541/how-can-i-push-my-existing-git-repository-to-team-foundation-service

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: http://stackoverflow.com/questions/10312521/how-to-fetch-all-git-branches

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

http://pluralsight.com/training/Courses/TableOfContents/team-foundation-server-2013-new-features

Git Design Goals:

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

Git with TFS

image
Signed up to tfsonline in www.visualstudio.com..

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

image

But then dll's in projects folder.  So switched to this .gitignore file: https://github.com/github/gitignore/blob/master/VisualStudio.gitignore

image
http://stackoverflow.com/questions/18618760/tfs-git-extensions-seems-to-ignore-gitignore  - yes, this is a bug

http://stackoverflow.com/questions/20010319/visual-studio-online-git-how-to-make-sure-packages-are-ignored

image
Right click and just exclude the Packages folder.

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

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

Work Items

image
Click New Work Item in blue on RHS.

Did some changes on HomeController.cs

image
Can do a simple compare between 2 versions.

Add a Work Item to a Checkin

image
image
Drag the work item over to RHS.

image
Can see the work item related to the commit.

Commit and Sync - means do a pull/push

Branching and Merging

TFS Projects

image
Project level dashboard

 

image

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

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

image
Adding a new Git repository to this team project.  However this will break work item tracking: http://stackoverflow.com/questions/17591461/can-you-add-multiple-git-repositories-to-a-team-project-in-tfs-tfs-service **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”

reverting:

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

 

http://stackoverflow.com/questions/19982053/how-do-i-add-an-existing-solution-to-github-from-visual-studio-2013

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

Used this:  https://github.com/djhmateer/Winter.git

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

http://visualstudiogallery.msdn.microsoft.com/abafc7d6-dcaa-40f4-8a5e-d6724bdb980c

image

Then went to add solution to source control

image

http://ilblogdipego.blogspot.co.uk/2013/03/how-to-use-git-with-visual-studio-2012.html

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)

gitgui

image

R# – Move to another file with same name

Forumla

http://locationcube.blogspot.co.uk/2010/12/project-eulerproblem-15.html

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!!

image

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)

40!/((20!)(40-20)!)

N = number of elements (40)

r = how many we want to choose

137,846,528,820

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”

[TestFixture]
public class DynamicProgrammingTests
{
    private DynamicProgramming dynamicProgramming;

    [SetUp]
    public void DoFirst()
    {
        this.dynamicProgramming = new DynamicProgramming();
    }

    [Test]
    public void Four_DynamicProgrammingSolver_GivesAnswerOf70()
    {
        var result = dynamicProgramming.Solve(4);
        Assert.AreEqual(70, result);
    }

    [Test]
    public void Five_DynamicProgrammingSolver_GivesAnswerOf252()
    {
        var result = dynamicProgramming.Solve(5);
        Assert.AreEqual(252, result);
    }

    [Test]
    public void Twenty_DynamicProgrammingSolver_GivesAnswerOf252()
    {
        var result = dynamicProgramming.Solve(20);
        //137,846,528,820
        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

[TestFixture]
public class SolverTests
{
    private BruteForceRecursionSolver bruteForceRecursionSolver;
    [SetUp]
    public void DoThisAtStart()
    {
        this.bruteForceRecursionSolver = new BruteForceRecursionSolver();
    }
    [Test]
    public void TwoGivesAnswerOf6()
    {
        bruteForceRecursionSolver.gridSize = 2;
        var result = bruteForceRecursionSolver.Progress(0, 0);
        Assert.AreEqual(6, result);
    }

    [Test]
    public void ThreeGivesAnswerOf20()
    {
        bruteForceRecursionSolver.gridSize = 3;
        var result = bruteForceRecursionSolver.Progress(0, 0);
        Assert.AreEqual(20, result);
    }

    [Test]
    public void FourGivesAnswerOf70()
    {
        bruteForceRecursionSolver.gridSize = 4;
        var result = bruteForceRecursionSolver.Progress(0, 0);
        Assert.AreEqual(70, result);
    }

    [Test]
    public void FiveGivesAnswerOf252()
    {
        bruteForceRecursionSolver.gridSize = 5;
        var result = bruteForceRecursionSolver.Progress(0, 0);
        Assert.AreEqual(252, result);
    }

    [Test]
    public void TenGivesAnswerOf184756()
    {
        bruteForceRecursionSolver.gridSize = 10;
        var result = bruteForceRecursionSolver.Progress(0, 0);
        Assert.AreEqual(184756, result);
    }

    [Test]
    public void ElevenGivesAnswerOf705432()
    {
        bruteForceRecursionSolver.gridSize = 11;
        var result = bruteForceRecursionSolver.Progress(0, 0);
        Assert.AreEqual(705432, result);
    }
}

//http://stackoverflow.com/questions/2200236/project-euler-15
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)
                Combination++;
        }
    }
static void Main(string[] args)
        {
            //gives correct answer: 137,846,528,820
            Console.WriteLine("starting");
            Stopwatch stopWatch = new Stopwatch();
            stopWatch.Start();
            var solveRecursion2 = new SolveRecursion { GridSize = 20 };
            solveRecursion2.CalculateCombination();
            var result = solveRecursion2.Combination;
            stopWatch.Stop();
            TimeSpan ts = stopWatch.Elapsed;
            Console.WriteLine("Result is: {0}, time was {1} seconds", result, ts.ToString());
        }

and non recursive thoughts on:

http://stackoverflow.com/questions/10890516/rewrite-recursive-algorithm-more-simply-euler-15

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

image

hmmmm

I did all this (using an existing repo)

image

follow instructions here!

http://help.github.com/win-set-up-git/

| | # 
# 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

OpenID

TDD/BDD do this.

  • NUnit
  • TestDriven.net

Code Snippets

To help with mundane writing code in unit tests.

Ctrl K Ctrl B

http://weblogs.asp.net/kdente/archive/2005/05/05/405843.aspx  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.

image

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

image

Feature branch in Git

Master is for finalised and deployed (?) code

git branch (to see current branches)

git checkout –b membership

.gitignore

*resharper.user

[Dd]ebug/

[Rr]elease/

build/

[Bb]in/

[Oo]bj/

*.suo

*.sln.cache

_ReSharper.*/

*.user

git add .

Global GitIgnore

http://jqr.github.com/2009/02/03/global-git-ignore.html

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

Test 1 – Not Accept Email with < 6 Chars

From http://weblogs.asp.net/nunitaddin/

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) {
            Console.WriteLine("-------------------------------");
            Console.WriteLine(description);
            Console.WriteLine("-------------------------------");
        }

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

        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:

image

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

 

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

        [Test]
        public void registration_should_not_accept_email_with_lt_6_chars() {
            var membership = new Membership();
            var result = membership.Register("test@test.com", "password", "password");
            Assert.False(result.Success);
        }
    }

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
[Test]
      public void registration_should_not_accept_email_with_lt_6_chars() {
          var result = _membership.Register("e", "password", "password");
          Assert.False(result.Success);
      }

      [Test]
      public void registration_should_not_accept_password_with_lt_6_chars() {
          var result = _membership.Register("test@test.com", "x", "x");
          Assert.False(result.Success);
      }

      [Test]
      public void registration_should_not_accept_mismatched_passwords() {
          var result = _membership.Register("test@test.com", "password1", "password2");
          Assert.False(result.Success);
      }

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

http://blog.wekeroad.com/helpy-stuff/and-i-shall-call-it-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**

image

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.

https://github.com/robconery/massive

 

Test 2 – Registration Should Not Accept Duplicate Emails

Test is something like:

[Test]
        public void registration_should_not_accept_duplicate_emails() {
            var result = _membership.Register("test@test.com", "password", "password");
            var result2 = _membership.Register("test@test.com", "password", "password");
            Assert.False(result2.Success);
        }

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>
</configuration>

installed classic 2000 Northwind sample:

http://www.microsoft.com/download/en/confirmation.aspx?id=23654   then look in C:\SQL Server 2000 Sample Databases

http://ndc2011.macsimum.no/mp4/Day2%20Thursday/Track1%201140-1240.mp4 – 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();
            dataAdapter.Fill(ds);
            Console.WriteLine(ds.GetXml());

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";

https://github.com/robconery/massive/pull/65 here is a fix by pulling from the App.config.

Getting strange errors!

Reverting to SQL Server

<configuration>
  <connectionStrings>
    <!--<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;" />
  </connectionStrings>
</configuration>

and change provider name back to:

var _providerName = "System.Data.SqlClient";
and to put a unique constrant on SQL Server column: http://stackoverflow.com/questions/64981/sql-server-2005-how-create-a-unique-constraint

Code Snippets

image

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

MVC3

Unfuddle for project mgt

image

or agilezen (kanban)

Source is on http://github.com/tekpub/mvc3

Setup a new MVC3 solution called VidPub.Web

image

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”

DropBox

mkdir e:\dropbox\repositories\vpub

image

in e:\dropbox\repositories\vpub

git init –bare

from \dev folder  git push origin master

image

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.

Authentication

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

Public\javscripts

Public\stylesheets

no more content directory

Model\AccountModels.cs to AccountModel

change CSS path in _Layout.cshtml

CDN

http://code.google.com/apis/libraries/devguide.html#jquery

image

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 http://www.microsoft.com/windowsazure/msdn-benefits/ MSDN have got some benefits.

Logging

NLog using NuGet

Code Snippet
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" >

  <targets>
    <!--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}" />

  </targets>

  <rules>

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

  </rules>

</nlog>

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) {
            _logger.Info(message);
        }

        public void LogWarning(string message) {
            _logger.Warn(message);
        }

        public void LogDebug(string message) {
            _logger.Debug(message);
        }

        public void LogError(string message) {
            _logger.Error(message);
        }
        public void LogError(Exception x) {
            LogError(BuildExceptionMessage(x));
        }
        public void LogFatal(string message) {
            _logger.Fatal(message);
        }
        public void LogFatal(Exception x) {
            LogFatal(BuildExceptionMessage(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;
        }
    }

IoC

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

Ninject.MVC3

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”

 

kernel.Bind<ILogger>().To<NLogger>();

added in Logs/Site.log into our project.

Glimpse

Added in bookmarks into bar to turn on and off.

image

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.

image

| | #