<?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/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>This one goes to 11</title>
	<atom:link href="https://phillters.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>https://phillters.wordpress.com</link>
	<description></description>
	<lastBuildDate>Sun, 02 Nov 2014 13:10:54 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<site xmlns="com-wordpress:feed-additions:1">5949481</site><cloud domain='phillters.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>https://s2.wp.com/i/webclip.png</url>
		<title>This one goes to 11</title>
		<link>https://phillters.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="https://phillters.wordpress.com/osd.xml" title="This one goes to 11" />
	<atom:link rel='hub' href='https://phillters.wordpress.com/?pushpress=hub'/>
	<item>
		<title>Running hapi in Azure</title>
		<link>https://phillters.wordpress.com/2014/11/02/running-hapi-in-azure/</link>
					<comments>https://phillters.wordpress.com/2014/11/02/running-hapi-in-azure/#respond</comments>
		
		<dc:creator><![CDATA[Phill]]></dc:creator>
		<pubDate>Sun, 02 Nov 2014 13:10:54 +0000</pubDate>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Azure]]></category>
		<category><![CDATA[hapi]]></category>
		<category><![CDATA[nodejs]]></category>
		<guid isPermaLink="false">http://phillters.wordpress.com/?p=156</guid>

					<description><![CDATA[Running Node in Azure may not seem the most intuitive but turns out to be quite easy. Azure has a number of options for hosting free sites/api’s which makes trying them out and hosting basic services relatively straight forward. The Azure website has documentation to setup a node app with automated deployment through Git. The [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>Running Node in Azure may not seem the most intuitive but turns out to be quite easy. Azure has a number of options for hosting free sites/api’s which makes trying them out and hosting basic services relatively straight forward.</p>
<p>The Azure website has <a href="http://azure.microsoft.com/en-us/documentation/articles/web-sites-nodejs-develop-deploy-mac/">documentation</a> to setup a node app with automated deployment through Git. The sample uses the node http server but hapi works just as well with a few modifications.</p>
<p>The sample doesn’t make it clear but Azure handles the host and port environment variables a bit differently than expected. Rather than the port being an integer, as expected, it’s a string containing a named pipe. Hapi can manage Windows named pipes just fine but requires a different setup than the normal host, port parameters.</p>
<p>The key in the below sample is to use the port as the host if it’s a named pipe. </p>
<div id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:3a2ce383-5fda-45c2-a4ce-0aa436db0e36" class="wlWriterEditableSmartContent" style="float:none;margin:0;display:inline;padding:0;">
<pre style="white-space:normal;">
<pre class="brush: jscript; pad-line-numbers: true; title: ; notranslate">
var hapi = require('hapi');

var host = process.env.HOST || '0.0.0.0';
var port = process.env.PORT || 8081;

var server;
if (port.toString().indexOf('pipe') &gt;= 0) {
    // Azure uses named pipes defined in the port env variable
    server = hapi.createServer(port);
}
else {
    // running locally
    server = hapi.createServer(host, port);
}
</pre>
</div>
<p>This <a href="https://github.com/hapijs/hapi/issues/1127">github issue</a> describes the problem and resolution.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://phillters.wordpress.com/2014/11/02/running-hapi-in-azure/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">156</post-id>
		<media:content url="https://2.gravatar.com/avatar/54096e54218942d6d2666adc3a98af22a93e590169948f2d8c69c91a6e20016c?s=96&#38;d=https%3A%2F%2F2.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">Phill</media:title>
		</media:content>
	</item>
		<item>
		<title>WCF with Subclasses, Abstract Classes and Interfaces</title>
		<link>https://phillters.wordpress.com/2011/05/14/wcf-with-subclasses-abstract-classes-and-interfaces/</link>
					<comments>https://phillters.wordpress.com/2011/05/14/wcf-with-subclasses-abstract-classes-and-interfaces/#comments</comments>
		
		<dc:creator><![CDATA[Phill]]></dc:creator>
		<pubDate>Sat, 14 May 2011 15:29:26 +0000</pubDate>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[WCF]]></category>
		<guid isPermaLink="false">http://phillters.wordpress.com/?p=146</guid>

					<description><![CDATA[Building a domain object model will inevitably lead to creating subclasses, abstract classes and interfaces to represent related objects and concepts. Polymorphism is after all a core tenant of object-oriented languages. C# handles these concepts gracefully as they are first class citizens within the language. However, managing these concepts in the world of web services [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>
Building a domain object model will inevitably lead to creating subclasses, abstract classes and interfaces to represent related objects and concepts. Polymorphism is after all a core tenant of object-oriented languages. C# handles these concepts gracefully as they are first class citizens within the language. However, managing these concepts in the world of web services (in this case SOAP) and the need to serialize and deserialize the objects into XML or JSON presents a challenge within the staticly typed nature of C# (ignoring the dynamic features of .net 4.0). Keeping in mind C# is staticly typed, how can a deserialization engine determine the proper type to be created when the only information available is an abstract class or interface? The engine would have to discover the available concrete types inspect the properties of each and figure out which object correctly maps to the serialized object.
</p>
<p><pre class="brush: csharp; title: ; notranslate">
[DataContract]
public class MyClass
{
    [DataMember]
    public IEnumerable&lt;IAnimal&gt; Animals { get; set; }
}
</pre>
</p>
<p><pre class="brush: csharp; title: ; notranslate">
public interface IAnimal
{
    string Name { get; set; }
}

[DataContract]
public class Dog : IAnimal
{
    [DataMember]
    public string Name { get; set; }

    [DataMember]
    public bool IsMansBestFriend { get; set; }
}

[DataContract]
public class Cat : IAnimal
{
    [DataMember]
    public string Name { get; set; }
    
    [DataMember]
    public string FavoriteCatFood { get; set; }
}
</pre>
</p>
<p>
In fact, WCF won&#8217;t even return the DataContract MyClass. WCF can&#8217;t figure out how to deserialize the list of dogs and cats. The solution is to use the KnownTypes attribute on the DataContract making use of these subclassed objects. With the KnownType attribute, WCF knows which concrete objects to use when deserializing.
</p>
<p><pre class="brush: csharp; title: ; notranslate">
[DataContract]
[KnownType(typeof(Dog))]
[KnownType(typeof(Cat))]
public class MyClass
{
    [DataMember]
    public IEnumerable&lt;IAnimal&gt; Animals { get; set; }
}
</pre>
</p>
<p>
It appears WCF handles this situation a bit differently depending on whether you&#8217;re using Add Service Reference to go after the WSDL or if you&#8217;re using the contracts directly and opening a ChannelFactory. Using the WSDL it appears you&#8217;ll get back a list of objects, not strongly typed. If you&#8217;re using the ChannelFactory and using the contract definitions then you&#8217;ll get strongly typed results.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://phillters.wordpress.com/2011/05/14/wcf-with-subclasses-abstract-classes-and-interfaces/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">146</post-id>
		<media:content url="https://2.gravatar.com/avatar/54096e54218942d6d2666adc3a98af22a93e590169948f2d8c69c91a6e20016c?s=96&#38;d=https%3A%2F%2F2.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">Phill</media:title>
		</media:content>
	</item>
		<item>
		<title>Cost-Benefit Analysis of Developer Productivity</title>
		<link>https://phillters.wordpress.com/2011/04/23/cost-benefit-analysis-of-developer-productivity/</link>
					<comments>https://phillters.wordpress.com/2011/04/23/cost-benefit-analysis-of-developer-productivity/#respond</comments>
		
		<dc:creator><![CDATA[Phill]]></dc:creator>
		<pubDate>Sat, 23 Apr 2011 14:46:05 +0000</pubDate>
				<category><![CDATA[Uncategorized]]></category>
		<guid isPermaLink="false">http://phillters.wordpress.com/?p=107</guid>

					<description><![CDATA[I&#8217;m going show how investing in high performance computers for developers, to save as little as 10 minutes a day, will provide a return on investment in under a year in addition to the many soft and indirect benefits. The concept of a developer getting &#8220;in the zone&#8221; is well documented. It seems that most [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>
I&#8217;m going show how investing in high performance computers for developers, to save as little as 10 minutes a day, will provide a return on investment in under a year in addition to the many soft and indirect benefits.
</p>
<p>
The concept of a developer getting &#8220;in the zone&#8221; is well documented.  It seems that most programmers with a blog have at least one post discussing how they best get &#8220;in the zone.&#8221;  This is the idea that the highest quality code is written when a developer can fully immerse themselves in the code or problem at hand and completely lose awareness of their surroundings.  Joel Spolsky has noted this occurs most frequently when a developer has quiet surroundings, possibly aided by headphones, see <a href="http://www.joelonsoftware.com/articles/fog0000000043.html">number 8 and 9</a> in his list of ways to improve your development process.  Keeping a dev &#8220;in the zone&#8221; is key to keeping them as productive as they possibly can be.
</p>
<p>
One of the easiest ways to get a developer out of the zone is to keep them from waiting for their computer to catch up.  Most processes that a developer waits on such as opening new applications, compiling, and running unit tests can be shortened by better hardware.  Though expensive, the hardware is much less expensive than the developer themselves.  As such it easy to show how the smallest time savers can improve productivity and save money.
</p>
<p>
Take a developer making $50,000, an amount not uncommon for entry level developers.  Assuming 2 weeks of vacation, they&#8217;re working 2,000 hours per year (250 days) works out to $25/hour.  Let&#8217;s also assume a cost of $2,000 for a new computer that will have a useful life of 2 years.  If this developer waits 9.6 minutes per day on their computer, the cost to his/her company is $4/day ($25*(9.6/60)).  Take $4 per day for 250 days per year works out to $1,000/year.  Over a 2 year period the organization will break even, financially.  The chart below shows the break-even point for developers at different salary levels and the amount of time saved per day that would justify a $2,000 computer.
</p>
<table border="1">
<tr>
<td>Salary</td>
<td>Minutes</td>
</tr>
<tr>
<td>$50,000</td>
<td>9.6</td>
</tr>
<tr>
<td>$60,000</td>
<td>8.0</td>
</tr>
<tr>
<td>$70,000</td>
<td>6.86</td>
</tr>
<tr>
<td>$80,000</td>
<td>6.0</td>
</tr>
<tr>
<td>$90,000</td>
<td>5.33</td>
</tr>
<tr>
<td>$100,000</td>
<td>4.8</td>
</tr>
<tr>
<td>$110,000</td>
<td>4.36</td>
</tr>
<tr>
<td>$120,000</td>
<td>4.0</td>
</tr>
</table>
<p>
The above chart shows only the break-even point.  Consider a developer making $60,000 working on a slow machine that he/she waits on for 20 minutes each day.  That 20 minutes in which the developer waits costs their organization $2,500 per year!  Spending $2,000 results in a return on investment in less than 10 months.  Over the 2 year life of the computer that results in an internal rate of return (<a href="http://en.wikipedia.org/wiki/Internal_rate_of_return">IRR</a>) of 91%.  Let&#8217;s assume for a minute that a company expects a 15% return for any investment to be accepted.  Over the 2 year span an investment of $2,000 to save 1 developer 20 minutes each day results in a net present value (<a href="http://en.wikipedia.org/wiki/Net_present_value">NPV&gt;</a>) of $2,064.
</p>
<p>
Providing high performance machines for developers not only increases productivity but can also provide incentive for new hires as well as perks for existing ones.  Developers enjoy working on the latest and greatest and providing that equipment can result in better employees.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://phillters.wordpress.com/2011/04/23/cost-benefit-analysis-of-developer-productivity/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">107</post-id>
		<media:content url="https://2.gravatar.com/avatar/54096e54218942d6d2666adc3a98af22a93e590169948f2d8c69c91a6e20016c?s=96&#38;d=https%3A%2F%2F2.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">Phill</media:title>
		</media:content>
	</item>
		<item>
		<title>Unity &#8211; Named Resolution with a Parameter Attribute</title>
		<link>https://phillters.wordpress.com/2011/04/22/unity-named-resolution-with-a-parameter-attribute/</link>
					<comments>https://phillters.wordpress.com/2011/04/22/unity-named-resolution-with-a-parameter-attribute/#respond</comments>
		
		<dc:creator><![CDATA[Phill]]></dc:creator>
		<pubDate>Sat, 23 Apr 2011 02:07:08 +0000</pubDate>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[IoC]]></category>
		<category><![CDATA[Unity]]></category>
		<guid isPermaLink="false">http://phillters.wordpress.com/?p=136</guid>

					<description><![CDATA[I try to limit dependencies in my code as much as possible. The less knowledge components have of each other the better. One such dependency I try to avoid is on a specific dependency injection container. Though the most popular containers generally feature the same general functionality I avoid having assembly references to a particular [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>
I try to limit dependencies in my code as much as possible. The less knowledge components have of each other the better. One such dependency I try to avoid is on a specific dependency injection container. Though the most popular containers generally feature the same general functionality I avoid having assembly references to a particular library in each project. I accomplish this by wrapping each external library in an abstracted library. This abstracted library has a tendency to expose only the main, core functionality leaving some of the edge cases out.
</p>
<p>
This is one such case in which I want to specify a custom attribute on a constructor parameter that specifies the name the container should use to resolve the dependency. Unity, the underlying container, already provides this through the DependencyAttribute class. The problem is that using this attribute requires a reference to the Unity assembly. In order to utilize this feature but not take another dependency on Unity I&#8217;m going to add an extension to allow me to specify my own attribute from which to pull the name used to resolve the dependency.
</p>
<h3>
Step 1: Inherit from the DefaultUnityConstructorSelectorPolicy<br />
</h3>
<p>
This policy is used when resolving dependencies from the ctor. Override the CreateResolver method which takes a ParameterInfo object as a parameter. This method is called on each parameter to the ctor and with it we&#8217;ll look for the custom attribute and pull the name of the dependency being resolved. First is the custom attribute itself, it contains a single string field for the name of the dependency.
</p>
<p><pre class="brush: csharp; title: ; notranslate">
[AttributeUsage(AttributeTargets.Parameter)]
public class NamedAttribute : Attribute
{
    private readonly string name;

    public NamedAttribute(string name)
    {
        this.name = name;
    }

    public string Name { get { return name; } }
}
</pre>
</p>
<p><pre class="brush: csharp; title: ; notranslate">
public class NamedAttributeConstructorSelectorPolicy
    : DefaultUnityConstructorSelectorPolicy
{
    protected override IDependencyResolverPolicy
        CreateResolver(ParameterInfo parameter)
    {
        List&lt;NamedAttribute&gt; attributes = 
            parameter.GetCustomAttributes(false)
                .OfType&lt;NamedAttribute&gt;()
                .ToList();
        if (attributes.Count &gt; 0)
        {
            string name = attributes[0].Name;
            return new NamedTypeDependencyResolverPolicy(
                parameter.ParameterType, name);
        }

        return base.CreateResolver(parameter);
    }
}
</pre>
</p>
<h3>
Step 2: Add the custom policy to the context.<br />
</h3>
<p>
This is a simple class that simply adds the custom policy created in the first step to the collection of policies that default with Unity in the current context.
</p>
<p><pre class="brush: csharp; title: ; notranslate">
public class CustomUnityExtension : UnityContainerExtension
{
    protected override void Initialize()
    {
        Context.Policies
            .SetDefault&lt;IConstructorSelectorPolicy&gt;(
                new NamedAttributeConstructorSelectorPolicy());
    }
}
</pre>
</p>
<h3>
Step 3: Add the extension to the container.<br />
</h3>
<p>
Another simple snippet that adds the custom extension to the container. This taken from the ctor of the wrapper class around Unity.
</p>
<pre class="brush: csharp; title: ; notranslate">
public UnityApplicationBlockContainer(IUnityContainer container)
{
    this.container = container;

    container.AddNewExtension&lt;CustomUnityExtension&gt;();
}
</pre>
<p>
With these 3 steps in place you can start marking up the parameters within the ctors of services.
</p>
<p><pre class="brush: csharp; title: ; notranslate">
public class Service
{
    private readonly IDatabase sqlDatabase;
    private readonly IDatabase couchDatabase;

    public Service([Named(&quot;SqlDb&quot;)]IDatabase sqlDatabase, 
        [Named(&quot;CouchDb&quot;)]IDatabase couchDatabase)
    {
        this.sqlDatabase = sqlDatabase;
        this.couchDatabase = couchDatabase;
    }
}
</pre>
]]></content:encoded>
					
					<wfw:commentRss>https://phillters.wordpress.com/2011/04/22/unity-named-resolution-with-a-parameter-attribute/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">136</post-id>
		<media:content url="https://2.gravatar.com/avatar/54096e54218942d6d2666adc3a98af22a93e590169948f2d8c69c91a6e20016c?s=96&#38;d=https%3A%2F%2F2.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">Phill</media:title>
		</media:content>
	</item>
		<item>
		<title>ActiveMQ Generic Typed Client for Queue Access</title>
		<link>https://phillters.wordpress.com/2010/11/06/activemq-generic-typed-client-for-queue-access/</link>
					<comments>https://phillters.wordpress.com/2010/11/06/activemq-generic-typed-client-for-queue-access/#respond</comments>
		
		<dc:creator><![CDATA[Phill]]></dc:creator>
		<pubDate>Sat, 06 Nov 2010 19:37:15 +0000</pubDate>
				<category><![CDATA[Uncategorized]]></category>
		<guid isPermaLink="false">http://phillters.wordpress.com/?p=131</guid>

					<description><![CDATA[The .Net client that exists to interact with ActiveMQ provides means to send and receive messages but it requires explicit knowledge of both the name of the queue that should be read from or pushed to and the type of the objects that are serialized into that queue. I find that these pieces of information [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>
The <a href="http://activemq.apache.org/nms/">.Net client</a> that exists to interact with ActiveMQ provides means to send and receive messages but it requires explicit knowledge of both the name of the queue that should be read from or pushed to and the type of the objects that are serialized into that queue.  I find that these pieces of information are not necessary for communication and add complexity as well as instability in the case where differently typed objects are serialized and sent to the queue.
</p>
<p>
A better approach I&#8217;ve found for interacting with the queue is to abstract away the specific queue that is being used as well as the type of the object being pulled from it.  This is done by using the fully qualified type of the object being pushed to the queue as the queue name.  This means you no longer need to specify which specific queue a message should be sent to because it&#8217;s based on the type of the object being serialized into a message.  This has the side effect of no longer needing to worry about the type of the object that is getting deserialized from the queue either since the queue is dependent on the type of object.
</p>
<p>
Lets start off with a definition of the object we&#8217;ll serialize and push to the queue.
</p>
<p><pre class="brush: csharp; title: ; notranslate">
namespace Organization.SubNamespace
{
    public class User
    {
        public string Name { get; set; }

        public int Age { get; set; }

        public DateTime Birthday { get; set; }
    }
}
</pre>
</p>
<p>
Now that we have an object to serialize, lets look at the base definition of the queue service and some helper methods we&#8217;ll use.
</p>
<p><pre class="brush: csharp; title: ; notranslate">
public class GenericQueueService&lt;T&gt;
    : IQueuePublisher&lt;T&gt;, IQueueConsumer&lt;T&gt;, IAsyncQueueConsumer&lt;T&gt; where T : class
{
    private readonly IQueue queue;
    private readonly Serializer serializer;
    private ISession session;
    private IMessageConsumer messageConsumer;
    private IMessageProducer messageProducer;

    public event EventHandler&lt;ConsumeQueueItemEventArgs&lt;T&gt;&gt; ConsumeQueueItem;

    public GenericQueueService()
    {
        queue = new ActiveMQQueue(typeof(T).FullName);
        serializer = new Serializer();
    }

    private void EnsureConsumerExists()
    {
        if (messageConsumer != null)
        {
            return;
        }

        if (session == null)
        {
            session = CreateSession();
        }

        messageConsumer = session.CreateConsumer(queue);
    }

    private static ISession CreateSession()
    {
        IConnectionFactory connectionFactory = 
            new ConnectionFactory(Settings.Default.MQServer);
        IConnection connection = connectionFactory.CreateConnection();
        connection.Start();
        return connection.CreateSession(AcknowledgementMode.ClientAcknowledge);
    }

    private void EnsureProducerExists()
    {
        if (messageProducer != null)
        {
            return;
        }

        if (session == null)
        {
            session = CreateSession();
        }

        messageProducer = session.CreateProducer(queue);
    }
}
</pre>
</p>
<p>
On the class definition I&#8217;ve identified a number of interfaces that can be used to get at specific parts of this service depending on whether there&#8217;s a need to push or pull messages from the queue.  Also included is an async specific listener so that messages can be pulled asynchronously.  This implementation requires that a separate service be instantiated for each type of object that will be pushed/pulled from the queue.
</p>
<p>
Notice in the constructor when a the new ActiveMQQueue object is created the fully qualified type name is used as the queue in which to communicate with.  A feature I like about ActiveMQ is that if a queue doesn&#8217;t exist yet pushing a message will create it on the fly.
</p>
<p><pre class="brush: csharp; title: ; notranslate">
public void Publish(T publishObject)
{
    EnsureProducerExists();

    ITextMessage textMessage = session.CreateTextMessage(serializer.Serialize(publishObject));
    messageProducer.Send(textMessage);
}
</pre>
</p>
<p>
The above method first ensures a producer exists which can push messages to the queue.  Next the object is serialized and the result passed to a TextMessage which is used host the serialized object.  Finally the message is sent to the server.
</p>
<p><pre class="brush: csharp; title: ; notranslate">
public T Consume()
{
    EnsureConsumerExists();

    IMessage message = messageConsumer.Receive();
    ITextMessage textMessage = message as ITextMessage;
    if (textMessage == null)
    {
        throw new MQException(&quot;Message pulled from queue must be of type ITextMessage.&quot;);
    }

    return ProcessTextMessage(textMessage);
}

private T ProcessTextMessage(ITextMessage textMessage)
{
    if (textMessage == null)
    {
        throw new MQException(&quot;Message from queue must be of type ITextMessage.&quot;);
    }

    return serializer.Deserialize&lt;T&gt;(textMessage.Text);
}
</pre>
</p>
<p>
Here we see how to consume messages synchronously.  The message is retrieved from the queue, casted to an ITextMessage and its contents are then deserialized back into an object.
</p>
<p><pre class="brush: csharp; title: ; notranslate">
public void StartAsyncConsumer()
{
    EnsureConsumerExists();

    messageConsumer.Listener += messageConsumer_Listener;
}

private void messageConsumer_Listener(IMessage message)
{
    T item = ProcessTextMessage(message as ITextMessage);
    if (ConsumeQueueItem != null)
    {
        ConsumeQueueItem(this, new ConsumeQueueItemEventArgs&lt;T&gt;(item));
    }
}
</pre>
</p>
<p>
This implementation requires that an instance of the queue service be created for each object type that is pushed to the message queue.  An enhancement could be made to allow a single service that takes in multiple types and manages itself which queues the messages are passed to and which queues messages should be retrieved from.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://phillters.wordpress.com/2010/11/06/activemq-generic-typed-client-for-queue-access/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">131</post-id>
		<media:content url="https://2.gravatar.com/avatar/54096e54218942d6d2666adc3a98af22a93e590169948f2d8c69c91a6e20016c?s=96&#38;d=https%3A%2F%2F2.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">Phill</media:title>
		</media:content>
	</item>
		<item>
		<title>Data Layer Abstraction</title>
		<link>https://phillters.wordpress.com/2010/10/26/data-layer-abstraction/</link>
					<comments>https://phillters.wordpress.com/2010/10/26/data-layer-abstraction/#respond</comments>
		
		<dc:creator><![CDATA[Phill]]></dc:creator>
		<pubDate>Wed, 27 Oct 2010 02:53:55 +0000</pubDate>
				<category><![CDATA[Uncategorized]]></category>
		<guid isPermaLink="false">http://phillters.wordpress.com/?p=127</guid>

					<description><![CDATA[One of the most common functions of an application is to retrieve data from a database. I&#8217;m going to provide a simple layer of abstraction to provide the basis from which to implement a service layer that can be used to retrieve data from a database to provide for both abstraction and scalability. The implementation [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>
One of the most common functions of an application is to retrieve data from a database.  I&#8217;m going to provide a simple layer of abstraction to provide the basis from which to implement a service layer that can be used to retrieve data from a database to provide for both abstraction and scalability.  The implementation provided is an attempt to limit the dependency on SQL Server and allow for the possibility to switch to Oracle or another database if needed with relative ease.  There is some degree of support for Oracle within the .Net framework that would make the transition to this platform easier than others.  There is the possibility that switching to DB2, MySql or another provider but there would be an amount of work to implement some classes to comply with the interfaces used in this implementation.  Another important aspect of the abstraction is to provide the ability to unit test services which rely on these classes.
</p>
<p>
It should be mentioned that generally I&#8217;m not providing the interface definitions.  Unless otherwise noted, assume all public members are exposed via the interface.  I&#8217;ve also removed comments from all of the members for sake of brevity but comments should always be included!
</p>
<p>
The implementation below of the CommandExecutor is to execute the provided database command and return either an IDataReader or the number of records affected by the query depending on the method executed.
</p>
<p><pre class="brush: csharp; title: ; wrap-lines: false; notranslate">
public class CommandExecutor : ICommandExecutor
{
    private readonly ILogger logger;

    public CommandExecutor(ILogger logger)
    {
        this.logger = logger;
    }

    public IDataReader ExecuteReader(IDbCommand command)
    {
        IDataReader reader;
        try
        {
            reader = command.ExecuteReader();
        }
        catch(SqlException e)
        {
            logger.Log(e);
            throw;
        }
        catch(InvalidOperationException e)
        {
            logger.Log(e);
            throw;
        }

        return reader;
    }

    public int ExecuteNonQueury(IDbCommand command)
    {
        try
        {
            return command.ExecuteNonQuery();
        }
        catch(SqlException e)
        {
            logger.Log(e);
            throw;
        }
        catch(InvalidOperationException e)
        {
            logger.Log(e);
            throw;
        }
    }
}
</pre>
</p>
<p>
The purpose of the ObjectMapper class is to utilize the utility <a href="http://automapper.codeplex.com/">automapper</a> which I&#8217;ve discussed in 2 parts <a href="http://wp.me/poXJn-1Q">here</a> and <a href="http://wp.me/poXJn-1X">here</a>.  This class will map the results contained in an IDataReader to a List of strongly typed objects that make sense in the domain in which they are used.  We&#8217;ll see in a bit the configuration required in order to make this work (it&#8217;s pretty simple, only a single line of code if everything lines up right).
</p>
<p><pre class="brush: csharp; title: ; wrap-lines: false; notranslate">
public class ObjectMapper : IMapper
{
    public TDestination Map&lt;TSource, TDestination&gt;(TSource source)
    {
        return Mapper.Map&lt;TSource, TDestination&gt;(source);
    }

    public TDestination Map&lt;TSource, TDestination&gt;(TSource source, TDestination destination)
    {
        return Mapper.Map(source, destination);
    }
}
</pre>
</p>
<p>
Below is an implementation of a SQL Server specific connection.  The connection string is pulled from the application configuration file of the project in which this class is contained.  This class does not protect itself against some possible null reference exceptions and attempts to log critical errors regarding failure to connect to the database.  Remember all public members are exposed through the interface and note the judicious use of non-SQL Server specified interfaces as the return types of the methods and properties in order to support the possibility of utilizing a different database platform.  As a side effect, the use of these interfaces also eases the unit testability of this abstraction.
</p>
<p><pre class="brush: csharp; title: ; wrap-lines: false; notranslate">
public class SqlConnection : IDatabaseConnection
{
    private readonly ILogger logger;

    public SqlConnection(ILogger logger)
    {
        this.logger = logger;

        ChangeConnection(Settings.Default.MADatabase);
    }

    public IDbConnection DbConnection { get; set; }

    public void Open()
    {
        DbConnection.Open();
    }

    public IDbTransaction GetSqlTransaction()
    {
        return DbConnection.BeginTransaction();
    }

    public void EstablishNewConnection()
    {
        ChangeConnection(Settings.Default.MADatabase);
    }

    public void ChangeConnection(string connectionString)
    {
        // Nice to register connection string in the container, then resolve named parameters (Unity addon would be needed).
        if (string.IsNullOrEmpty(connectionString))
        {
            logger.Log(&quot;Could not retrieve db connection string from Settings file.&quot;, LogSeverity.Error);
            return;
        }

        try
        {
            DbConnection = new System.Data.SqlClient.SqlConnection(connectionString);
            DbConnection.Open();
        }
        catch(InvalidOperationException e)
        {
            logger.Log(&quot;Could not open database connection!&quot;, e, LogSeverity.Critical);
        }
        catch(SqlException e)
        {
            logger.Log(&quot;Could not open database connection!&quot;, e, LogSeverity.Critical);   
        }
    }

    public IDbCommand CreateCommand()
    {
        return DbConnection.CreateCommand();
    }
}
</pre>
</p>
<p>
The below class, DatabaseExecutor, is used as a utility by the abstract class that our domain specific services will implement.  This class allows for the creation of transactions as well as executing commands and returning strongly typed results.  The dependencies have all been defined above and are represented as interfaces of which the implementations will be injected.  There are a number of overloads of the Execute method to return the results of the command, return whether the command executed successfully and passing the results as an out parameter and finally executing a command that doesn&#8217;t return results.
</p>
<p><pre class="brush: csharp; title: ; wrap-lines: false; notranslate">
public class DatabaseExecutor : IDatabase
{
    private readonly ILogger logger;
    private readonly IDatabaseConnection dbConnection;
    private readonly IMapper mapper;
    private readonly ICommandExecutor commandExecutor;
    private IDbTransaction currentTransaction;

    public DatabaseExecutor(ILogger logger, IDatabaseConnection dbConnection,
        IMapper mapper, ICommandExecutor commandExecutor)
    {
        this.logger = logger;
        this.dbConnection = dbConnection;
        this.mapper = mapper;
        this.commandExecutor = commandExecutor;

        currentTransaction = null;
    }

    public void BeginTransaction()
    {
        currentTransaction = dbConnection.GetSqlTransaction();
    }

    public void CommitTransaction()
    {
        currentTransaction.Commit();

        currentTransaction = null;
    }

    public void RollbackTransaction()
    {
        currentTransaction.Rollback();

        currentTransaction = null;
    }

    public T Execute&lt;T&gt;(IDbCommand command) where T : class, new()
    {
        if (command == null)
        {
            return null;
        }

        command.Connection = dbConnection.DbConnection;
        command.Transaction = currentTransaction;

        IDataReader reader;
        try
        {
            reader = commandExecutor.ExecuteReader(command);
        }
        catch(SqlException)
        {
            StringBuilder builder = new StringBuilder(&quot;Database command failure details&quot;);
            builder.AppendLine();
            builder.AppendLine(command.CommandText);
            foreach (IDataParameter parameter in command.Parameters)
            {
                builder.AppendLine(string.Format(&quot;{0}:{1}&quot;,
                    parameter.ParameterName, parameter.Value));
            }

            logger.Log(builder.ToString(), LogSeverity.Error);

            throw;
        }

        if (reader == null)
        {
            return null;
        }

        try
        {
            return typeof(IEnumerable).IsAssignableFrom(typeof(T))
                       ? mapper.Map&lt;IDataReader, T&gt;(reader)
                       : mapper.Map&lt;IDataReader, List&lt;T&gt;&gt;(reader).FirstOrDefault();
        }
        catch(Exception e)
        {
            logger.Log(e);
            throw;
        }
        finally
        {
            reader.Close();
        }
    }

    public bool Execute&lt;T&gt;(IDbCommand command, out T result)
        where T : class, new()
    {
        result = Execute&lt;T&gt;(command);

        return result != null
            ? true
            : false;
    }

    public void Execute(IDbCommand command)
    {
        if (command == null)
        {
            return;
        }

        command.Connection = dbConnection.DbConnection;
        command.Transaction = currentTransaction;

        try
        {
            commandExecutor.ExecuteNonQueury(command);
        }
        catch(SqlException)
        {
            StringBuilder builder = new StringBuilder(&quot;Database command failure details&quot;);
            builder.AppendLine(command.CommandText);
            foreach (IDataParameter parameter in command.Parameters)
            {
                builder.AppendLine(string.Format(&quot;{0}:{1}&quot;,
                    parameter.ParameterName, parameter.Value));
            }

            logger.Log(builder.ToString(), LogSeverity.Error);
            throw;
        }
    }
}
</pre>
</p>
<p>
The abstract class that should be used as the base for any data access services is provided below.  From this class transaction may be started.  Also is a helper function, GetValueCatchNull, which is used when using Automapper to map between fields that don&#8217;t match by convention (example shown further below).
</p>
<p>
My original implementation of this abstract class included properties and methods that would dynamically inspect the properties of an object and create parameter and value lists that could be passed to sql insert/select/update/delete commands but was only half-baked and thus not included here so if this looks a bit sparse and you&#8217;re wondering why you couldn&#8217;t just request the IDatabase class as a direct dependency within your data access service, you could.  Hopefully in the future I&#8217;ll find a better implementation of a way to do this but as of yet hasn&#8217;t worked very well.
</p>
<p><pre class="brush: csharp; title: ; notranslate">
public abstract class DatabaseServiceBase
{
    protected readonly IDatabase database;

    protected DatabaseServiceBase(IDatabase database)
    {
        this.database = database;
    }

    public void BeginTransaction()
    {
        database.BeginTransaction();
    }

    public void CommitTransaction()
    {
        database.CommitTransaction();
    }

    public void RollbackTransaction()
    {
        database.RollbackTransaction();
    }

    protected static T GetValueCatchNull&lt;T&gt;(Func&lt;T&gt; func)
    {
        try
        {
            return func();
        }
        catch(SqlNullValueException)
        {
            return default(T);
        }
    }
}
</pre>
</p>
<p>
Finally, an implementation of the data service layer utilizing the above defined classes.  Notice here how we&#8217;re implementing the abstract class DatabaseServiceBase and calling the base constructor and passing to it the requested dependency IDatabase.  Also of importance is the static constructor which creates the mapping between the results from the database (IDataReader) and mapping that to the User object.  See the previous <a href="http://wp.me/poXJn-1X">automapper</a> post for info on why we&#8217;re mapping a single object to a data type that may return multiple results.  Notice the use of the GetValueCatchNull in order to manage if a null value is returned from the IDataReader and cannot be applied to value types.  Last but not least notice that in the GetUsers method we&#8217;re actually returning a list of results and this is possible due to the previous implementation of the IDatabase interface defined as DatabaseExecutor which allows us to pass in a single object or List of objects and it will map both.
</p>
<p><pre class="brush: csharp; title: ; wrap-lines: false; notranslate">
public class UserService : DatabaseServiceBase, IUserService
{
    private readonly ILogger logger;

    public UserService(ILogger logger, IDatabase database)
        : base(database)
    {
        this.logger = logger;
    }

    static UserService()
    {
        Automapper.Mapper.CreateMap&lt;IDataReader, User&gt;()
            .ForMember(m =&gt; m.FirstName, opt =&gt; opt.MapFrom(p =&gt; GetValueCatchNull(() =&gt; p.GetString(p.GetOrdinal(&quot;First&quot;)))));
    }

    public User GetUserById(int userId)
    {
        SqlCommand command = new SqlCommand(&quot;select * from Users where UserId = @UserId&quot;);
        command.Parameters.AddWithValue(&quot;@UserId&quot;, userId);

        return database.Execute&lt;User&gt;(command);
    }

    public List&lt;Users&gt; GetUsers()
    {
        SqlCommand command = new SqlCommand(&quot;select * from Users&quot;);
        
        return database.Execute&lt;List&lt;Users&gt;&gt;(command);
    }
}
</pre>
</p>
<p>
There you have it, an abstraction of a data layer that will ease transition from a SQL Server database to Oracle or even an unsupported system like DB2 or MySql.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://phillters.wordpress.com/2010/10/26/data-layer-abstraction/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">127</post-id>
		<media:content url="https://2.gravatar.com/avatar/54096e54218942d6d2666adc3a98af22a93e590169948f2d8c69c91a6e20016c?s=96&#38;d=https%3A%2F%2F2.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">Phill</media:title>
		</media:content>
	</item>
		<item>
		<title>Using Automapper Part 2 &#8211; Object Relational Mapping (ORM)</title>
		<link>https://phillters.wordpress.com/2010/10/24/using-automapper-part-2-object-relational-mapping-orm/</link>
					<comments>https://phillters.wordpress.com/2010/10/24/using-automapper-part-2-object-relational-mapping-orm/#respond</comments>
		
		<dc:creator><![CDATA[Phill]]></dc:creator>
		<pubDate>Sun, 24 Oct 2010 23:29:18 +0000</pubDate>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Automapper]]></category>
		<guid isPermaLink="false">http://phillters.wordpress.com/?p=121</guid>

					<description><![CDATA[Last time I described that basic usage of Automapper to map the properties of one object to the properties of another. A more interesting use of the tool is as an object-relational mapper (ORM). Object-relational mapping is the process of taking data retrieved from the database and representing it as objects in your application. An [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>
<a href="http://wp.me/poXJn-1Q">Last time</a> I described that basic usage of <a href="http://automapper.codeplex.com/">Automapper</a> to map the properties of one object to the properties of another.  A more interesting use of the tool is as an object-relational mapper (ORM).  Object-relational mapping is the process of taking data retrieved from the database and representing it as objects in your application.  An alternative method would be to manipulate ADO.Net objects that are created by the Sql libraries as part of the ADO framework.  The ADO.Net objects can either be data readers or data tables which can be tedious to work with.  Rather than access the data through those objects, ORM allows you to create data models that represent the data from the database for more intuitive manipulation.  Let&#8217;s look at an example.
</p>
<p><pre class="brush: csharp; title: ; notranslate">
public class User
{
    public int UserId { get; set; }

    public string FirstName { get; set; }

    public string LastName { get; set; }
}
</pre>
</p>
<p><pre class="brush: csharp; title: ; wrap-lines: false; notranslate">
public List&lt;User&gt; GetUsers()
{
    Automapper.Mapper.CreateMap&lt;IDataReader, User&gt;();

    SqlCommand command = new SqlCommand(&quot;select * from Users&quot;);
    command.Connection = new SqlConnection(&quot;connection string goes here&quot;);

    IDataReader dataReader = command.ExecuteReader();
    List&lt;User&gt; users = Automapper.Mapper.Map&lt;List&lt;User&gt;&gt;(dataReader);
    return users;
}
</pre>
</p>
<p>
Establishing the mapping relationship and actually mapping the objects gets a little tricky.  Notice the line Automapper.Mapper.CreateMap() maps the data reader to a single object.  The problem is that likely multiple records will be returned from the query resulting in multiple objects.  As such when the IDataReader is actually mapped to a list of objects, the destination is specified as an IEnumberable.  I prefer to directly use the List class because it is not uncommon to use the FirstOrDefault() Linq extenstion method when I know there is only 1 record being returned by the query if I&#8217;m retrieving a record by PK for example.
</p>
<p>
It would probably be a good idea to throw a try-catch around the Map method call in order to catch exceptions thrown when the results of an IDataReader cannot be mapped to an object.  Also a good idea to close the IDataReader but the example shown is to demonstrate the object mapping capabilities.
</p>
<p>
The example above expects that the database column names identically match the data model properties (including case, ie &#8216;UserId&#8217; does not map to &#8216;UserID&#8217;).  In these cases when you create the mapping relationship you can specify which properties should be mapped where.  Mapping the data reader is a bit annoying but looks like the below code.
</p>
<p><pre class="brush: csharp; title: ; wrap-lines: false; notranslate">
public List&lt;User&gt; GetUsers()
{
    Automapper.Mapper.CreateMap&lt;IDataReader, User&gt;()
        .ForMember(m =&gt; m.UserId, opt =&gt; opt.MapFrom(r =&gt; r.GetInt32(r.GetOrdinal(&quot;UserID&quot;))))
        .ForMember(m =&gt; m.FirstName, opt =&gt; opt.MapFrom(r =&gt; r.GetString(r.GetOrdinal(&quot;FirstNameColumnName&quot;))));

    // Rest of code...
}
</pre></p>
]]></content:encoded>
					
					<wfw:commentRss>https://phillters.wordpress.com/2010/10/24/using-automapper-part-2-object-relational-mapping-orm/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">121</post-id>
		<media:content url="https://2.gravatar.com/avatar/54096e54218942d6d2666adc3a98af22a93e590169948f2d8c69c91a6e20016c?s=96&#38;d=https%3A%2F%2F2.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">Phill</media:title>
		</media:content>
	</item>
		<item>
		<title>Using Automapper (Part 1)</title>
		<link>https://phillters.wordpress.com/2010/10/23/using-automapper-part-1/</link>
					<comments>https://phillters.wordpress.com/2010/10/23/using-automapper-part-1/#respond</comments>
		
		<dc:creator><![CDATA[Phill]]></dc:creator>
		<pubDate>Sat, 23 Oct 2010 13:31:57 +0000</pubDate>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Automapper]]></category>
		<guid isPermaLink="false">http://phillters.wordpress.com/?p=114</guid>

					<description><![CDATA[Automapper is a convention-based, object-to-object mapping utility which is open-source and hosted on codeplex. In a two-part series I&#8217;m going to show how Automapper can be used not only to map objects to each other but also as an Object-Relational Mapper for mapping results pulled from a database into objects. Part 2 is about using [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>
<a href="http://automapper.codeplex.com/">Automapper</a> is a convention-based, object-to-object mapping utility which is open-source and hosted on <a href="http://www.codeplex.com/">codeplex</a>.  In a two-part series I&#8217;m going to show how Automapper can be used not only to map objects to each other but also as an Object-Relational Mapper for mapping results pulled from a database into objects.
</p>
<p>
<a href="http://wp.me/poXJn-1X">Part 2</a> is about using Automapper as an object-relational mapper (ORM).
</p>
<p>
This tool has a number of useful and time saving functions.  It&#8217;s normal function proves helpful when implementing best practices around XML serialization/deserialization as well as WCF data contracts in which you want to utilize objects in your application that aren&#8217;t necessarily marked up with XML attributes, are able to be versioned in the case of WCF or in which you want to change the structure of the data model to better fit your needs for use within your application.  In these scenarios you typically have two identical data model objects with properties of the same name and type, except one of the objects is marked up with XML attributes or WCF data contract attributes.  Rather than create a helper method to map between these objects Automapper will figure out which properties line up based on convention (same name and type).  Automapper requires a single line of code to tell it, statically, which objects should map to each other and then you simply give Automapper your source object and it returns to you a new instance of your mapped object.  Simple example is provided below.
</p>
<p><pre class="brush: csharp; title: ; notranslate">
[DataContract]
public class SourceObject
{
    [DataMember]
    public int MyIntegerProperty { get; set; }

    [DataMember]
    public string MyStringProperty { get; set }
}
</pre>
</p>
<p><pre class="brush: csharp; title: ; notranslate">
public class DestinationObject
{
    public int MyIntegerProperty { get; set; }

    public string MyStringProperty { get; set; }
}
</pre>
</p>
<p><pre class="brush: csharp; title: ; wrap-lines: false; notranslate">
public class Test
{
    public static void Main(string[] args)
    {
        Automapper.Mapper.CreateMap&lt;SourceObject, DestinationObject&gt;();

        SourceObject source = new SourceObject
            {
                MyIntegerProperty = 123, 
                MyStringProperty = &quot;asdf&quot;
            };

        // destination object contains int property with value 123 
        // and string property with value &quot;adsf&quot;.
        DestinationObject destination =
            Automapper.Mapper.Map&lt;DestinationObject&gt;(source);
    }
}
</pre>
</p>
<p>
For situations in which you have properties that do not match by convention, as in they are spelled differently or in the case where you wish to change the data structure, Automapper provides a way to specify which properties should be matched to other properties.
</p>
<p><pre class="brush: csharp; title: ; notranslate">
public class NewDestinationObject
{
    public int SomeIntegerProperty { get; set; }

    public string AStringProperty { get; set; }
}
</pre>
</p>
<p><pre class="brush: csharp; title: ; wrap-lines: false; notranslate">
public static void Main(string[] args)
{
    Automapper.Mapper.CreateMap&lt;SourceObject, NewDestinationObject&gt;()
        .ForMember(m =&gt; m.SomeIntegerProperty, opt =&gt; opt.MapFrom(p =&gt; p.MyIntegerProperty))
        .ForMember(m =&gt; m.AStringProperty, opt =&gt; opt.MapFrom(p =&gt; p.MyStringProperty));

        SourceObject source = new SourceObject
            {
                MyIntegerProperty = 123, 
                MyStringProperty = &quot;asdf&quot;
            };

        DestinationObject destination =
            Automapper.Mapper.Map&lt;DestinationObject&gt;(source);
}
</pre>
</p>
<p>
In the above example, Automapper allows you to use Lambda expressions to specify the properties to map to and the properties they should be mapped from.  Given the use of Lambda&#8217;s, you can create any number of complicated mapping schemas.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://phillters.wordpress.com/2010/10/23/using-automapper-part-1/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">114</post-id>
		<media:content url="https://2.gravatar.com/avatar/54096e54218942d6d2666adc3a98af22a93e590169948f2d8c69c91a6e20016c?s=96&#38;d=https%3A%2F%2F2.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">Phill</media:title>
		</media:content>
	</item>
		<item>
		<title>Hosting Silverlight Application in a WCF Rest Service</title>
		<link>https://phillters.wordpress.com/2010/09/12/hosting-silverlight-application-in-a-wcf-rest-service/</link>
					<comments>https://phillters.wordpress.com/2010/09/12/hosting-silverlight-application-in-a-wcf-rest-service/#comments</comments>
		
		<dc:creator><![CDATA[Phill]]></dc:creator>
		<pubDate>Sun, 12 Sep 2010 16:30:11 +0000</pubDate>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[REST]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[WCF]]></category>
		<guid isPermaLink="false">http://phillters.wordpress.com/?p=97</guid>

					<description><![CDATA[Typically Silverlight apps are hosted in IIS or on some other web server. Getting a website setup can be a tedious process and constantly deploying can be annoying especially if the service is not an integral one to the functionality of an application. A WCF Rest service is an easy way to test Silverlight applications [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>
Typically Silverlight apps are hosted in IIS or on some other web server.  Getting a website setup can be a tedious process and constantly deploying can be annoying especially if the service is not an integral one to the functionality of an application.  A WCF Rest service is an easy way to test Silverlight applications or host utility apps that don&#8217;t need to be especially scalable.
</p>
<p>
I find it convenient also to reference web services used by the Silverlight client relative the base url of the rest service (the url of the browser).
</p>
<p><pre class="brush: csharp; title: ; notranslate">
[ServiceContract]
public interface IFrameworkRestService
{
    [OperationContract]
    [WebGet(UriTemplate=&quot;clientaccesspolicy.xml&quot;)] 
    Stream ClientAccessPolicy();

    [OperationContract]
    [WebGet(UriTemplate = &quot;{fileName}&quot;)]
    Stream GetFile(string fileName);

    [OperationContract]
    [WebGet(UriTemplate = &quot;&quot;)]
    Stream RootHtmlPage();
}</pre>
</p>
<p>
As with all WCF services, attributes are used to indicate a particular class is a web service.  Additionally each method is marked with the OperationContract attribute.  The WebGet attribute indicates a particular method should be accessed in a restful way.  The UriTemplate parameter defines how the operation can be accessed relative the base URL used to expose the service.  For example if the service is exposed on the URL, &#8220;<a href="http://localhost/MyService&#038;#8221" rel="nofollow">http://localhost/MyService&#038;#8221</a>;, the ClientAccessPolicy can be executed by calling the URL, &#8220;<a href="http://localhost/MyService/clientaccesspolicy.xml&#038;#8221" rel="nofollow">http://localhost/MyService/clientaccesspolicy.xml&#038;#8221</a>;.  The RootHmtlPage can be accessed through the URL, &#8220;<a href="http://localhost/MyService&#038;#8221" rel="nofollow">http://localhost/MyService&#038;#8221</a>; as an empty string is passed to the UrlTemplate attribute.  The GetFile method has a special parameter, with brackets around the name, that maps to any URL after the &#8216;MyService&#8217; part of the URL.  This method will serve up the Xap Silverlight files.  Some examples would be &#8220;<a href="http://localhost/MyService/Test1.xap&#038;#8221" rel="nofollow">http://localhost/MyService/Test1.xap&#038;#8221</a>; and &#8216;<a href="http://localhost/MyService/Test2.xap&#038;#8217" rel="nofollow">http://localhost/MyService/Test2.xap&#038;#8217</a>;.  The name of the file is passed into the GetFile method in the fileName parameter.
</p>
<p><pre class="brush: csharp; title: ; notranslate">
[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single, AddressFilterMode=AddressFilterMode.Any)]
public class FrameworkRestService : IFrameworkRestService
{
    private readonly ILogger logger;

    public FrameworkRestService(ILogger logger)
    {
        this.logger = logger;
    }

    public Stream ClientAccessPolicy()
    {
        const string result = @&quot;&lt;?xml version=&quot;&quot;1.0&quot;&quot; encoding=&quot;&quot;utf-8&quot;&quot;?&gt;
                    &lt;access-policy&gt;
                        &lt;cross-domain-access&gt;
                            &lt;policy&gt;
                                &lt;allow-from http-request-headers=&quot;&quot;*&quot;&quot;&gt;
                                    &lt;domain uri=&quot;&quot;*&quot;&quot;/&gt;
                                &lt;/allow-from&gt;
                                &lt;grant-to&gt;
                                    &lt;resource path=&quot;&quot;/&quot;&quot; include-subpaths=&quot;&quot;true&quot;&quot;/&gt;
                                &lt;/grant-to&gt;
                            &lt;/policy&gt;
                        &lt;/cross-domain-access&gt;
                    &lt;/access-policy&gt;&quot;;

        if (WebOperationContext.Current != null)
        {
            WebOperationContext.Current.OutgoingResponse.ContentType = &quot;application/xml&quot;;
        }

        return new MemoryStream(Encoding.UTF8.GetBytes(result));
    }

    public Stream GetFile(string fileName)
    {
        string path = AppDomain.CurrentDomain.BaseDirectory;
        string absolutePath = string.Format(@&quot;{0}\{1}&quot;, path, fileName);

        logger.Log(string.Format(&quot;Serving up {0}.&quot;, absolutePath));

        try
        {
            return new FileStream(absolutePath, FileMode.Open);
        }
        catch(Exception e)
        {
            logger.Log(&quot;Exception getting file.&quot;, e);
        }

        return null;
    }

    public Stream RootHtmlPage()
    {
        if (WebOperationContext.Current != null)
        {
            WebOperationContext.Current.OutgoingResponse.ContentType = &quot;text/html&quot;;
        }

        string path = AppDomain.CurrentDomain.BaseDirectory;

        logger.Log(&quot;Serving up root MAClient html page.&quot;);

        try
        {
            return new FileStream(string.Concat(path, @&quot;ClientTestPage.html&quot;), FileMode.Open);
        }
        catch(Exception e)
        {
            logger.Log(&quot;Exception retrieving root html page.&quot;, e);
        }

        return null;
    }
}
</pre>
</p>
<p>
Couple things to note in the implementation of the REST service.  Don&#8217;t forget to set the MIME type when serving up the root html page and the clientaccesspolicy.  Not sure why but the browser has trouble figuring out what it&#8217;s getting if this isn&#8217;t set.  It is assumed that the Silverlight HTML files and Xap files are located in the directory that the application is running from but this could be set to anywhere in the GetFile method.
</p>
<p>
The test html page created by Visual Studio usually references the base Silverlight xap file within the ClientBin directory.  Edit the html file and remove the ClientBin from before the xap file reference.  Otherwise the GetFile method won&#8217;t be called because it won&#8217;t match the UriTemplate of the GetFile interface method.
</p>
<p><pre class="brush: csharp; title: ; wrap-lines: false; notranslate">
public class RestServiceHost
{
    private readonly IFrameworkRestService;
    private readonly WebServiceHost restServiceHost;

    public RestServiceHost()
    {
        IFrameworkRestService restService = new FrameworkRestService(new Logger());
        restServiceHost = new WebServiceHost(restService, new Uri(&quot;http://localhost/MyService&quot;, UriKind.Absolute));

        restServiceHost.Open();
    }

}
</pre>
</p>
<p>
Use the WebServiceHost rather than ServiceHost as it is better suited for hosting Rest services (less configuration required).  Once these services are running navigate your browser to <a href="http://localhost/MyService" rel="nofollow">http://localhost/MyService</a> and the Silverlight app should appear.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://phillters.wordpress.com/2010/09/12/hosting-silverlight-application-in-a-wcf-rest-service/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">97</post-id>
		<media:content url="https://2.gravatar.com/avatar/54096e54218942d6d2666adc3a98af22a93e590169948f2d8c69c91a6e20016c?s=96&#38;d=https%3A%2F%2F2.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">Phill</media:title>
		</media:content>
	</item>
		<item>
		<title>Enterprise Library Logging</title>
		<link>https://phillters.wordpress.com/2010/09/12/enterprise-library-logging/</link>
					<comments>https://phillters.wordpress.com/2010/09/12/enterprise-library-logging/#respond</comments>
		
		<dc:creator><![CDATA[Phill]]></dc:creator>
		<pubDate>Sun, 12 Sep 2010 15:29:33 +0000</pubDate>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[EnterpriseLibrary]]></category>
		<category><![CDATA[Logging]]></category>
		<guid isPermaLink="false">http://phillters.wordpress.com/?p=90</guid>

					<description><![CDATA[Logging is an essential function of an application to help debug issues that occur on a production system when you don&#8217;t have access to a debugger. It is also helpful to keep track of what&#8217;s happening as it runs during testing, as a confirmation that the events and actions you expect to happen are happening. [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>
Logging is an essential function of an application to help debug issues that occur on a production system when you don&#8217;t have access to a debugger.  It is also helpful to keep track of what&#8217;s happening as it runs during testing, as a confirmation that the events and actions you expect to happen are happening.
</p>
<p>
There are a number of popular logging utilities and for the most part each is about as good as any other.  They are all very similar.  I am partial to the <a href="http://entlib.codeplex.com/">Enterprise Library Logging Application Block</a> which can be downloaded <a href="http://www.microsoft.com/downloads/en/details.aspx?FamilyId=bcb166f7-dd16-448b-a152-9845760d9b4c&amp;displaylang=en">here</a>.
</p>
<p>
The Enterprise Library Logging Application Block, like other logging frameworks, allow you to create log messages and send those messages to different targets of output.  Multiple output targets may be configured.  The most typical output targets include a console window, file, database, web services and email though any conceivable target could be configured.  Use of the logging infrastructure includes 3 components.  1) configuring each logging component 2) calling the logging infrastructure and 3) listening for log messages and sending them to the output targets.
</p>
<p>
The implementation below starts off with a wrapper around the actual EntLib logger.  The wrapper is intended to limit references to the EntLib assemblies to one project.  Going this route would allow for the EntLib logger to be swapped out for another with minimal impact on the application.
</p>
<p>
I should note that access to most loggers is static.  The wrapper implementation below uses the static calls but the object itself is intended to be registered in an IoC container and used as an instance.  This way I can add an interface and have better control over the object lifetime and better manage multiple loggers.  The application in which this logger is used manages long running background threads.  Each thread could be thought of as a sub-application and thus gets its own logger to differentiate the log messages.  Though when I say &#8220;own logger&#8221; it&#8217;s really separate instances of the wrapper making static calls to the underlying EntLib logger.  This approach also makes testing easier as I can mock out the logger interface and just ignore all logging calls in the unit tests.
</p>
<p><pre class="brush: csharp; title: ; wrap-lines: false; notranslate">
public class EntLibLogger : ILogger
{
    public string Name { get; set; }
        
    public void Log(string message)
    {
        Log(message, LogSeverity.Information);
    }

    public void Log(string message, LogSeverity logSeverity)
    {
        LogEntry log = new LogEntry
                           {
                               Message = message,
                               Priority = GetLogSeverity(logSeverity),
                               Title = Name
                           };
        log.Categories.Add(Name);
            
        Logger.Write(log);
    }

    public void Log(Exception exception)
    {
        Log(exception, LogSeverity.Error);
    }

    public void Log(Exception exception, LogSeverity logSeverity)
    {
        Log(string.Empty, exception, logSeverity);
    }

    public void Log(string message, Exception exception)
    {
        Log(message, exception, LogSeverity.Information);
    }

    public void Log(string message, Exception exception, LogSeverity logSeverity)
    {
        const string subjectFormat = &quot;{0}\r\n\r\n{1}&quot;;
        LogEntry logEntry = new LogEntry
                                {
                                    Message = string.IsNullOrEmpty(message) ? FormatException(exception) : string.Format(subjectFormat, message, FormatException(exception)),
                                    Priority = GetLogSeverity(logSeverity),
                                    Title = Name
                                };

        logEntry.Categories.Add(Name);
            
        // Set the category to the name of this logger, hopefully we can use this to distinguish log messages.
        // Setting the category causes the message to not be picked up by the console or email listeners, not sure whats up.
        //logEntry.Categories.Add(Name);
        Logger.Write(logEntry);
    }

    private static int GetLogSeverity(LogSeverity severity)
    {
        switch(severity)
        {
            case LogSeverity.Information:
                return 10;
            case LogSeverity.Highlight:
                return 20;
            case LogSeverity.Warning:
                return 30;
            case LogSeverity.Error:
                return 40;
            case LogSeverity.Critical:
                return 50;
            default:
                return 10;
        }
    }

    private static string FormatException(Exception exception)
    {
        StringBuilder formattedException = new StringBuilder();
        formattedException.AppendLine(exception.Source);
        formattedException.AppendLine(exception.Message);
        formattedException.AppendLine(exception.StackTrace);
        formattedException.AppendLine();

        if (exception.InnerException != null)
        {
            formattedException.AppendLine(FormatException(exception.InnerException));
        }

        return formattedException.ToString();
    }
}
</pre>
</p>
<p>
There are a number of utility/helper overrides of the Log method to ease logging the desired information at the certain levels.  The Name property exists to track in the log output where log messages come from.  The Name property is set when the log instance is created and each message that gets log has this Name included in it.  The GetLogSeverity method maps EntLib logging priority levels, indicated as integers, and translates those numbers to an enum containing more descriptive levels of logging priority.  The FormatException method translates the important information contained in an exception into something readable.  The ILogger interface contains all of the public methods in this class.
</p>
<p><pre class="brush: csharp; title: ; wrap-lines: false; notranslate">
[ConfigurationElementType(typeof(CustomTraceListenerData))]
public class ConsoleTraceListener : CustomTraceListener
{
    public ConsoleTraceListener()
    {
        Console.BufferHeight = 9999;
    }

    public override void TraceData(TraceEventCache eventCache, string source, TraceEventType eventType, int id, object data)
    {
        LogEntry log = data as LogEntry;
        if (log != null &amp;&amp; Formatter != null)
        {
            ConsoleColor color = Console.ForegroundColor;
            SetConsoleColor(log);
            WriteLine(Formatter.Format(data as LogEntry));
            Console.ForegroundColor = color;
        }
        else if (data != null)
        {
            WriteLine(data.ToString());
        }
    }

    public override void Write(string message)
    {
        Console.Write(message);
    }

    public override void WriteLine(string message)
    {
        Console.WriteLine(message);
    }

    private static void SetConsoleColor(LogEntry entry)
    {
        if (entry.Priority &lt;= 10)
        {
            Console.ForegroundColor = Settings.Default.InformationLogColor;
        }
        else if (entry.Priority &lt;= 20)
        {
            Console.ForegroundColor = Settings.Default.HighlightLogColor;
        }
        else if (entry.Priority &lt;= 30)
        {
            Console.ForegroundColor = Settings.Default.WarningLogColor;
        }
        else if (entry.Priority &lt;= 40)
        {
            Console.ForegroundColor = Settings.Default.ErrorLogColor;
        }
        else if (entry.Priority &lt;= 50)
        {
            Console.ForegroundColor = Settings.Default.CriticalLogColor;
        }
    }
}
</pre>
</p>
<p>
The above class inherits from the CustomTraceListener and has an attribute ConfigurationElementType.  The TraceData method is where the log messages get outputed.  It is a good idea to make use of the Write and WriteLine overrides in case the underlying class calls them as well.  The constructor sets the buffer of the Console window to be big in order to maintain a longer history of log messages.  This is important when you start to see large numbers of log messages.
</p>
<p>
The final step to logging with EntLib is to configure each of the previous components to work together.
</p>
<p><pre class="brush: xml; title: ; wrap-lines: false; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot; ?&gt;
&lt;configuration&gt;
  &lt;configSections&gt;
    &lt;section name=&quot;loggingConfiguration&quot; type=&quot;Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35&quot; /&gt;
    &lt;section name=&quot;dataConfiguration&quot; type=&quot;Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35&quot; /&gt;
  &lt;/configSections&gt;
  &lt;loggingConfiguration name=&quot;Logging Application Block&quot; tracingEnabled=&quot;true&quot;
    defaultCategory=&quot;General&quot; logWarningsWhenNoCategoriesMatch=&quot;true&quot;&gt;
    &lt;listeners&gt;
      &lt;add formatter=&quot;ConsoleFormatter&quot; initializeData=&quot;&quot; delimiter=&quot;------------------------------------&quot;
        listenerDataType=&quot;Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.CustomTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35&quot;
        traceOutputOptions=&quot;None&quot; filter=&quot;All&quot; type=&quot;MyNamespace.ConsoleTraceListener, MyAssembly.Name, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null&quot;
        name=&quot;ConsoleTraceListener&quot; /&gt;
      &lt;add source=&quot;Enterprise Library Logging&quot; formatter=&quot;Text Formatter&quot;
        log=&quot;Application&quot; machineName=&quot;&quot; listenerDataType=&quot;Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FormattedEventLogTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35&quot;
        traceOutputOptions=&quot;None&quot; filter=&quot;All&quot; type=&quot;Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FormattedEventLogTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35&quot;
        name=&quot;Formatted EventLog TraceListener&quot; /&gt;
    &lt;/listeners&gt;
    &lt;formatters&gt;
      &lt;add template=&quot;Timestamp: {timestamp}&#xD;&#xA;Message: {message}&#xD;&#xA;Category: {category}&#xD;&#xA;Priority: {priority}&#xD;&#xA;EventId: {eventid}&#xD;&#xA;Severity: {severity}&#xD;&#xA;Title:{title}&#xD;&#xA;Machine: {machine}&#xD;&#xA;Application Domain: {appDomain}&#xD;&#xA;Process Id: {processId}&#xD;&#xA;Process Name: {processName}&#xD;&#xA;Win32 Thread Id: {win32ThreadId}&#xD;&#xA;Thread Name: {threadName}&#xD;&#xA;Extended Properties: {dictionary({key} - {value}&#xD;&#xA;)}&quot;
        type=&quot;Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35&quot;
        name=&quot;Text Formatter&quot; /&gt;
      &lt;add type=&quot;Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35&quot;
           name=&quot;ConsoleFormatter&quot;
           template=&quot;{category} {timestamp}:  {message}&quot; /&gt;
    &lt;/formatters&gt;
    &lt;categorySources&gt;
      &lt;add switchValue=&quot;All&quot; name=&quot;General&quot;&gt;
        &lt;listeners&gt;
          &lt;add name=&quot;ConsoleTraceListener&quot; /&gt;
        &lt;/listeners&gt;
      &lt;/add&gt;
    &lt;/categorySources&gt;
    &lt;specialSources&gt;
      &lt;allEvents switchValue=&quot;All&quot; name=&quot;All Events&quot; /&gt;
      &lt;notProcessed switchValue=&quot;All&quot; name=&quot;Unprocessed Category&quot; /&gt;
      &lt;errors switchValue=&quot;All&quot; name=&quot;Logging Errors &amp;amp; Warnings&quot;&gt;
        &lt;listeners&gt;
          &lt;add name=&quot;Formatted EventLog TraceListener&quot; /&gt;
        &lt;/listeners&gt;
      &lt;/errors&gt;
    &lt;/specialSources&gt;
  &lt;/loggingConfiguration&gt;
&lt;/configuration&gt;
</pre>
</p>
<p>
Configuring the logger is a tedious process but does provide a lot of flexibility in terms of formatting output and determining which loggers get which log messages.  First, you need to setup the configuration sections of which there is one required for the EntLib logging application block called loggingConfiguration.  In the loggingConfiguration section add a listener to point to the ConsoleTraceListener class created ealier.  Also in the loggingConfiguration section create a formatter to determine how the output of the log messages in text will appear.  After the formatters, create categorySources which determines which targets will receive log messages from each logger.
</p>
<p>
Once the configuration is completed you&#8217;re ready to start logging messages.  There are a number of other log targets, mentioned earlier, that can be created to solve unique logging requirements.  I&#8217;ll include a couple other log listeners below that can be used.  The comments are removed for sake of brevity.
</p>
<p><pre class="brush: csharp; title: ; wrap-lines: false; notranslate">
[ConfigurationElementType(typeof(CustomTraceListenerData))]
public class EmailTraceListener : CustomTraceListener
{
    private readonly EmailLogService emailService;

    public EmailTraceListener()
    {
        emailService = new EmailLogService();
    }
    public override void TraceData(TraceEventCache eventCache, string source, TraceEventType eventType, int id, object data)
    {
        LogEntry logEntry = data as LogEntry;
        if (logEntry != null &amp;&amp; logEntry.Priority &gt;= 50)
        {
            emailService.SendExceptionEmail(logEntry.Title, logEntry.Message);
        }
    }

    public override void Write(string message)
    {
    }

    public override void WriteLine(string message)
    {
    }
}
</pre>
<pre class="brush: csharp; title: ; wrap-lines: false; notranslate">
public class EmailLogService
{
    private readonly SmtpClient mailClient;

    public EmailLogService()
    {
        mailClient = new SmtpClient(Constants.EmailHost, 25);
    }
   
    public void SendExceptionEmail(string subject, string body)
    {
        MailMessage email = new MailMessage
                                {
                                    From = new MailAddress(Constants.DefaultDebugEmailAddress),
                                    Subject = string.IsNullOrEmpty(subject) ? &quot;MAFramework Critical Error&quot; : subject,
                                    Body = body
                                };

        email.To.Add(Settings.Default.DefaultDebugEmailAddresses);

        mailClient.Send(email);
    }
}
</pre>
</p>
<p>
The EmailTraceListener sends an email for log messages of the highest priority which are reserved for serious system errors, usually in which the application is crashing or is being prevented from running normally.  Note in the TraceData method the send email service is used only when log priority is greater than or equal to 50.  Also note the Write and WriteLine methods do nothing.
</p>
<p><pre class="brush: csharp; title: ; wrap-lines: false; notranslate">
[ConfigurationElementType(typeof(CustomTraceListenerData))]
public class PublishLogTraceListener : CustomTraceListener
{
    private readonly ILogNotifier logNotifier;

    public PublishLogTraceListener()
    {
        logNotifier = LogNotifierFactory.GetLogNotifier();
    }

    static PublishLogTraceListener()
    {
        Mapper.CreateMap&lt;LogEntry, LogMessage&gt;();
    }

    public override void TraceData(TraceEventCache eventCache, string source, TraceEventType eventType, int id, object data)
    {
        LogEntry logEntry = data as LogEntry;
        if (logEntry == null)
        {
            return;
        }

        logNotifier.FireMessageLogged(Mapper.Map&lt;LogEntry, LogMessage&gt;(logEntry));
    }

    public override void Write(string message)
    {
    }

    public override void WriteLine(string message)
    {
    }
}
</pre>
</p>
<p>
The PublishLogTraceListener is used to broadcast log messages using WCF&#8217;s duplex services.  I have created a Silverlight web app that listens for and displays these log messages essentially creating a Console window in the browser that allows for viewing application log messages without being logged onto the server to see the actual console window.  Also since the Silverlight client is dealing with log message objects I can create a UI around sorting and filtering different messages to view only the most significant errors for the application function I&#8217;m interested in.  A sample implementation of the of the PollingDuplexBinding can be found in an older post <a href="http://wp.me/poXJn-1i">here</a>.  Note too that I&#8217;m using Automapper to map from the EntLib log object to a log object of my own.  This is so the client can have access to the log object without needing a reference to EntLib.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://phillters.wordpress.com/2010/09/12/enterprise-library-logging/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">90</post-id>
		<media:content url="https://2.gravatar.com/avatar/54096e54218942d6d2666adc3a98af22a93e590169948f2d8c69c91a6e20016c?s=96&#38;d=https%3A%2F%2F2.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">Phill</media:title>
		</media:content>
	</item>
	</channel>
</rss>
