Search

Categories

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Send mail to the author(s) E-mail

# Wednesday, 07 August 2013
( NLog | this.Log )

Log to the output window in VS

<!--<target name="debugger" xsi:type="Debugger" layout="${logger}::${message}"/>—>

<!-- See output window in VS-->
<!--<logger name="*" minlevel="Debug" maxlevel="Warn" writeTo="debugger" />—>

DB

http://stackoverflow.com/questions/1008093/how-to-get-nlog-to-write-to-database

<target type="Database" name="database" connectionStringName="DBConnect">
  <commandText>
    insert into Log ([CreateDate], [Origin], [LogLevel], [Message], [Exception], [StackTrace]) values (@createDate, @origin, @logLevel, @message, @exception, @stackTrace);
  </commandText>
  <parameter name="@createDate" layout="${date}"/>
  <parameter name="@origin" layout="${logger}"/>
  <parameter name="@logLevel" layout="${level}"/>
  <parameter name="@message" layout="${message}"/>
  <parameter name="@exception" layout="${exception:format=Message,StackTrace}"/>
  <parameter name="@stackTrace" layout="${stacktrace}"/>
  <parameter name="@stackTrace" layout=""/>
</target>

then


<logger name="*" appendTo="database"/>

NLog Errors

Very useful for debugging why something is not logging.

<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" throwExceptions="true" internalLogFile="c:\temp\nlog.txt" internalLogLevel="Debug">

| | # 
# Wednesday, 10 July 2013
( NLog | this.Log )

http://devlicio.us/blogs/rob_reynolds/archive/2012/12/15/introducing-this-log.aspx

  • It does no logging if you don’t have a logging engine set up.
  • It works everywhere in your code base (where you can write C#). This means in your razor views as well!
  • It uses deferred execution, which means you don’t have to mock it to use it with testing (your tests won’t fail on logging lines).
  • You can mock it easily and use that as a means of testing.
  • You have no references to your actual logging engine anywhere in your codebase, so swapping it out (or upgrading) becomes a localized event to one class where you provide the adapter.

I’ve been using NLog as the engine.

 

Use NuGet to pull down this.log and NLog

public class SomeClass { 
  
  public void SomeMethod() { 
    this.Log().Info(() => "Here is a log message with params which can be in Razor Views as well: '{0}'".FormatWith(typeof(SomeClass).Name)); 
 
    this.Log().Debug("I don't have to be delayed execution or have parameters either"); 
  } 
 
  public static void StaticMethod() { 
    "SomeClass".Log().Error("This is crazy, right?!"); 
  } 
  
}

and to setup:

LoggingExtensions.Logging.Log.InitializeWith<LoggingExtensions.NLog.NLogLog>();

and in App.Config

<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <targets>
      <target name="file" type="AsyncWrapper" queueLimit="5000" overflowAction="Discard">
        <!--<target type="File" fileName="${basedir}/logs/UER.Web.log" layout="${longdate} | ${pad:padding=-4:inner=${threadid}}| ${pad:padding=-10:inner=[${level:uppercase=true}]}| ${pad:padding=-50:inner=${logger}}| ${message}" archiveFileName="${basedir}/logs/UER.Web-archive-{#}.log" archiveEvery="Day" archiveNumbering="Rolling" maxArchiveFiles="14" concurrentWrites="true" keepFileOpen="false" encoding="iso-8859-2" />-->
        <target type="File" fileName="e:/temp/UER.Web.log" layout="${longdate} | ${pad:padding=-4:inner=${threadid}}| ${pad:padding=-10:inner=[${level:uppercase=true}]}| ${pad:padding=-50:inner=${logger}}| ${message}" archiveFileName="${basedir}/logs/UER.Web-archive-{#}.log" archiveEvery="Day" archiveNumbering="Rolling" maxArchiveFiles="14" concurrentWrites="true" keepFileOpen="false" encoding="iso-8859-2" />
      </target>
      <target name="file-exceptions" type="AsyncWrapper" queueLimit="5000" overflowAction="Discard">
        <target type="File" fileName="${basedir}/logs/UER.Web-exceptions.log" layout="${longdate} | ${machinename} | ${processinfo:property=ProcessName} | ${threadid}|[${level:uppercase=true}] | (${logger})${newline}[START]${newline}${message}${newline}[END]" archiveFileName="${basedir}/logs/UER.Web-exceptions-archive-{#}.log" archiveEvery="Day" archiveNumbering="Rolling" maxArchiveFiles="14" concurrentWrites="true" keepFileOpen="false" encoding="iso-8859-2" />
      </target>

      <!--<target name="console" type="ColoredConsole" layout="${longdate} [${level:uppercase=true}] ${message}">
        <highlight-row backgroundColor="NoChange" condition="level = LogLevel.Error" foregroundColor="Red" />
        <highlight-row backgroundColor="NoChange" condition="level = LogLevel.Warn" foregroundColor="Yellow" />
      </target>-->
      
      
      <!--<target name="errorSmtp" type="Mail" layout="${longdate} ${threadid} [${level:uppercase=true}] ${logger} - ${message}" subject="this.Log Sample Console Errors - LOCAL DEBUG" to="noone@noreply.org" from="this.Log.sample@noreply.org" smtpServer="localhost" />-->
    </targets>
    <rules>
      <logger name="*" minlevel="Debug" maxlevel="Warn" writeTo="file" />
      <!--<logger name="*" minlevel="Debug" maxlevel="Warn" writeTo="console" />-->
      <logger name="*" minlevel="Error" maxlevel="Fatal" writeTo="file-exceptions" />
      <!--<logger name="*" minlevel="Error" writeTo="errorSmtp" />-->
    </rules>
  </nlog>

When using Resharper’s test runner, I used e:/temp to dump log files to, with permissions set to everyone writeable.

| | # 
# Wednesday, 13 March 2013
# 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

| | #