<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Gurock Software Blog &#187; si-article</title>
	<atom:link href="http://blog.gurock.com/postings/tag/si-article/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.gurock.com</link>
	<description>Our products, programming &#38; business.</description>
	<lastBuildDate>Thu, 22 Jul 2010 14:01:41 +0000</lastBuildDate>
	
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>WCF logging and tracing with SmartInspect</title>
		<link>http://blog.gurock.com/postings/wcf-logging-and-tracing-with-smartinspect/1442/</link>
		<comments>http://blog.gurock.com/postings/wcf-logging-and-tracing-with-smartinspect/1442/#comments</comments>
		<pubDate>Fri, 04 Jun 2010 13:21:26 +0000</pubDate>
		<dc:creator>Dennis Gurock</dc:creator>
				<category><![CDATA[Gurock Software]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[SmartInspect]]></category>
		<category><![CDATA[si-article]]></category>

		<guid isPermaLink="false">http://blog.gurock.com/?p=1442</guid>
		<description><![CDATA[Distributed software applications are usually difficult to debug. Bugs and performance issues can occur on the client, on the server or in the communication stack. Finding the root cause of such problems is often not trivial, especially if the issue only occurs on a production system. Luckily, .NET logging tools like SmartInspect help with this [...]]]></description>
			<content:encoded><![CDATA[<p>Distributed software applications are usually difficult to debug. Bugs and performance issues can occur on the client, on the server or in the communication stack. Finding the root cause of such problems is often not trivial, especially if the issue only occurs on a production system. Luckily, <a href="http://www.gurock.com/smartinspect/">.NET logging</a> tools like SmartInspect help with this and allow you to trace method execution end-to-end and log critical application data to analyze the inner-workings of your programs.</p>
<p>The Windows Communication Foundation (WCF) is Microsoft&#8217;s approach to service-oriented architectures and allows you to easily built client/server and distributed applications with .NET. SmartInspect can be used to debug applications that make use of WCF and this article (and the attached demo project) explains how to do this. The demo application is based on <a href="http://msdn.microsoft.com/en-us/library/ms734712.aspx">Microsoft&#8217;s WCF tutorial</a>, so if you haven&#8217;t worked with WCF before, the tutorial is a good way to start.</p>
<h2>The service application</h2>
<p>The service application that is part of the demo project exposes a simple service that offers various calculation methods (add, subtract, multiply, and divide). We use SmartInspect to log the method execution, parameters and results:</p>
<pre class="brush: csharp;">
class CalculatorService : ICalculator
{
	public double Add(double n1, double n2)
	{
		SiAuto.Main.EnterMethod(this, &quot;Add({0},{1})&quot;,
			new object[] {n1, n2});
		double result = n1 + n2;
		SiAuto.Main.LogValue(&quot;Result&quot;, result);
		SiAuto.Main.LeaveMethod(this, &quot;Add&quot;);
		return result;
	}

	// [..]
}
</pre>
<h2>The client application</h2>
<p>The client application connects to the service and uses the exposed methods to calculate various results. The client application is also instrumented with SmartInspect log calls and logs the calculation results returned from service:</p>
<pre class="brush: csharp;">
static void Calculate(CalculatorClient client)
{
	SiAuto.Main.EnterMethod(&quot;Program.Calculate&quot;);

	// Call the Add service operation
	double value1 = 100.00D;
	double value2 = 15.99D;
	double result = client.Add(value1, value2);
	SiAuto.Main.LogMessage(&quot;Add({0},{1}) = {2}&quot;, value1, value2, result);

	// [..]

	SiAuto.Main.LeaveMethod(&quot;Program.Calculate&quot;);
}
</pre>
<h2>Debugging with the SmartInspect Console</h2>
<p>When you launch both demo applications, the SmartInspect Console automatically receives the log messages via named-pipes (make sure to start Visual Studio as administrator, as this is required by WCF to register the service). You can also redirect the logging data to log files or other protocols by setting the connection string accordingly.</p>
<p>The SmartInspect Console makes it easy to see the log messages and data in context or to separate the log messages of the client and service. The Console also helps with tracking the involved threads and processes (e.g. you can see in the screenshot that .NET starts and recycles two threads to serve the four service calls).</p>
<div class="framed-image">
<a href="http://blog.gurock.com/wp-content/uploads/2010/05/console.png"><img src="http://blog.gurock.com/wp-content/uploads/2010/05/console-small.png" alt="" title="" width="550" height="397" class="alignnone size-full wp-image-1450" /></a><br />
<span>Log messages of the client and service in the <a href="http://www.gurock.com/smartinspect/tour/">SmartInspect Console</a></span>
</div>
<h2>Tracing WCF</h2>
<p>WCF also has some tracing and logging capabilities of its own. This allows you to trace the messages and packets WCF sends and receives. Inspecting the exchanged messages is especially useful if you need to debug interoperability issues with other platforms and frameworks. WCF uses .NET&#8217;s built-in tracing API to log messages and packets. </p>
<p>Fortunately, SmartInspect makes it easy to receive .NET debug messages as it comes with a custom trace listener. To redirect WCF diagnostic messages to SmartInspect, simply add the <code>Gurock.SmartInspect.DebugTrace</code> assembly as a reference to your project and add the following code to the App.config (the demo projects already come with all the required bits pre-configured; you just need to uncomment the config settings):</p>
<pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;configuration&gt;
  &lt;system.diagnostics&gt;
    &lt;sources&gt;
      &lt;source name=&quot;System.ServiceModel.MessageLogging&quot; &gt;
        &lt;listeners&gt;
          &lt;clear /&gt;
          &lt;add name=&quot;SmartInspect&quot;
              type=&quot;Gurock.SmartInspect.DebugTrace.SmartInspectTraceListener,        Gurock.SmartInspect.DebugTrace&quot; /&gt;
        &lt;/listeners&gt;
      &lt;/source&gt;
    &lt;/sources&gt;
  &lt;/system.diagnostics&gt;
  &lt;system.serviceModel&gt;
      &lt;diagnostics&gt;
        &lt;messageLogging
             logEntireMessage=&quot;true&quot;
             logMalformedMessages=&quot;true&quot;
             logMessagesAtServiceLevel=&quot;true&quot;
             logMessagesAtTransportLevel=&quot;true&quot;
             maxMessagesToLog=&quot;3000&quot;
             maxSizeOfMessageToLog=&quot;2000&quot;/&gt;
      &lt;/diagnostics&gt;
    &lt;/system.serviceModel&gt;
&lt;/configuration&gt;
</pre>
<p>The full demo application will be included in the next SmartInspect release, but you can also <a href="http://blog.gurock.com/wp-content/uploads/2010/05/smartinspect-wcf.zip">download a copy</a> of the demo project from this site in the meantime.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.gurock.com/postings/wcf-logging-and-tracing-with-smartinspect/1442/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Aspect-oriented logging for .NET with Unity and SmartInspect</title>
		<link>http://blog.gurock.com/postings/aspect-oriented-logging-for-net-with-unity-and-smartinspect/1386/</link>
		<comments>http://blog.gurock.com/postings/aspect-oriented-logging-for-net-with-unity-and-smartinspect/1386/#comments</comments>
		<pubDate>Mon, 31 May 2010 11:59:34 +0000</pubDate>
		<dc:creator>Dennis Gurock</dc:creator>
				<category><![CDATA[Gurock Software]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[SmartInspect]]></category>
		<category><![CDATA[si-article]]></category>

		<guid isPermaLink="false">http://blog.gurock.com/?p=1386</guid>
		<description><![CDATA[This article is part of a series about aspect-oriented logging with SmartInspect, our logging tool for .NET, Java and Delphi. Please see the first article of this series for a complete overview of the available posts.
Michael Baarz recently emailed us as he was a looking for a modern .NET logging tool for his company&#8217;s complex [...]]]></description>
			<content:encoded><![CDATA[<p><em>This article is part of a series about aspect-oriented logging with <a href="http://www.gurock.com/smartinspect/">SmartInspect</a>, our logging tool for .NET, Java and Delphi. Please see the <a href="http://blog.gurock.com/postings/aspect-oriented-logging-and-smartinspect/814/">first article of this series</a> for a complete overview of the available posts.</em></p>
<p>Michael Baarz recently emailed us as he was a looking for a modern .NET logging tool for his company&#8217;s complex telecommunication and PBX software. Michael was about to redesign his company&#8217;s flagship product and was planning to use Microsoft&#8217;s dependency injection framework <a href="http://unity.codeplex.com/">Unity</a>.</p>
<p>He told us that he really enjoyed working with SmartInspect and because Unity also supports some aspect oriented programming features, Michael decided to write an unofficial library to integrate SmartInspect with Unity so he could benefit from this useful combination. This posting introduces Michael&#8217;s library and will explain how to get started with the extension to integrate and benefit from SmartInspect and Unity.</p>
<h2>Unity, a dependency injection container</h2>
<p>Unity is Microsoft&#8217;s dependency injection container and framework and is part of their <a href="http://msdn.microsoft.com/en-us/practices/default.aspx">Patterns &#038; Practices</a> initiative. If you are new to dependency injection in general, I recommend taking a look at <a href="http://martinfowler.com/articles/injection.html">this article</a> by Martin Fowler that explains the basic concepts and benefits. Besides common dependency injection features, Unity also supports aspect oriented programming by allowing you to intercept and wrap method calls.</p>
<p>The big difference between dependency injection (DI) frameworks and classic AOP tools such as PostSharp is that DI frameworks are configured at run-time, whereas PostSharp injects and builds its aspects at compile time. Both approaches have their pros and cons, so it really depends on the circumstances which one you should use (DI frameworks are usually more flexible as you can change the behavior at run-time, whereas &#8216;classic&#8217; AOP tools support more features and are usually faster).</p>
<h2>Using the SmartInspect Unity Interception Extension</h2>
<p>Michael&#8217;s library to integrate SmartInspect and Unity is called the <a href="http://siunity.codeplex.com/">SmartInspect Unity Interception Extension</a> and can be downloaded from CodePlex. To get started with the library, either <a href="http://siunity.codeplex.com/SourceControl/list/changesets">check out the source code</a> via Subversion or download one of the <a href="http://siunity.codeplex.com/SourceControl/list/changesets">releases</a> (there wasn&#8217;t a release at the time of this writing yet).</p>
<p>To use the library in your solution, you first need to add a few assembly references to your projects. First of all, you need to reference the <code>Microsoft.Practices.Unity</code> and <code>Microsoft.Practices.Unity.Interception</code> assemblies; these are part of Unity and are automatically installed and registered when you <a href="http://unity.codeplex.com/releases">download and install Unity</a>. The next assembly reference you need to add is <code>Gurock.SmartInspect</code>, as this is required to use SmartInspect logging. Last but not least you need to add Michael&#8217;s <code>SmartInspect.Extensions.Unity</code> assembly as a reference to your project, either by adding a reference to the compiled DLL or by adding the project to your solution and using a project reference.</p>
<h2>Tracing method execution</h2>
<p>One of the more useful aspects (no pun intended) of AOP is the capability to easily trace method execution, so this is the first thing I&#8217;m going to demonstrate. Unity is a dependency injection framework so we will need to properly register and instantiate all classes we want to intercept for logging. The first thing we need to do is to define the interface for the class we want to instantiate through Unity. Because one of the design goals of DI is that we can easily replace the actual implementation for an interface, using interfaces is mandatory here. For our <code>Hello, World</code> example, I&#8217;ve defined an interface and implementation class:</p>
<pre class="brush: csharp;">
interface IHello
{
	int Count { get; set; }
	void SayHello(string name);
	string SayGoodbye(string name);
	void RaiseException(string name);
}
</pre>
<p>The actual implementation already makes use of SmartInspect to log various messages:</p>
<pre class="brush: csharp;">
class Hello : IHello
{
	public int Count { get; set; }

	public void SayHello(string name)
	{
		SiAuto.Main.LogMessage(&quot;Hello, {0}.&quot;, name);
	}

	public string SayGoodbye(string name)
	{
		string msg = String.Format(&quot;Goodbye, {0}.&quot;, name);
		SiAuto.Main.LogMessage(msg);
		return msg;
	}

	public void RaiseException(string name)
	{
		SiAuto.Main.LogMessage(&quot;Hello, {0}.&quot;, name);
		throw new Exception(&quot;This is a test exception&quot;);
	}
}
</pre>
<p>Now to intercept and trace the method calls, we first need to make sure that we register and instantiate the interface and implementation with Unity. To do this, we use an instance of <code>UnityContainer</code> and add and configure the <code>Interception</code> extension. Here&#8217;s the full Main method of our example program:</p>
<pre class="brush: csharp;">
static void Main(string[] args)
{
	// Enable SmartInspect logging
	SiAuto.Si.Enabled = true;

	// Create the Unity dependency injection container,
	// register the Interception extension and register our
	// our example class
	IUnityContainer container = new UnityContainer();
	container
		.AddNewExtension&lt;Interception&gt;()
		.RegisterType&lt;IHello, Hello&gt;();

	// Now tell Unity how to intercept IHello method calls
	container.Configure&lt;Interception&gt;()
		.SetInterceptorFor&lt;IHello&gt;(new TransparentProxyInterceptor());

	// Instead of creating our Hello class directly, we ask
	// Unity to resolve the dependency for the IHello interface
	IHello hello = container.Resolve&lt;IHello&gt;();

	// Call The IHello methods and assign property values
	hello.SayHello(&quot;World&quot;);
	hello.SayGoodbye(&quot;World&quot;);

	Random r = new Random();
	for (int i = 0; i &lt; 10; i++)
	{
		hello.Count = r.Next(100);
		Thread.Sleep(1000);
	}

	hello.RaiseException(&quot;Hello World&quot;);
}
</pre>
<p>Now to actually use the the SmartInspect Unity extension and trace method calls, we just need to add a single attribute to the interface, namely the <code>[SiMethodCall]</code> attribute (which can be found in the <code>SmartInspect.Extensions.Unity</code> namespace):</p>
<pre class="brush: csharp;">
[SiMethodCall]
interface IHello
{
	// [..]
}
</pre>
<p>The attributes come with various properties to influence the behavior of the log calls, such as changing the log level, adding name prefixes/suffixes and so on. For a complete list of properties just see the Intellisense help within Visual Studio. Once we launch the example application, we see the following output in the SmartInspect Console (also take a look at the viewer toolbox at the bottom right of the window, it shows the method arguments of the selected log entry):</p>
<div class="framed-image">
<a href="http://blog.gurock.com/wp-content/uploads/2010/05/methods.png"><img src="http://blog.gurock.com/wp-content/uploads/2010/05/methods-small.png" alt="" title="" width="550" height="425" class="alignnone size-full wp-image-1410" /></a><br />
<span>Log messages and method tracing in the <a href="http://www.gurock.com/smartinspect/tour/">SmartInspect Console</a></span>
</div>
<h2>Logging exceptions</h2>
<p>Logging occurred exceptions is another useful thing you can automate with AOP. The SmartInspect Unity extension comes with its own attribute to log exceptions, namely the <code>[SiException]</code> attribute. The attribute doesn&#8217;t handle the exceptions (it just logs them) so it doesn&#8217;t change the behavior of your code. To use the attribute, just specify it for an interface or method like this:</p>
<pre class="brush: csharp;">
[SiException(LogArgumentsToViewer = true)]
interface IHello
{
	// [..]
}
</pre>
<p>The resulting log messages in the SmartInspect Console look like this:</p>
<div class="framed-image">
<a href="http://blog.gurock.com/wp-content/uploads/2010/05/exceptions.png"><img src="http://blog.gurock.com/wp-content/uploads/2010/05/exceptions-small.png" alt="" title="" width="550" height="425" class="alignnone size-full wp-image-1410" /></a><br />
<span>Logged exception in the <a href="http://www.gurock.com/smartinspect/tour/">SmartInspect Console</a></span>
</div>
<h2>Watching property values</h2>
<p>SmartInspect allows you to easily log and watch field and property values. The SmartInspect Unity extension comes with an attribute to automatically log changes of properties as they occur. To benefit from this, simply add the <code>[SiWatch]</code> attribute to the <code>set</code> method of your properties:</p>
<pre class="brush: csharp;">
interface IHello
{
	int Count { get; [SiWatch]set; }
}
</pre>
<p>This blog posting is intended to give you an overview of the capabilities the SmartInspect Unity extension library provides, but it cannot explain all the useful options and features that the library comes with. So to get started with the library and learn about all its capabilities, I recommend <a href="http://siunity.codeplex.com/">downloading it</a> and start playing with it.</p>
<p>Please also note that the SmartInspect Unity extension introduced here is not a Gurock Software product and is not official supported by us. To send feedback and to contribute to the project, please take a look at the <a href="http://siunity.codeplex.com/">CodePlex project page</a>. Thanks Michael for writing the library and for contributing to the SmartInspect ecosystem!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.gurock.com/postings/aspect-oriented-logging-for-net-with-unity-and-smartinspect/1386/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Aspect-oriented logging for .NET with PostSharp and SmartInspect</title>
		<link>http://blog.gurock.com/postings/aspect-oriented-logging-for-net-with-postsharp-and-smartinspect/848/</link>
		<comments>http://blog.gurock.com/postings/aspect-oriented-logging-for-net-with-postsharp-and-smartinspect/848/#comments</comments>
		<pubDate>Mon, 02 Nov 2009 14:00:23 +0000</pubDate>
		<dc:creator>Tobias Gurock</dc:creator>
				<category><![CDATA[Gurock Software]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[SmartInspect]]></category>
		<category><![CDATA[si-article]]></category>

		<guid isPermaLink="false">http://blog.gurock.com/?p=848</guid>
		<description><![CDATA[This article is part of a series about aspect-oriented logging with SmartInspect, our logging tool for .NET, Java and Delphi. Please see the first article of this series for a complete overview over the available posts.
Our PostSharp aspect library has a new home: SmartInspect for PostSharp
There are various AOP frameworks available for each of the [...]]]></description>
			<content:encoded><![CDATA[<p><em>This article is part of a series about aspect-oriented logging with <a href="http://www.gurock.com/smartinspect/">SmartInspect</a>, our logging tool for .NET, Java and Delphi. Please see the <a href="http://blog.gurock.com/postings/aspect-oriented-logging-and-smartinspect/814/">first article of this series</a> for a complete overview over the available posts.</em></p>
<p><strong>Our PostSharp aspect library has a new home: <a href="http://code.gurock.com/p/smartinspect-postsharp/">SmartInspect for PostSharp</a></strong></p>
<p>There are various AOP frameworks available for each of the three platforms SmartInspect supports, so why did we decide to start with <a href="http://www.postsharp.org/">PostSharp</a> for the first part of this blog series about apsect-oriented logging? PostSharp has become the de-facto standard AOP framework for .NET and there are many things to like about PostSharp:</p>
<ul>
<li>PostSharp is really easy to use. It integrates nicely with MSBuild (and therefore Visual Studio) and you just need to complete the PostSharp setup and are good to go.</li>
<li>It provides different APIs depending on what you are trying to accomplish. You can use a low-level API for injecting snippets of MSIL code for complexer tasks (PostSharp.Core) or a very simple high-level API (PostSharp.Laos) to develop aspects with custom .NET attributes.</li>
<li>It&#8217;s very well documented. The APIs are fully documented and there are getting started tutorials, videos, a plugin repository and lots more. Can&#8217;t get a lot better than that.</li>
<li>It&#8217;s a compile-time AOP framework. Unlike other tools which inject the AOP code at runtime, it post-processes the assemblies directly after compliation which is more efficient and allows for more flexibility.</li>
<li>Last but not least, some SmartInspect customers were already successfully using PostSharp in their applications and told us that they liked the combination of both tools (that&#8217;s how we became aware of PostSharp in the first place).</li>
</ul>
<p>We will be using the simpler Laos API for our SmartInspect PostSharp aspects, as we found it sufficient for all our needs. The resulting library is able to automatically trace method execution, log exceptions and watch changes of field variables. The library comes with three aspects for the different tasks, each implemented as a custom .NET attribute.</p>
<h2>Using the SmartInspect aspects</h2>
<p>The general procedure of using a PostSharp aspect is to install the <a href="http://www.postsharp.org/download">PostSharp framework</a> and to add the <code>PostSharp.Public</code> and <code>PostSharp.Laos</code> assembly references to your application. PostSharp injects itself into the MSBuild build process and automatically processes all assemblies that reference PostSharp.</p>
<p>For our logging aspects, you further need to add references to the <code>Gurock.SmartInspect</code> and <code>Gurock.SmartInspect.PostSharp</code> assemblies (the logging library and PostSharp aspects, respectively). The logging library is included in the <a href="http://www.gurock.com/smartinspect/trial/">SmartInspect trial download</a> and the SmartInspect AOP plugin can be downloaded from the <a href="http://www.gurock.com/smartinspect/resources/">SmartInspect resources page</a>.</p>
<h2>Tracing method execution</h2>
<p>The first aspect I am going to demonstrate is for tracing method execution. This aspect makes it really easy to generate a complete call trace of your application, showing you the entire application flow and letting you inspect stack traces at each execution point. It automatically generates two log messages for each method call: one for entering a method and one when a method exits. You can also log the passed method arguments (when entering a method) and the method result (when exiting a method), respectively.</p>
<p>To use this aspect, simple add the <code>SiTrace</code> custom attribute to your application as follows (note how you can continue to use SmartInspect for complementary log messages, of course):</p>
<pre class="brush: csharp;">
using System;
using Gurock.SmartInspect;
using Gurock.SmartInspect.PostSharp;

[assembly:SiTrace(SessionName=&quot;Main&quot;)]

namespace Gurock.SmartInspect.PostSharp.Samples
{
	class Program
	{
		static void Main(string[] args)
		{
			SiAuto.Si.Enabled = true; // Enable logging
			Hello(&quot;World&quot;);
			Goodbye(&quot;World&quot;);
		}

		static void Hello(string name)
		{
			SiAuto.Main.LogMessage(&quot;Hello, {0}.&quot;, name);
		}

		static string Goodbye(string name)
		{
			string msg = String.Format(&quot;Goodbye, {0}.&quot;, name);
			SiAuto.Main.LogMessage(msg);
			return msg;
		}
	}
}
</pre>
<p>The attribute can be specified on a per-class/per-method basis or, like in our example, for the entire assembly. You can further specify filters for including/excluding certain modules/classes (called attribute targets in the PostSharp terminology), set aspect priorities (useful with nested aspects) <a href="http://www.postsharp.org/contributions/documentation">and much more</a>.</p>
<p>Our aspects have a few additional SmartInspect-related options. First, as you can see in the example above, you can set the session name used for sending log messages. If you do not want a hard-coded session name, you can tell the aspect to make use of the logging context and automatically adjust the name based on the current namespace or class. You can do so by setting a so called session policy. For example, to automatically use a session name that equals the name of the current class context, you can use a session policy of <code>SessionPolicy.TypeName</code> and omit the session name:</p>
<pre class="brush: csharp;">
...
[assembly:SiTrace(SessionPolicy=SessionPolicy.TypeName)]
...
</pre>
<p>There are additional options for including the method arguments (<code>IncludeArguments</code>) and method return value (<code>IncludeReturnValue</code>). With both options enabled, the resulting log looks as follows in the <a href="http://www.gurock.com/smartinspect/tour/1/">SmartInspect Console</a> (SmartInspect&#8217;s viewer application). Note how the automatic enter/exit messages are mixed with the manual log messages:</p>
<div class="framed-image">
<a href="/wp-content/uploads/2009/10/postsharp-sitrace.png"><img src="/wp-content/uploads/2009/10/postsharp-sitrace-small.png" alt="The SiTrace sample log shown in the SmartInspect Console" title="The SiTrace sample log shown in the SmartInspect Console" width="550" height="334" class="size-full wp-image-892" /></a><br />
<span>The SiTrace sample log shown in the <a href="http://www.gurock.com/smartinspect/tour/1/">SmartInspect Console</a></span>
</div>
<h2>Logging exceptions</h2>
<p>Another typical use-case for logging is recording all occurring exceptions and this is usually done by adding log calls to your exception handlers. Adding log statements to all your exception handlers can get tedious and error-prone though (e.g., you could forget to rethrow the exception after logging it), so we&#8217;ve added an aspect to automate this task for you. To use it, just add the <code>SiException</code> attribute to your code:</p>
<pre class="brush: csharp;">
using System;
using Gurock.SmartInspect;
using Gurock.SmartInspect.PostSharp;

...

[assembly: SiException(SessionName=&quot;Main&quot;)]

...

		static void Hello(string name)
		{
			SiAuto.Main.LogMessage(&quot;Hello, {0}.&quot;, name);
			throw new Exception(&quot;This is a test exception&quot;);
		}

...
</pre>
<p>Note how the exception is now automatically included in the resulting log (within the expected method context):</p>
<div class="framed-image">
<a href="/wp-content/uploads/2009/10/postsharp-siexception.png"><img src="/wp-content/uploads/2009/10/postsharp-siexception-small.png" alt="The SiException sample log shown in the SmartInspect Console" title="The SiException sample log shown in the SmartInspect Console" width="550" height="334" class="size-full wp-image-892" /></a><br />
<span>The SiException sample log shown in the <a href="http://www.gurock.com/smartinspect/tour/1/">SmartInspect Console</a></span>
</div>
<h2>Watching field values</h2>
<p>Arguably the most advanced aspect in this library is the <code>SiField</code> attribute. This attribute lets you automatically record any changes to values of object or class fields. The aspect gets notified whenever the value of a field changes and then logs the name of the field along with its old and new value. You can configure whether the aspect should send the name and values as normal log messages or as SmartInspect watches (for showing the latest values of a variable in the watches toolbox or for displaying its history as a chart in the watches graph). By default, both watches and normal messages are logged.</p>
<p>Let&#8217;s have a look at the following example which demonstrates <code>SiField</code> in practice. Note how we use <code>SiField</code> as an attribute for the entire assembly again. We could also limit it to individual classes or fields, either by writing the attribute above the classes/fields we want to inspect or by specifying filters/attribute targets for the global attribute.</p>
<pre class="brush: csharp;">
using System;
using Gurock.SmartInspect;
using Gurock.SmartInspect.PostSharp;

[assembly: SiField(SessionName = &quot;Main&quot;)]

namespace Gurock.SmartInspect.PostSharp.Samples
{
	class Program
	{
		public static int FIELD;

		static void Main(string[] args)
		{
			SiAuto.Si.Enabled = true; // Enable logging
			Counting();
		}

		static void Counting()
		{
			Random r = new Random();

			for (int i = 0; i &lt; 10; i++)
			{
				FIELD = r.Next(100);
				Thread.Sleep(1000);
			}
		}
	}
}
</pre>
<p>And here&#8217;s the generated log in the SmartInspect Console:</p>
<div class="framed-image">
<a href="/wp-content/uploads/2009/10/postsharp-sifield.png"><img src="/wp-content/uploads/2009/10/postsharp-sifield-small.png" alt="The SiField sample log shown in the SmartInspect Console" title="The SiField sample log shown in the SmartInspect Console" width="550" height="334" class="size-full wp-image-892" /></a><br />
<span>The SiField sample log shown in the <a href="http://www.gurock.com/smartinspect/tour/1/">SmartInspect Console</a></span>
</div>
<p>As you can see, every field change is automatically logged and shown in the Console. The watches toolbox in the lower left of the Console displays the latest value of <code>FIELD</code> in addition to the normal log messages in the main view. Also note the watches graph on the right that displays the field&#8217;s history as a chart (with its values over time). I believe an upcoming version of PostSharp will also be able to watch properties and we will update our library accordingly when this feature is available.</p>
<p>The nice thing about these aspects is that they can be freely combined as you like. You can mix and match the aspects as needed. If you plan to use our aspects and library, I also recommend taking a look at the <a href="http://www.postsharp.org/">PostSharp documentation</a> for more details about aspects, AOP and PostSharp in general as well as how to configure PostSharp for more complex scenarios.</p>
<p>Feel free to <a href="mailto:tg@gurock.com">send me an email</a> or leave a comment on this blog in case you have any questions <a href="http://www.gurock.com/smartinspect/resources/">about this plugin</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.gurock.com/postings/aspect-oriented-logging-for-net-with-postsharp-and-smartinspect/848/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Working with Delphi&#8217;s new Exception.StackTrace</title>
		<link>http://blog.gurock.com/postings/working-with-delphis-new-exception-stacktrace/730/</link>
		<comments>http://blog.gurock.com/postings/working-with-delphis-new-exception-stacktrace/730/#comments</comments>
		<pubDate>Mon, 12 Oct 2009 16:30:16 +0000</pubDate>
		<dc:creator>Tobias Gurock</dc:creator>
				<category><![CDATA[DelphiFeeds.com]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[SmartInspect]]></category>
		<category><![CDATA[si-article]]></category>

		<guid isPermaLink="false">http://blog.gurock.com/?p=730</guid>
		<description><![CDATA[One feature I often miss when using Delphi is the support for proper exception stack traces at run-time. You know, those useful stack traces that show you exactly where an exception occurred, ideally with the method name and line number of where the exception was raised. Both .NET and Java have excellent stack trace support [...]]]></description>
			<content:encoded><![CDATA[<p>One feature I often miss when using Delphi is the support for proper exception stack traces at run-time. You know, those useful stack traces that show you exactly where an exception occurred, ideally with the method name and line number of where the exception was raised. Both .NET and Java have excellent stack trace support built right into the framework and the Exception classes. You just call <a href="http://msdn.microsoft.com/en-us/library/system.exception.stacktrace.aspx">Exception.StackTrace</a> (.NET) or <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Throwable.html#getStackTrace%28%29">Exception.getStackTrace</a> (Java) and get a detailed analysis of where the exception was thrown and how it got passed to your exception handler.</p>
<p>Unfortunately, Delphi never had good (built-in) run-time support for stack traces. The features for stack traces during debugging in the IDE are/were okay, but there were nothing in the language or framework which helped you to find out programmatically where an exception occurred at run-time and, more importantly, how it got passed to your exception handler (besides the original exception address, maybe). So, I was happy to see that Delphi 2009 finally introduced a new StackTrace property which, I hoped, would return a full-blown stack trace when you caught an exception.</p>
<p>The initial happiness soon wore off when I realized that the StackTrace property was really just a placeholder to <em>return a stack trace from a possible stack trace provider</em> rather than a real stack trace implementation. So, without such a provider (and there&#8217;s none that comes directly with Delphi), there is still no way to get a stack trace for your exceptions. Though a bit disappointing, the good thing is that there&#8217;s now finally a standardized way to get a stack trace, even if it&#8217;s not implemented by default.</p>
<p>Exception reporting tools such as <a href="http://www.eurekalog.com/">Eurekalog</a> or <a href="http://www.madshi.net/madExceptDescription.htm">madExcept</a> or debug helpers such as the <a href="http://sourceforge.net/projects/jcl/">JclDebug</a> unit can register themselves as providers and use their engines to return a stack trace when an exception is raised. I&#8217;ve built a small unit which demonstrates this with the Jcl in combination with our logging tool <a href="http://www.gurock.com/smartinspect/">SmartInspect</a> and I&#8217;ve heard Fabio of Eurekalog is working on a similar feature for his component:</p>
<pre class="brush: delphi;">
unit StackTrace;

interface

uses
  SysUtils, Classes, JclDebug;

implementation

function GetExceptionStackInfoProc(P: PExceptionRecord): Pointer;
var
  LLines: TStringList;
  LText: String;
  LResult: PChar;
begin
  LLines := TStringList.Create;
  try
    JclLastExceptStackListToStrings(LLines, True, True, True, True);
    LText := LLines.Text;
    LResult := StrAlloc(Length(LText));
    StrCopy(LResult, PChar(LText));
    Result := LResult;
  finally
    LLines.Free;
  end;
end;

function GetStackInfoStringProc(Info: Pointer): string;
begin
  Result := string(PChar(Info));
end;

procedure CleanUpStackInfoProc(Info: Pointer);
begin
  StrDispose(PChar(Info));
end;

initialization
  // Start the Jcl exception tracking and register our Exception
  // stack trace provider.
  if JclStartExceptionTracking then
  begin
    Exception.GetExceptionStackInfoProc := GetExceptionStackInfoProc;
    Exception.GetStackInfoStringProc := GetStackInfoStringProc;
    Exception.CleanUpStackInfoProc := CleanUpStackInfoProc;
  end;

finalization
  // Stop Jcl exception tracking and unregister our provider.
  if JclExceptionTrackingActive then
  begin
    Exception.GetExceptionStackInfoProc := nil;
    Exception.GetStackInfoStringProc := nil;
    Exception.CleanUpStackInfoProc := nil;
    JclStopExceptionTracking;
  end;
end.
</pre>
<p>The unit merely starts and stops the exception tracking of the Jcl, implements a minimal stack trace provider and registers for the Exception provider events. The GetExceptionStackInfoProc and CleanUpStackInfoProc functions are automatically called by the RTL to give the provider the opportunity to initialize and cleanup the stack trace after an exception occurred. GetStackInfoStringProc is called indirectly when you access the StackTrace property and is responsible for returning the actual stack trace. </p>
<p>So, how do you use this unit? Let&#8217;s have a look at the following example:</p>
<pre class="brush: delphi;">
...

uses
  ..., StackTrace;

type
  TForm1 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    procedure SomeMethod;
  end;

implementation

procedure TForm1.Button1Click(Sender: TObject);
begin
  try
    SomeMethod;
  except
    // Log the exception: We use SmartInspect here because it has
    // built-in support for Exception.StackTrace but you could also
    // access the StackTrace property here directly.
    SiMain.LogException;
  end;
end;

procedure TForm1.SomeMethod;
begin
  raise Exception.Create('A test exception');
end;

...
</pre>
<p>As you can see, using this unit is just a matter of adding it to our uses clause. It won&#8217;t get any simpler than that. The unit will take care of registering/unregistering itself as a stack trace provider and when you now access the StackTrace property of an Exception object, you will get a detailed stack trace. To include the method names and line numbers in the stack trace, make sure to let the linker include debug symbols into your application and to enable the &#8216;Use debug .dcus&#8217; option in case you also want line numbers from the VCL and RTL methods.</p>
<div style="text-align: center">
<a href="/wp-content/uploads/2009/10/delphi-stacktrace.png"><br />
<img src="/wp-content/uploads/2009/10/delphi-stacktrace-small.png" alt="delphi-stacktrace-small" title="delphi-stacktrace-small" width="550" height="441" class="aligncenter size-full wp-image-787" /></a><br />
<em>The <a href="http://www.gurock.com/smartinspect/">SmartInspect Console</a> showing the stack trace of an exception</em>
</div>
<p>Now, when you use SmartInspect for logging and have a stack trace provider registered, all your logged exceptions automatically include the exception&#8217;s call stack. Pretty useful, isn&#8217;t it?</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.gurock.com/postings/working-with-delphis-new-exception-stacktrace/730/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>SQLite logging for Delphi with SmartInspect</title>
		<link>http://blog.gurock.com/postings/sqlite-logging-for-delphi-with-smartinspect/591/</link>
		<comments>http://blog.gurock.com/postings/sqlite-logging-for-delphi-with-smartinspect/591/#comments</comments>
		<pubDate>Tue, 16 Jun 2009 16:15:20 +0000</pubDate>
		<dc:creator>Dennis Gurock</dc:creator>
				<category><![CDATA[DelphiFeeds.com]]></category>
		<category><![CDATA[Gurock Software]]></category>
		<category><![CDATA[SmartInspect]]></category>
		<category><![CDATA[si-article]]></category>

		<guid isPermaLink="false">http://blog.gurock.com/?p=591</guid>
		<description><![CDATA[David Lambert was kind enough to send us his very nice SmartInspect SQLite logging protocol for Delphi and allowed us to make it available on our website. It can be used to write SmartInspect logging data to an SQLite database instead of typical log files, allowing for customized filtering and analysis with SQL tools. This [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.dmisoft.com/">David Lambert</a> was kind enough to send us his very nice SmartInspect SQLite logging protocol for Delphi and allowed us to make it available on our website. It can be used to write SmartInspect logging data to an SQLite database instead of typical log files, allowing for customized filtering and analysis with SQL tools. This SmartInspect protocol is licensed under the Creative Commons Attribution license and uses the DISQLite3 database library, which is available as a free personal edition or affordable professional version with additional features from <a href="http://www.yunqa.de/delphi/doku.php/products/sqlite3/index">Ralf Junker</a>.</p>
<p><a href="http://blog.gurock.com/wp-content/uploads/2009/06/sqlite-log.png"><img src="http://blog.gurock.com/wp-content/uploads/2009/06/sqlite-log-small.png" alt="" title="" width="540" height="332" class="alignright size-full wp-image-597" /></a><br />
<em>SmartInspect SQLite log viewed in <a href="http://www.yunqa.de/delphi/doku.php/products/sqlitespy/index">SQLiteSpy</a></em></p>
<p>The logging protocol automatically creates and initializes a new SQLite database on its first use, making it very easy to deploy application with it. All SmartInspect packets such as log entries, watches and process flow entries are supported and stored in the resulting SQLite database. <del datetime="2009-06-17T16:24:32+00:00">Please note that the protocol has been written for Delphi 2009, but there are only a few changes required if you want to use it with an older Delphi version.</del> <strong>Update:</strong> The protocol works with multiple Delphi versions out of the box, including Delphi 2007 and Delphi 2009.</p>
<p>Until our upcoming new website with a more useful SmartInspect resources section has been launched (scheduled for next month), you can download David&#8217;s protocol here:</p>
<p><strong><a href="http://www.gurock.com/downloads/smartinspect/smartinspect-sqlite.zip">Download</a></strong> (5 KB)</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.gurock.com/postings/sqlite-logging-for-delphi-with-smartinspect/591/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using SmartInspect  with madExcept</title>
		<link>http://blog.gurock.com/postings/using-smartinspect-with-madexcept/354/</link>
		<comments>http://blog.gurock.com/postings/using-smartinspect-with-madexcept/354/#comments</comments>
		<pubDate>Wed, 17 Dec 2008 21:21:42 +0000</pubDate>
		<dc:creator>Dennis Gurock</dc:creator>
				<category><![CDATA[DelphiFeeds.com]]></category>
		<category><![CDATA[Gurock Software]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[SmartInspect]]></category>
		<category><![CDATA[si-article]]></category>

		<guid isPermaLink="false">http://blog.gurock.com/?p=354</guid>
		<description><![CDATA[Inspired by our recent article about using EurekaLog together with SmartInspect, SmartInspect user Jeremy Brown ported our example to madExcept and kindly provided us with screenshots and sample code.

The example project demonstrates how to attach an event handler to madExcept and add a SmartInspect log file to madExept&#8217;s crash report whenever an unhandled exception occurs:

uses
 [...]]]></description>
			<content:encoded><![CDATA[<p>Inspired by our recent article about <a href="http://www.gurock.com/products/smartinspect/articles/integrating-smartinspect-and-eurekalog/">using EurekaLog together with SmartInspect</a>, SmartInspect user Jeremy Brown ported our example to <a href="http://www.madshi.net/madExceptDescription.htm">madExcept</a> and kindly provided us with screenshots and sample code.</p>
<div style="text-align: center"><a href="http://blog.gurock.com/images/postings/2008-12-17/crash.png"><img src="http://blog.gurock.com/images/postings/2008-12-17/crash-small.png" /></a></div>
<p>The example project demonstrates how to attach an event handler to madExcept and add a SmartInspect log file to madExept&#8217;s crash report whenever an unhandled exception occurs:</p>
<pre class="brush: delphi;">
uses
  madExcept;

// [...]

procedure ExceptionHandler(const ExceptIntf: IMEException;
    var Handled: Boolean);
const
  ZIPFILE = 'CrashReport.zip';
var
  LStream   : TFileStream;
  LTempPath : array[0..MAX_PATH+1] of Char;
  LFileName : String;
begin
  Handled := False;

  { Get a temporary filename }
  if GetTempPath(MAX_PATH, LTempPath) = 0 then
    Exit;

  // Save madShi's bug report information in the log.
  SiMain.LogException(Exception(ExceptIntf.ExceptObject),
    'Madshi Exception Handler');
  SiMain.LogString('BugReport', ExceptIntf.BugReport);

  ExceptIntf.AdditionalAttachments.Clear;

  { Put everything in a zip file }
  ExceptIntf.ScreenShotZip := ZIPFILE;
  ExceptIntf.BugReportZip  := ZIPFILE;

  { Just some extra optional information }
  ExceptIntf.AdditionalFields.Add('Application',
    Application.Title);

  LFileName := IncludeTrailingPathDelimiter(LTempPath) +
    'CrashLog.sil';
  { Save the log file }
  LStream := TFileStream.Create(LFileName, fmCreate);
  try
    Si.Dispatch('mem', 0, LStream);
  finally
    LStream.Free;
  end;

  { Attach the file to madShi's crash report }
  ExceptIntf.AdditionalAttachments.Add(LFileName, '', ZIPFILE);
end;

initialization
  RegisterExceptionHandler(ExceptionHandler,
    stTrySyncCallOnSuccess);
end.
</pre>
<p>The resulting madExcept email and crash report zip file includes a SmartInspect log file with the recent user actions and application data, along with madExcept&#8217;s error report and screenshot:</p>
<div style="text-align: center"><img src="http://blog.gurock.com/images/postings/2008-12-17/archive.png" style="border: 1px solid silver" /></div>
<p>If you are already using madExcept and are planning to integrate it with SmartInspect (or the other way around), Jeremy&#8217;s example code is a great starting point and should get you up and running in a few minutes. You can <a href="http://blog.gurock.com/images/postings/2008-12-17/madexcept-smartinspect.zip">download the example code here</a> and learn more about the used techniques in the related <a href="http://www.gurock.com/products/smartinspect/articles/integrating-smartinspect-and-eurekalog/">EurekaLog article</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.gurock.com/postings/using-smartinspect-with-madexcept/354/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
