Showing posts with label example. Show all posts
Showing posts with label example. Show all posts

Friday, October 28, 2011

Capturing Console output without interfering with it

Recently I've had to tackle the following problem: given an existing .NET console application, send the commandline output to an email address when the application is finished. Sounded reasonably simple, right? And in the end it was.

Options...

The key to making this work is finding out that the .NET implementation of System.Console has access to the normal stdin, stdout and stderr console streams wrapped in a TextWriter.

If you then find out that Console has methods like SetOut()for changing the TextWriters that are used for this, you have way of capturing text that the existing console application writes out using Console.Writeline() and related methods so you can email it.

...that leave existing output as it

But wait, functionality for the application should remain the same, so this output should stilll remain visible on the console too. Here design patterns come to our aid, in this case the Decorator pattern. The class we need is the following:

using System;
using System.IO;
using System.Text;

namespace peSHIr
{
  public class StringBufferPassthroughWriter : TextWriter
  {
     private TextWriter wrapped;
     private StringBuilder buffer;

     public StringBufferPassthroughWriter(TextWriter wrap)
     {
        wrapped = wrap;
        buffer = new StringBuilder();
     }

     public override Encoding Encoding { get { return wrapped.Encoding; } }
     public override void Write(string value) { wrapped.Write(value); buffer.Append(value); }
     public override void WriteLine(string value) { wrapped.WriteLine(value); buffer.AppendLine(value); }
     public override void WriteLine() { wrapped.WriteLine(); buffer.AppendLine(); }

     public string Buffer { get { return buffer.ToString(); } }
  }
}

What does the above class do? Well, not very much. All it does is decorate another TextWriter. That is: it derives from TextWriter, taking another TextWriter in its constructor which it stores, and then it simply passes through all method calls that write elementary pieces of text to the stored TextWriter. This makes sure it does not interfere with whatever that other TextWriter would normally be doing.

And it does one extra thing: keep an instance of a StringBuilder as well, and also fill this from the same overridden methods. Finally, our new TextWriter decorator supplies a read-only property to get at the stored string in the StringBuilder buffer.

How to use this

It should now probably be fairly obvious now how to actually "insert" this decorator in our existing console application to enable it to send an email with its complete output without interfering with that same output. I'll show a simple "before" and "after" comparison of the Main() method for the application.

Before

using System;

static int Main(string[] args)
{
  // Application code, calling Console.WriteLine() etc.
  return 0;
}

After

using System;
using peSHIr;

// Actual EmailSuperUser() method omitted as
// exercise for the reader... ;-)

static int Main(string[] args)
{
  using (var output = new StringBufferPassthroughWriter(Console.Out))
  {
    Console.SetOut(output);
    // Application code, calling Console.WriteLine() etc.
    EmailSuperUser(output.Buffer);
  }
  return 0;
}

And that is basically all. Hope you enjoyed this little code sample.

(For more information on how to write the EmailSuperUser method, see this Scott Guthrie blogpost and/or the System.Net.Mail documentation.)

Thursday, June 30, 2011

Easily exclude generated proxies from your code coverage

This is just a quick heads-up that many of you might already know about: partial classes easily enable you to add an attribute to an existing class by just adding an empty partial class definition for the same class in another source code location that just has that attribute on it.

Adding an attribute like this can be used to exclude the generated code of a webservice proxy from unit test code coverage by adding a DebuggerNonUserCode attribute to the relevant classes, like so:

// Add DebuggerNonUserCode attribute to generated
// proxy classes to exclude it from code coverage.

namespace Your.ServiceProxy.Namespace
{
 using System.Diagnostics;
 [DebuggerNonUserCode] public partial class YourWebService { }
 [DebuggerNonUserCode] public partial class SomeServiceDto { }
 [DebuggerNonUserCode] public partial class AnotherServiceDto { }
 // et cetera
}

As long as the service keeps using the same classnames, this solution even enables you to regenerate your proxy without losing the code coverage exclusion of the proxy (if you put this code in place not touched on regeneration).

Nifty, huh? ;-)

Wednesday, March 2, 2011

Example code for SplitUp(), on infinite sequence! ;-)

I've received some positive reactions to my previous post, in which I gave source code of a lazy implementation of a SplitUp() function that could be used for paging an IEnumerable<T>.

However, I also got comments that example code on how you could use this would be nice. I had been thinking about that - also to show off exactly how the SplitUp() code is lazy and what actually happens if you use it - but decided to leave it out. That was mainly because I myself already knew; it just wasn't a goal of that previous blog post for me. Personally I'm not that much of a "need to see it work in an example" kind of guy, you know? Plus, blog posts take a bit of time. ;-)

Having said that, I can now give you this example, which should be self-explanatory if you run the following code in a console app project that includes the source from the previous blog code as well. Hope you enjoy it; as always all comments are welcome!

namespace SplitUpExample
{
  using System;
  using System.Linq;
  using System.Collections.Generic;
  using peSHIr.Utilities;

  class Program
  {
    static bool TraceDataCreation;
        
    static Action<string> println = text => Console.WriteLine(text);
    static Action<string> print = text => Console.Write(text);
    static Action newline = () => Console.WriteLine();

    static void Main(string[] args)
    {
      newline();
      println("* How can SplitUp() be used for paging");
      TraceDataCreation = false;
            
      var allData = TestData(64);
      var pagedData = allData.SplitUp(7);
      foreach (var page in pagedData)
      {
        print("Page:");
        foreach (int i in page)
        {
           print(" ");
           print(i.ToString());
        }
        newline();
      }

      newline();
      println("* And is it really lazy?");
      TraceDataCreation = true;
            
      println("Calling SplitUp() on infinite sequence now");
      var pagedInfinity = TestData().SplitUp(4);

      println("Retrieving first page now");
      var page1 = pagedInfinity.ElementAt(0);
            
      println("Retrieving third page now");
      var page3 = pagedInfinity.ElementAt(2);
            
      Action<string,int,int> results = (text,sum,count)
        => Console.WriteLine("{0}: {1}, {2}", text, sum, count);

      println("Showing results:");
      results("First page", page1.Sum(), page1.Count());
      results("Third page", page3.Sum(), page3.Count());
      println("So yes, SplitUp() is lazy like LINQ! ;-)");

#if DEBUG
      newline();
      println("(Key to quit)");
      Console.ReadKey();
#endif
    }

    static IEnumerable<int> TestData(int n)
    {
      return TestData().Take(n);
    }

    static IEnumerable<int> TestData()
    {
      // WARNING: this returns an infinite sequence!
      // Or at least: until int overflows... ;-)
      int i = 0;
      while (true)
      {
        if (TraceDataCreation)
          Console.WriteLine("Yielding {0}", i);
        yield return i++;
      }
    }

  }

}