You Want To Trace.Write... How About No!

You know the story... guy writes code... guy wants to debug code... guy wants to trace messages to understand what's happenin'... guy uses Trace.Write().  Now the part that smacked me in the tush with a wet towel this late night was the different between ASP.NET Trace.Write() and System.Diagnostics.Trace.Write().  In a default setup of an ASP.NET web app System.Diagnostics.Trace.Write() doesn't output to the Page Trace or the Trace.axd.  It goes to the "standard output" whatever that might be (assumed to be a console window).  This becomes problematic when you want to trace from a business object, data layer, server control, etc as these items have no HTTP Context which implements Trace as a System.Web.TraceContext property.

Alas my faithful reader you can add a trace listener to your web.config or programmatically to have all Trace.Write() methods output to the ASP.NET trace.  There are a variety of trace listeners one can add including the WebPageTraceListener which is what satisfies our case here.  Here's how you CaN GeTZ TrACe (my best LOLCats impression).

Trace Listener via config
<system.diagnostics>
  <trace>
    <listeners>
       <add name="WebPageTraceListener"
            type="System.Web.WebPageTraceListener, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
    </listeners>
  </trace>
</system.diagnostics>

Trace Listener programmatically from the Global.asax
void Application_Start(Object sender, EventArgs e)
{
    WebPageTraceListener gbTraceListener = new WebPageTraceListener();
    System.Diagnostics.Trace.Listeners.Add(gbTraceListener);
}

Keep reading!

For your System.Diagnostics.Trace statements to write to the trace your project MUST be compiled with the TRACE compiler switch.  In your project properties the Build tab has this defined as "Define TRACE constant". 

Now for the reverse... you want to route all ASP.NET trace to the standard system tracing output.  Modify your config to include an appropriate trace listener such as TextWriterTraceListener (note: WebPageTraceListener probably isn't appropriate for this one:) and update your web.config to have the trace element's writeToDiagnostics set to "true".

<system.web>
    <trace writeToDiagnosticsTrace="true"/>
</system.web>

kick it on DotNetKicks.com
Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

How To: Dependency Injection with Spring.NET

Download the sample Dependency Injection project.

Until recently I hadn’t explored an implementation of Dependency Injection (DI), or Inversion of Control (IoC), but knew I had uses for it.  If you’re interested in the types of Dependency Injection or are looking for a good explanation check out Martin Fowler’s Inversion of Control Containers and the Dependency Injection pattern article.  My interest was in having the ability to write code which implements an interface, having the client work against the interface, and loading the implementation at run time.  The benefit?  I can change my implementation at will without having to recompile and retest the whole app.  If this is sounding familiar you may be comparing it to the Provider pattern commonly used in the .NET framework.

Finally I had a project I felt was a great candidate for the Dependency Injection pattern and did some work with Spring.NET.  Here’s a straightforward example for getting started.

Create a new project called Spring.Net.Test and add an interface called IClass (we’re going real generic here).

IClass.cs
namespace Spring.Net.Test
{
   
public interface IClass
    {
       
string Name { get; }
    }
}

Next  create two classes called ClassA.cs and ClassB.cs and have both implement IClass.

ClassA.cs
namespace
Spring.Net.Test

{

    public class ClassA : IClass

    {

        public string Name

        {

            get { return "Class A"; }

        }

    }

}

 

ClassB.cs
namespace
Spring.Net.Test
{
   
public class ClassB : IClass
    {
       
public string Name
        {
           
get { return "Class B"; }
        }
    }
}

Now I’d want to use Dependency Injection to obtain a class which implements IClass.  We have two of them but the client app shouldn’t care which one is returned… just that it implements IClass.  To make this easily usable let’s create a factory to return an instance of IClass.  I called it IClassFactory.

IClassFactory.cs
using
System.IO;

using Spring.Objects.Factory.Xml;

 

namespace Spring.Net.Test

{

    public class IClassFactory

    {

        public static IClass CreateIClass()

        {

            using (Stream stream = File.OpenRead(@"C:\path to your config file\config.xml"))

            {

                Spring.Core.IO.InputStreamResource resource = new Spring.Core.IO.InputStreamResource(stream, "config");

                XmlObjectFactory xmlObjectFactory = new XmlObjectFactory(resource);

                IClass IClassObj = (IClass) xmlObjectFactory.GetObject("IClassObject");

                return IClassObj;

            }

        }

    }

}

Notice the first thing we’re doing is opening up an XML file which is the configuration file to tell Spring.NET what assembly and class to create an instance of.  Spring.NET then takes the stream in, locates the configuration for “IClassObject” and does some lifting to give us our object.  The configuration is simple. 

Config.xml
<?
xml version="1.0" encoding="utf-8" ?>
<
objects xmlns="http://www.springframework.net">
    <
object name="IClassObject" singleton="false" type="Spring.Net.Test.ClassB,Spring.Net.Test" />
</
objects>

Lastly we’ll write a test with NUnit to verify the functionality. 

Tests.cs
using NUnit.Framework;

 

namespace Spring.Net.Test

{

    [TestFixture]

    public class Tests

    {

        [Test]

        public void FactoryTest()

        {

            IClass myClass = IClassFactory.CreateIClass();

            Assert.AreEqual(myClass.Name, "Class B");

        }

    }

}

That’s pretty much it!  There are other packages than Spring.NET but I’ve yet to check them out.  Have you found another to be better?  How about performance of using DI? 

Download the sample Dependency Injection project.

kick it on DotNetKicks.com
Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Boy Was I Late for THIS One!

I think I'll hit "Snooze". 

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Cheat your Way Through Writing with AutoCorrect

I’m constantly writing email and documents using abbreviated names for products and features we have here at IGN Entertainment.  Words like “registration” are universally recognized from the abbreviated use of “reg” as is “Fileplanet” from “fp”.  By themselves neither of these short forms are valid words therefore annoying me with the little red squiggly line beneath (I use Office 2007).  It’s easy to right-click these and “Add to Dictionary” or “Ignore” to get rid of the error indication.  In thinking about it though, the proper answer is to type out the full word.

Right or wrong, I don’t want to type out the whole word.  It takes time... time that somehow I've talked myself in to not having :).

Then it struck me today – AutoCorrect does this all the time for words I misspell; I can probably add my own AutoCorrect terms!  Yep, I could.  Here’s the quick and dirty on how that’s done:

Start by typing out a word you love to incorrectly abbreviate… I’ll choose “fp”.

Fileplanet text

Now right-click the abbreviate, go to the AutoCorrect menu, and choose AutoCorrect Options.

AutoCorrect Properties Dialogue 

As you can see I’ve entered “fp” as the text to Replace, and “Fileplanet” as the text to replace it With.  Click “Add” and you’re all set!

Now test it out by typing the abbreviated word and watch it magically transform into your intended real-life word.

I wonder what else I haven’t considered which is so simple and productive?
Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

About Me

I'm Ian Suttle and I work for IGN Entertainment, a division of Fox Interactive Media.

Recent posts