Search

Categories

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Send mail to the author(s) E-mail

# Wednesday, October 26, 2011
( Git )

image

hmmmm

I did all this (using an existing repo)

image

follow instructions here!

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

Comments [0] | | # 
# Wednesday, September 21, 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() {                      }
Comments [0] | | # 
# Tuesday, September 20, 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

Comments [0] | | #