<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">

  <title><![CDATA[Steven Kuhn]]></title>
  <link href="http://www.stevenkuhn.net/atom.xml" rel="self"/>
  <link href="http://www.stevenkuhn.net/"/>
  <updated>2013-02-28T09:50:52-06:00</updated>
  <id>http://www.stevenkuhn.net/</id>
  <author>
    <name><![CDATA[Steven Kuhn]]></name>
    
  </author>
  <generator uri="http://octopress.org/">Octopress</generator>

  
  <entry>
    <title type="html"><![CDATA[Triggering Events in a Windows Service From an ASP.NET Site Using Redis]]></title>
    <link href="http://www.stevenkuhn.net/blog/2012/02/02/triggering-events-in-a-windows-service-from-an-asp-dot-net-site-using-redis/"/>
    <updated>2012-02-02T00:37:00-06:00</updated>
    <id>http://www.stevenkuhn.net/blog/2012/02/02/triggering-events-in-a-windows-service-from-an-asp-dot-net-site-using-redis</id>
    <content type="html"><![CDATA[<p><em>(You can skip the introduction and go straight to the <a href="#install-redis">install and setup</a>).</em></p>

<p>I am working on a <a href="https://twitter.com/#!/stevenkuhn/status/109807616837947393">game server hosting project</a> using ASP.NET MVC which will allow users to rent and manage their own game servers on an hourly basis (instead of hosting their own or paying per month for a dedicated server). In order to keep the website responsive, my intention is to use a Windows service to schedule jobs and perform all of the background tasks. Of course, I needed a way for the ASP.NET to communicate with the Windows service in some manner. After weighing different options (exposing a WCF endpoint or using MSMQ), I decided to give Redis a try.</p>

<h2>What is Redis?</h2>

<p>From the <a href="http://redis.io/topics/introduction">Redis website</a>:</p>

<blockquote><p>Redis is an open source, advanced key-value store. It is often referred to as a data structure server since keys can contain <a href='http://redis.io/topics/data-types#strings'>strings</a>, <a href='http://redis.io/topics/data-types#hashes'>hashes</a>, <a href='http://redis.io/topics/data-types#lists'>lists</a>, <a href='http://redis.io/topics/data-types#sets'>sets</a> and <a href='http://redis.io/topics/data-types#sorted-sets'>sorted sets</a>.</p></blockquote>


<p>In other words, it&#8217;s a way to store strings in memory that is also shared, atomic, and persistent. Similar to <a href="http://memcached.org/">memcached</a>, the data in Redis is entirely stored in memory, but it also has native support to persist that data to disk.</p>

<h2>Why don&#8217;t you expose a WCF endpoint on the service?</h2>

<p>While I don&#8217;t like to <a href="http://en.wikipedia.org/wiki/Program_optimization#When_to_optimize">prematurely optimize</a>, two things that I want to keep in mind for this project are scalability and availability. If I simply expose a WCF endpoint, my website is tightly bound to the service. If the service goes down for an update or due to a crash, the website would go down along with it. One feature I want is the ability to take the website or service down without affecting the other.</p>

<h2>Why don&#8217;t you use MSMQ?</h2>

<p>To be honest I&#8217;m sure that MSMQ would work, but my brief experience with it has led me to believe it would be overkill for my simple use. I just want to push event messages to my service and not spend a lot of time configuring, managing, and troubleshooting MSMQ. Using Redis also gives me the flexibility of running it on Linux servers which can be more cost-effective compared to a Windows-only architecture.</p>

<h2><span id="install-redis">Installing and Running Redis</span></h2>

<h4>Download/Install the Server</h4>

<p>I looked at few Redis servers that run on Windows (see <a href="https://github.com/ServiceStack/ServiceStack.Redis">ServiceStack.Redis</a> wiki page under <em>Redis Server builds for Windows</em>) and <a href="https://github.com/dmajkic/redis/downloads">downloaded </a> one that used the latest version of Redis. From there it&#8217;s just a matter of extracting the files into the directory of your choice.</p>

<h4>Running the Server</h4>

<p>For development, I run the <code>redis-server.exe</code> file located inside the extracted path of <code>\redis-2.4.5-win32-win64\32bit\</code>. By default the server runs on port 6379.</p>

<h4>Install the Client</h4>

<p>The easiest method was to install the <a href="http://nuget.org/packages/ServiceStack.Redis">ServiceStack.Redis NuGet package</a> for both my website and Windows service projects, although I could <a href="https://github.com/ServiceStack/ServiceStack.Redis/downloads">download ServiceStack.Redis.dll</a> directly.</p>

<h2>Using the Redis Client</h2>

<p>I use <a href="http://ninject.org/">Ninject</a> as my IoC/DI container to manage my dependencies in my website and service so first I configure the Redis client manager dependency:</p>

<div><script src='https://gist.github.com/1721753.js?file=Ninject.cs'></script>
<noscript><pre><code>kernel.Bind&lt;IRedisClientsManager&gt;()
      // BasicRedisClientManager 
      //     - use when the redis server and client are on the same host.
      // PooledRedisClientManager
      //     - use when the redis server and client are on different hosts.
      .To&lt;BasicRedisClientManager&gt;()
      .InSingletonScope()
      .WithConstructorArgument(&quot;readWriteHosts&quot;, new string[] { &quot;localhost:6379&quot; });</code></pre></noscript></div>


<h4>Windows Service</h4>

<p>Next I configure my Windows service to listen to events that my website will publish. In my example here, I am listening to an event called <code>User.ForgotPassword</code> that sends an email to a user when they forget their password.</p>

<div><script src='https://gist.github.com/1721753.js?file=EventService.cs'></script>
<noscript><pre><code>private void ProcessEvents() {

    using (var client = redisManager.GetClient()) {
        // incoming events are JSON, so deserialize each one to IDictionary&lt;&gt;.
        var events = client.GetTypedClient&lt;IDictionary&lt;string, object&gt;&gt;().Lists[&quot;urn:events&quot;];

        while (true) {
            // wait for next event, then convert it to an ExpandoObject;
            dynamic @event = events.BlockingDequeue(null).ToExpando();

            if (@event.Name == &quot;User.ForgotPassword&quot;)
                SendForgottenPasswordEmail(@event.Email);
        }
    }
}</code></pre></noscript></div>


<p>The most important line is <code>events.BlockingDequeue(TimeSpan? timeOut)</code>. Just like a normal queue it pops the first item off the event list. However, if there are no events in the list, the call will block until an event is available. That saves me from having the poll repeatedly for new events. And it also works well if I run multiple services to process events, allowing me to scale out.</p>

<h4>ASP.NET MVC site</h4>

<p>Finally I write an action method in my controller that will queue an event to Redis server and thus triggering the code my service above. There is nothing special about MVC here; using ASP.NET WebForms will work here as well.</p>

<div><script src='https://gist.github.com/1721753.js?file=UserController.cs'></script>
<noscript><pre><code>public class UserController : Controller {

    private IRedisClientManager redisManager;

    [HttpPost]
    public ActionResult ForgotPassword(string email) {
    
        using (var client = redisManager.GetClient()) {
            // each event is automatically serialized to JSON
            var events = client.GetTypedClient&lt;dynamic&gt;().Lists[&quot;urn:events&quot;];
            
            events.Enqueue(new
            {
                Name = &quot;User.ForgotPassword&quot;,
                Email = email
            });
        }   
    }
}</code></pre></noscript></div>


<h2>Final Thoughts</h2>

<p>Using Redis as a way to trigger events like this has been working quite well. It is extremely fast, efficient, and uses a very small footprint (~1.6MB of RAM with no events). It also gives me an easy way to scale out in the future as demand increases. I still need to design a way to handle exceptions during event processing, but that is a blog post for another time. :)</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[How to Build Your Own Home Phone Server]]></title>
    <link href="http://www.stevenkuhn.net/blog/2011/05/05/how-to-build-your-own-home-phone-server/"/>
    <updated>2011-05-05T11:17:00-05:00</updated>
    <id>http://www.stevenkuhn.net/blog/2011/05/05/how-to-build-your-own-home-phone-server</id>
    <content type="html"><![CDATA[<blockquote><p><strong>Using Asterisk in conjunction with Google Voice will help you dramatically reduce your landline phone bill</strong><br/><br/>Google Voice. Skype. VoIP-to-PSTN providers. SIP-to-SIP calls. All of these technologies and products allow you to make calls that are either free or much cheaper than on your landline. Wouldn&#8217;t it be great if you could escape the clutches of your Telco and connect your home phone to these services? A phone server like Asterisk can help you realize this dream.<br/><br/>Short for Private Branch Exchange, PBX is a telephone exchange that is often used by businesses or offices. If you work a 9-to-5, chances are that your phone system is PBX-based. The short definition is that it&#8217;s essentially a network of phones connected to a main public switched telephone network (PSTN) that functions in a similar manner to a data network. In fact, in many instances today, the voice network is actually a VoIP-based network operating over data lines.<br/><br/>There&#8217;s a cheap and fairly simple way that you can ditch Ma or Pa Bell. The trick entails using an old PC to set up your own PBX in your home, and then connecting this PBX to Google Voice.</p><footer><strong>Maximum PC</strong> <cite><a href='http://www.maximumpc.com/article/how-tos/how_build_your_own_home_phone_server'>How to Build Your Own Home Phone Server</a></cite></footer></blockquote>


<p>This article has really sparked my interest in using Asterisk with Google Voice. I have a Nexus One phone that integrates fantastically with it, although reception is questionable at times inside my apartment. This certainly could be the solution I need for a quality landline in my apartment without requiring a separate provider/phone number.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[ASP.NET Deployment Needs To Be Fixed]]></title>
    <link href="http://www.stevenkuhn.net/blog/2011/04/06/asp-dot-net-deployment-needs-to-be-fixed/"/>
    <updated>2011-04-06T16:18:00-05:00</updated>
    <id>http://www.stevenkuhn.net/blog/2011/04/06/asp-dot-net-deployment-needs-to-be-fixed</id>
    <content type="html"><![CDATA[<blockquote><p>I deploy Tekpub, on average, 3-5 times a week. This used to scare me every single time I did it - for various reasons: no rollbacks, I&#8217;d overwrite some of Avery&#8217;s changes, I&#8217;d forget something. Imma go ahead and say it: ASP.NET Deployment is a joke.</p><footer><strong>WekeRoad</strong> <cite><a href='http://wekeroad.tumblr.com/post/4373719917/asp-net-deployment-needs-to-be-fixed'>ASP.NET Deployment Needs to Be Fixed</a></cite></footer></blockquote>


<p>I agree with Rob that the state of deployment for ASP.NET applications is lacking. Issues arising from deployment is something that the team I work with continually have to deal with. It seems that the build and deployment tools that Microsoft provides are so complex that it requires a dedicated person solely responsible for managing them. When we moved to Team Foundation Server 2010 we wanted to incorporate deployment as part of the build process. However, trying to adapt Windows Workflow to a custom build process is an absolute nightmare. I&#8217;m not saying having an automated build and deployment process is trivial, but it doesn&#8217;t need to be that complex.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Disposing a WCF Proxy Using an Extension Method]]></title>
    <link href="http://www.stevenkuhn.net/blog/2009/07/02/disposing-a-wcf-proxy-using-an-extension-method/"/>
    <updated>2009-07-02T10:00:00-05:00</updated>
    <id>http://www.stevenkuhn.net/blog/2009/07/02/disposing-a-wcf-proxy-using-an-extension-method</id>
    <content type="html"><![CDATA[<p>A while back I read a <a href="http://www.danrigsby.com/blog/index.php/2008/02/26/dont-wrap-wcf-service-hosts-or-clients-in-a-using-statement/">blog post by Dan Rigsby</a> about why you should not use C# <code>using</code> statements on a WCF service proxy class even though it implements IDisposable. Basically it comes down to the <code>Dispose()</code> method calls <code>Close()</code> which can throw an exception preventing the service proxy from being disposed properly. The solution by Dan Rigsby involving a wrapper class and <a href="http://bloggingabout.net/blogs/erwyn/archive/2006/12/09/WCF-Service-Proxy-Helper.aspx">another solution by Erwyn van der Meer</a> (which provides a helper class that you can derive from) both allow you to use the <code>using</code> statement and still properly dispose of the proxy.</p>

<p>I wrote an extension method below will dispose a service proxy properly, but it doesn&#8217;t require you to change that proxy in any way. By providing an extension method around ICommunicationObject, any WCF class that dervives from it (ClientBase, ServiceHostBase, etc.) will have this method available as well.</p>

<div><script src='https://gist.github.com/1655793.js?file=ICommunicationObjectExtensions.cs'></script>
<noscript><pre><code>public static class ICommunicationObjectExtensions
{
   public static void TryCloseOrAbort(this ICommunicationObject obj)
   {
      if (obj != null)
      {
         if (obj.State != CommunicationState.Faulted &amp;&amp;
             obj.State != CommunicationState.Closed)
         {
            try { obj.Close(); }
            catch (CommunicationObjectFaultedException)
            { obj.Abort(); }
            catch (TimeoutException)
            { obj.Abort(); }
            catch (Exception)
            {
               obj.Abort();
               throw;
            }
         }
         else
            obj.Abort();
      }
   }
}</code></pre></noscript></div>


<p>With that method in place, all you you have to do is call <code>TryCloseOrAbort()</code> in a <code>try-finally</code> block to make sure it is called even if an exception is thrown.</p>

<div><script src='https://gist.github.com/1655793.js?file=Usage.cs'></script>
<noscript><pre><code>// Example usage:
//      assume MyServiceClient is a WCF service proxy class
var client = new MyServiceClient();

try { client.MyServiceMethod(); }
finally { client.TryCloseOrAbort(); }</code></pre></noscript></div>

]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Extension Method to Sort ListItems in a ListControl in ASP.NET]]></title>
    <link href="http://www.stevenkuhn.net/blog/2008/08/27/extension-method-to-sort-listitems-in-a-listcontrol-in-asp-dot-net/"/>
    <updated>2008-08-27T10:00:00-05:00</updated>
    <id>http://www.stevenkuhn.net/blog/2008/08/27/extension-method-to-sort-listitems-in-a-listcontrol-in-asp-dot-net</id>
    <content type="html"><![CDATA[<p>Yesterday I needed a way to sort the items in a ListControl (in this case, a DropDownList) after the list had been populated. The reason for that is after I databound my DropDownList from a collection of items, I inserted a few more ListItems depending on certain circumstances. Instead of trying to hack some method of inserting those items in my original collection, I wanted a more elegant solution. After I came across a post on Google I came up with a solution using an extension method and LINQ:</p>

<div><script src='https://gist.github.com/1655779.js'></script>
<noscript><pre><code></code></pre></noscript></div>


<p>I wanted a simple solution so I didn&#8217;t do any performance metrics on it. Things I might change is add ability to sort by ListItem.Value, add the ability to change the sort direction, or perhaps sort by a custom comparer. So if you want a way to sort a ListItemCollection, give this a try and let me know what you think! :)</p>

<p><strong>Update (July 16, 2009)</strong>
The post that I found <a href="http://coercedcode.blogspot.com/2007/08/sorting-listitem-collections-in-aspnet.html">http://coercedcode.blogspot.com/2007/08/sorting-listitem-collections-in-aspnet.html</a> no longer works. If I find it, I&#8217;ll update this post.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[An error was discovered processing the &lt;Security&gt; header]]></title>
    <link href="http://www.stevenkuhn.net/blog/2008/08/04/an-error-was-discovered-processing-the-security-header/"/>
    <updated>2008-08-04T10:00:00-05:00</updated>
    <id>http://www.stevenkuhn.net/blog/2008/08/04/an-error-was-discovered-processing-the-security-header</id>
    <content type="html"><![CDATA[<p>A coworker and I were troubleshooting an issue we were having concerning a .NET call to a webservice that used WSE Security. Our client derived from <code>Microsoft.Web.Services2.WebServicesClientProtocol</code> and every time we tried to call the webservice this error would appear:</p>

<blockquote><p>An error was discovered processing the &lt;Security&gt; header</p></blockquote>

<p>A quick search on Google returned a <a href="http://forums.asp.net/p/966958/1838192.aspx">quick, easy solution</a>: verify that client and server have their <em>system time in synch</em> (a 5 minute window is allowed). Once the server time (about 6 minutes apart) was fixed the issue immediately disappeared.</p>
]]></content>
  </entry>
  
</feed>
