<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
  <title>SeeSharp Software</title>
  
  <subtitle>SeeSharp Software Website</subtitle>
  <link href="http://www.seesharpsoftware.com.au/atom.xml" rel="self"/>
  
  <link href="http://www.seesharpsoftware.com.au/"/>
  <updated>2022-05-02T02:20:14.678Z</updated>
  <id>http://www.seesharpsoftware.com.au/</id>
  
  <author>
    <name>Hadi Eskandari</name>
    
  </author>
  
  <generator uri="https://hexo.io/">Hexo</generator>
  
  <entry>
    <title>Staggered-batch message processing</title>
    <link href="http://www.seesharpsoftware.com.au/2022-04-01-staggered-batch-processing-using-messaging/"/>
    <id>http://www.seesharpsoftware.com.au/2022-04-01-staggered-batch-processing-using-messaging/</id>
    <published>2022-04-01T08:15:00.000Z</published>
    <updated>2022-05-02T02:20:14.678Z</updated>
    
    <content type="html"><![CDATA[<h1 id="The-problem"><a href="#The-problem" class="headerlink" title="The problem"></a>The problem</h1><p>When using messaging, in some scenarios many messages are generated as a result of an incoming message to process the initial request. Normally a <a href="https://en.wikipedia.org/wiki/Fan-out_(software)">fan-out pattern</a> or <a href="https://medium.com/event-driven-utopia/competing-consumers-pattern-explained-b338d54eff2b">competing-consumers</a> can ensure these messages are processed inline with the designated SLA as we can scale out the processing side of it, but the queuing nature of messaging is also an important factor to remember.</p><p>Imagine an incoming request to process a batch of work like image processing, or text file cleaning, or downloading web pages from the internet. The initial incoming request could generate thousands of messages to deal with the request (e.g. a message per work item). Meanwhile a second message comes in and similarly generates thousands of related messages to deal with its work items. The work items for the second message will queue behind the first request’s messages and this could delay the processing for the second request beyond its SLA. This design is also wasteful when you consider cancellation scenarios. When the initial request is cancelled, you will still need to churn through all the generated messages that are in the queue, even though there is nothing to do. Can we do any better?</p><h1 id="What-is-staggered-batch-processing"><a href="#What-is-staggered-batch-processing" class="headerlink" title="What is staggered-batch processing"></a>What is staggered-batch processing</h1><p>An alternative approach is to not generate all the messages upfront and generate them in batches. We’ll need some sort of a persistence to remember how many of the messages are generated, and generate a new batch once a batch is fully processed. By not generating all the messages upfront, we’re not congesting the queue and in case of cancellations we simply stop generating more messages.</p><blockquote><p>Here ‘batch’ synonymous to a group of messages generated to handle the work process.</p></blockquote><p>While generally you can do this with vanilla messaging and a database, you will need to take consistencies between message queue and database and deal with concurrency issues. What happens when two messages try to update the database at the same time? These are already done by Saga abstractions for you, so you can focus on the business code, like in this case, batching the request and processing them. Let’s see how this can be done using NServiceBus saga implementations.</p><p>The saga to generate and track work orders has main events:</p><ul><li>Start a new instance when a work request comes in. At this point, we also start importing the first batch. (StartProcessing)</li><li>Wait for acknowledgement of a batch being imported and import the next batch (WorkOrderCompleted)</li><li>Finish up when all batches are imported and terminate (WorkAllDone)</li></ul><p>When importing the next batch, either all work requests are already generated (no more batches to generate) or we need to generate the next one. </p><figure class="highlight csharp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">async</span> Task <span class="title">ImportNextBatch</span>(<span class="params">IMessageHandlerContext context</span>)</span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (Data.Progress.AllWorkCompleted(Data.WorkCount))</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">await</span> FinishWork(context);</span><br><span class="line">    &#125; </span><br><span class="line">    <span class="keyword">else</span> <span class="keyword">if</span> (Data.Progress.HasRemainingWork(Data.WorkCount))</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">await</span> SendWorkRequest(MakeNextBatch(), context);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>The saga <code>Data</code> access allows concurrent and thread safe access to the progress information. The concurrency checks built into the saga means the Data is never updated by two concurrently running messages at the same time. This is all transparent to the users’ code.</p><p>The messages to process the work order (ProcessWorkOrder) is sent to a different queue, so it can be scaled out as it makes sense. The processing time of the messages can be monitored so that the number of consumers can be adjusted accordingly.</p><p>The output of this process is that the messages are generated in batches (here a batch consists of 100 messages):</p><figure class="highlight cmd"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">Starting the process <span class="keyword">for</span> &#x27;<span class="number">987</span>&#x27; work orders.</span><br><span class="line">Queueing next batch of work orders: (<span class="number">1</span> - <span class="number">100</span>).</span><br><span class="line">Importing the next batch of work.</span><br><span class="line">Queueing next batch of work orders: (<span class="number">101</span> - <span class="number">200</span>).</span><br><span class="line">...</span><br><span class="line">Importing the next batch of work.</span><br><span class="line">Queueing next batch of work orders: (<span class="number">901</span> - <span class="number">987</span>).</span><br><span class="line">All done.</span><br></pre></td></tr></table></figure><h1 id="Caveats"><a href="#Caveats" class="headerlink" title="Caveats"></a>Caveats</h1><p>This process halts when a message errors out on the processing side, as the subsequent batches are no longer generated and processed. This may be desired in certain scenarios where the work as a whole makes sense (failing a request can fail the whole work), but if partial processing is acceptable this will need to change. There are a few strategies to handle this:</p><ul><li><p>The generation of the messages can be done via a time out. This will stagger the generation side so that the processing side can handle the messages as they come in.</p></li><li><p>More elaborate work tracking can be designed so that errors from processing side are also reported. The errored tasks can be retried/discarded as appropriate.</p></li></ul><h2 id="Summary"><a href="#Summary" class="headerlink" title="Summary"></a>Summary</h2><p>The thread and concurrent safe programing model of Sagas allows easier redesigning of fan-out message processes in a way that is more efficient and results in better overall SLAs. The sample code can be found on <a href="https://github.com/HEskandari/NSBBatchingSample">my github repository</a>.</p>]]></content>
    
    
    <summary type="html">When using messaging, in some scenarios many messages are generated as a result of an incoming message to process the initial request. The initial incoming request could generate thousands of messages to deal with the request. This approach has a number of problems and inefficiencies associated with it. Can we do any better?</summary>
    
    
    
    
    <category term="nservicebus" scheme="http://www.seesharpsoftware.com.au/tags/nservicebus/"/>
    
    <category term="nsb" scheme="http://www.seesharpsoftware.com.au/tags/nsb/"/>
    
    <category term="fanout" scheme="http://www.seesharpsoftware.com.au/tags/fanout/"/>
    
    <category term="sagas" scheme="http://www.seesharpsoftware.com.au/tags/sagas/"/>
    
    <category term="patterns" scheme="http://www.seesharpsoftware.com.au/tags/patterns/"/>
    
    <category term="messaging" scheme="http://www.seesharpsoftware.com.au/tags/messaging/"/>
    
  </entry>
  
  <entry>
    <title>Persian calendar library, now in Go</title>
    <link href="http://www.seesharpsoftware.com.au/2022-02-06-Farsi-Library-Now-In-Golang/"/>
    <id>http://www.seesharpsoftware.com.au/2022-02-06-Farsi-Library-Now-In-Golang/</id>
    <published>2022-02-05T23:21:54.000Z</published>
    <updated>2022-02-07T09:26:11.882Z</updated>
    
    <content type="html"><![CDATA[<h1 id="Looking-in-the-rearview-mirror"><a href="#Looking-in-the-rearview-mirror" class="headerlink" title="Looking in the rearview mirror"></a>Looking in the rearview mirror</h1><p>Back in 2005, I released a set controls and date libraries to work with dates, in particular <a href="https://en.wikipedia.org/wiki/Solar_Hijri_calendar">Solar Hijri Calendar</a> (a.k.a Persian calendar). </p><p>To quote from Wikipedia: </p><blockquote><p>The Solar Hijri calendar is one of the oldest calendars in the world, as well as the most accurate solar calendar in use today.</p></blockquote><p>The calendar is in use in many countries such as Iran, Afghanistan, Tajikstan (with minor differences in month names).</p><p>The library called FarsiLibrary and was originally built on top of .NET Framework 1.1 and then ported to .NET Framework 2.0, which lacked official solar hijro calendar support. The library was <em>published</em> as an article on <a href="https://www.codeproject.com/Articles/13664/Farsi-Library-Working-with-Dates-Calendars-and-Dat">CodeProject</a> and was a great hit. The Right-To-Left controls were not a common place and the lack of calendar and date calculation was an impediment to multi-cultural business application. In late 2006/early 2007 WPF was the new cool kid around the block, so as a way to learn, I ported my controls over and subsequently published a new set of controls. This was published as another <a href="https://www.codeproject.com/Articles/20232/Farsi-Library-FX">article</a> on Code Project.</p><p>Throughout this process, one thing was a common denominator: I leared a lot as I was working on it.</p><p>Now, after more than a decade, I have re-written the library, this time in GoLang as a way to help brush up on my Go. The first initial version can be found on my Github repository and will be officially in the following weeks. </p><h1 id="Date-Functions"><a href="#Date-Functions" class="headerlink" title="Date Functions"></a>Date Functions</h1><p>Two way date conversions are now possible, using <code>time.Time</code> and <code>PersianDate</code> structs:</p><figure class="highlight golang"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> (</span><br><span class="line">    <span class="string">&quot;github.com/heskandari/farsilibrary.go/date&quot;</span></span><br><span class="line">    <span class="string">&quot;time&quot;</span></span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">Test</span><span class="params">()</span></span> &#123; </span><br><span class="line"></span><br><span class="line">    <span class="comment">// convert time.Now</span></span><br><span class="line">    pd := date.ToPersianDate(time.Now())</span><br><span class="line"></span><br><span class="line">    <span class="comment">// create directly</span></span><br><span class="line">    pd2, err := date.NewPersianDate(<span class="number">1387</span>, <span class="number">7</span>, <span class="number">7</span>) <span class="comment">//7 Mehr 1387</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">// same as above, but with parsed strings </span></span><br><span class="line">    pd3, err := date.Parse(<span class="string">&quot;1387/7/7&quot;</span>) </span><br><span class="line"></span><br><span class="line">    <span class="comment">// convert back</span></span><br><span class="line">    gd := date.ToGregorianDate(pd)  <span class="comment">// returns a time.Time instance</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>The <code>PersianDate</code> struct implements Stringer interface as well as json marshal/unmarshal interfaces, so you can use it accordingly:</p><figure class="highlight golang"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">Serialize</span><span class="params">()</span></span> &#123;</span><br><span class="line">    dob, _ := date.NewPersianDate(<span class="number">1400</span>, <span class="number">01</span>, <span class="number">01</span>)</span><br><span class="line">    p := Person&#123;</span><br><span class="line">        Name: <span class="string">&quot;John&quot;</span>,</span><br><span class="line">        DoB:  &amp;dob,</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    js, _ := json.Marshal(&amp;p) <span class="comment">// output is &#123;&quot;Name&quot;: &quot;John&quot;, &quot;DoB&quot;: &quot;1400-01-01&quot;&#125;</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><h1 id="Formatting"><a href="#Formatting" class="headerlink" title="Formatting"></a>Formatting</h1><p>Other formatting functions are also available throught the <code>Format()</code> function.</p><figure class="highlight golang"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">pd, err := date.Parse(<span class="string">&quot;1388/02/30&quot;</span>)</span><br><span class="line">pd.Format(date.GenericFormat) <span class="comment">// returns &quot;۱۳۸۸/۰۲/۰۳&quot;</span></span><br><span class="line">pd.Format(date.MonthYearFormat) <span class="comment">// returns &quot;اردیبهشت ۱۳۸۸&quot;</span></span><br><span class="line">pd.Format(date.MonthDayFormat) <span class="comment">// returns &quot;۳ اردیبهشت&quot;</span></span><br><span class="line">pd.Format(date.GenericShortFormat) <span class="comment">// returns &quot;۱۳۸۸/۲/۳&quot;</span></span><br><span class="line">pd.Format(date.WrittenFormat) <span class="comment">// returns &quot;پنجشنبه ۳ اردیبهشت ۱۳۸۸&quot;</span></span><br></pre></td></tr></table></figure><p>Note that these string use the persian numerals. Other formats also exist that return arabic numerals:</p><figure class="highlight golang"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">pd.Format(<span class="string">&quot;S&quot;</span>) <span class="comment">// returns serializable format &quot;1388-02-03&quot;</span></span><br><span class="line">pd.Format(<span class="string">&quot;&quot;</span>) <span class="comment">// returns &quot;1388/02/03&quot;</span></span><br><span class="line">pd.String() <span class="comment">// returns &quot;1388/02/03&quot;</span></span><br></pre></td></tr></table></figure><h1 id="Summary"><a href="#Summary" class="headerlink" title="Summary"></a>Summary</h1><p>The Go version of the FarsiLibrary is here! It is built on the trusted and matured .NET version of the library. Feel free to drop a comment if you have any comments/feedbacks.</p>]]></content>
    
    
    <summary type="html">After more than a decade, I have re-written the FarsiLibrary, this time in GoLang as a way to help brush up on my Go skills. The first initial version can be found on my Github repository.</summary>
    
    
    
    
    <category term="go" scheme="http://www.seesharpsoftware.com.au/tags/go/"/>
    
    <category term="golang" scheme="http://www.seesharpsoftware.com.au/tags/golang/"/>
    
    <category term="farsilibrary" scheme="http://www.seesharpsoftware.com.au/tags/farsilibrary/"/>
    
  </entry>
  
  <entry>
    <title>ASP.NET Core action parameter matching</title>
    <link href="http://www.seesharpsoftware.com.au/2020-10-26-ASPNET-Core-Action-Matching/"/>
    <id>http://www.seesharpsoftware.com.au/2020-10-26-ASPNET-Core-Action-Matching/</id>
    <published>2020-10-26T00:49:00.000Z</published>
    <updated>2022-02-07T01:05:27.059Z</updated>
    
    <content type="html"><![CDATA[<p>When porting an old .NET MVC/API application to ASP .NET Core application things might not be as straightforward as you’d expect. A personal application that I was porting tumbled and even the most basic scenario wouldn’t work the way I expected (or the way the old .NET MVC used to work). This was nowhere on the massive Microsoft documentation website either. Read on, as I have figured out what was happening.<a id="more"></a></p><p>Let me tell you what the problem was to begin with.</p><p>The controller has two actions with two different method names. Both of the methods accept a boolean (with different names). The caller would pass the parameter name and the value of the parameter. The controller code would look like this:</p><figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">[<span class="meta">ApiController</span>]</span><br><span class="line">[<span class="meta">Route(<span class="meta-string">&quot;[controller]&quot;</span>)</span>]</span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">MyController</span> : <span class="title">ControllerBase</span></span><br><span class="line">&#123;</span><br><span class="line">    [<span class="meta">HttpPost</span>]</span><br><span class="line">    <span class="function"><span class="keyword">public</span> ActionResult <span class="title">DoSomething</span>(<span class="params"><span class="built_in">bool</span> real</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        <span class="keyword">return</span> Content(<span class="string">&quot;Something Done&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">        </span><br><span class="line">    [<span class="meta">HttpPost</span>]</span><br><span class="line">    <span class="function"><span class="keyword">public</span> ActionResult <span class="title">DoSomethingElse</span>(<span class="params"><span class="built_in">bool</span> unreal</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        <span class="keyword">return</span> Content(<span class="string">&quot;Something else done&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>And the caller would invoke the endpoints like <code>/my?real=true</code> or <code>/my?unreal=true</code>. While this code works fine in the old asp.net WebAPI, this would not work in the new asp.net core application.</p><h2 id="But-why-There-is-a-history…"><a href="#But-why-There-is-a-history…" class="headerlink" title="But why? There is a history…"></a>But why? There is a history…</h2><p>So although this was working in my case (asp.net mvc/api) as I was using <code>ApiController</code> class, if you used the other <code>Controller</code> class it would not work. Why the descrepancy? I don’t know for sure, but probably because MVC and WebAPI was developed by two different teams and had different timelines and design decisions. </p><p>The design for ApiController pipeline was that it would match the action parameter names against the Query String parameters. The Controller class does not, which means you have to make it non-ambiguous (e.g. have one action per HTTP verb in a controller).  </p><p>Okay, so it worked in <code>ApiController</code>, so why is it not working in ASP.NET Core? In the .NET Core, they merged the two frameworks into one (yay) but they had to make a decision as to which model they wanted to support and they went the MVC controller model (boo). </p><p>When you try to read the controller via <code>my?real=true</code>, you get the following exception:</p><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">AmbiguousActionException: Multiple actions matched. The following actions matched route data and had all constraints satisfied:</span><br><span class="line"></span><br><span class="line">Controllers.MyController.DoSomething</span><br><span class="line">Controllers.MyController.DoSomethingElse</span><br></pre></td></tr></table></figure><h2 id="The-Fix"><a href="#The-Fix" class="headerlink" title="The Fix"></a>The Fix</h2><p>The error message should be clear: you need to make your actions less ambiguous. A way to make it less-ambiguous is to map the parameters to querystring parameters (like how the old ApiController did).</p><p>The solution would be to create a new attribute for your actions and inherit from <code>ActionMethodSelectorAttribute</code> so that it gets invoke when the request comes in and you get a say if the action is a right match for the incoming request. The attribute would look like this:</p><figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">[<span class="meta">AttributeUsage(AttributeTargets.Method, AllowMultiple = true)</span>]</span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">MapToQueryStingAttribute</span> : <span class="title">ActionMethodSelectorAttribute</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="built_in">string</span> QueryStingName &#123; <span class="keyword">get</span>; <span class="keyword">set</span>; &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">MapToQueryStingAttribute</span>(<span class="params"><span class="built_in">string</span> qname</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        QueryStingName = qname;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">override</span> <span class="built_in">bool</span> <span class="title">IsValidForRequest</span>(<span class="params">RouteContext routeContext, ActionDescriptor action</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        StringValues <span class="keyword">value</span>;</span><br><span class="line"></span><br><span class="line">        routeContext.HttpContext.Request.Query.TryGetValue(QueryStingName, <span class="keyword">out</span> <span class="keyword">value</span>);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> !StringValues.IsNullOrEmpty(<span class="keyword">value</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>and now you can decorate your actions like so.</p><figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">[<span class="meta">HttpPost</span>]</span><br><span class="line">[<span class="meta">MapToQuerySting(<span class="meta-string">&quot;real&quot;</span>)</span>]</span><br><span class="line"><span class="function"><span class="keyword">public</span> ActionResult <span class="title">DoSomething</span>(<span class="params"><span class="built_in">bool</span> real</span>)</span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">return</span> Content(<span class="string">&quot;Something Done&quot;</span>);</span><br><span class="line">&#125;</span><br><span class="line">    </span><br><span class="line">[<span class="meta">HttpPost</span>]</span><br><span class="line">[<span class="meta">MapToQuerySting(<span class="meta-string">&quot;unreal&quot;</span>)</span>]</span><br><span class="line"><span class="function"><span class="keyword">public</span> ActionResult <span class="title">DoSomethingElse</span>(<span class="params"><span class="built_in">bool</span> unreal</span>)</span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">return</span> Content(<span class="string">&quot;Something else done&quot;</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>What we say here is that if the query string has that variable name (e.g. ‘real’ or ‘unreal’) match it against the action. Now is depending on your actions and the complexity (e.g. how many actions you have, if you have overloads that could cause overlaps and further ambiguity) this may not be enough. So you may need to further enhance the attribute to say: if the incoming request has this variable but doesn’t have that variable, then map it. In those cases you can use this version of the attribute:</p><figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="built_in">string</span> QueryStingName &#123; <span class="keyword">get</span>; <span class="keyword">set</span>; &#125;</span><br><span class="line"><span class="keyword">public</span> <span class="built_in">bool</span> ShouldInclude &#123; <span class="keyword">get</span>; <span class="keyword">set</span>; &#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">MapToQueryStingAttribute</span>(<span class="params"><span class="built_in">string</span> qname, <span class="built_in">bool</span> shouldInclude=<span class="literal">true</span></span>)</span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    QueryStingName = qname;</span><br><span class="line">    ShouldInclude = shouldInclude;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">override</span> <span class="built_in">bool</span> <span class="title">IsValidForRequest</span>(<span class="params">RouteContext routeContext, ActionDescriptor action</span>)</span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    StringValues <span class="keyword">value</span>;</span><br><span class="line"></span><br><span class="line">    routeContext.HttpContext.Request.Query.TryGetValue(QueryStingName, <span class="keyword">out</span> <span class="keyword">value</span>);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (ShouldInclude)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">return</span> !StringValues.IsNullOrEmpty(<span class="keyword">value</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> StringValues.IsNullOrEmpty(<span class="keyword">value</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>and now you can say mix the attribute to say the request should include and should not include what parameters.</p><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">[HttpGet]</span><br><span class="line">[MapToQuerySting(&quot;real&quot;)]</span><br><span class="line">[MapToQuerySting(&quot;unreal&quot;, ShouldInclude &#x3D; false)]</span><br><span class="line">public ActionResult DoSomething(bool real)</span><br><span class="line">&#123;</span><br><span class="line">    return Content(&quot;Something Done&quot;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>Happy porting!</p>]]></content>
    
    
    <summary type="html">&lt;p&gt;When porting an old .NET MVC/API application to ASP .NET Core application things might not be as straightforward as you’d expect. A personal application that I was porting tumbled and even the most basic scenario wouldn’t work the way I expected (or the way the old .NET MVC used to work). This was nowhere on the massive Microsoft documentation website either. Read on, as I have figured out what was happening.</summary>
    
    
    
    
    <category term="aspnet" scheme="http://www.seesharpsoftware.com.au/tags/aspnet/"/>
    
    <category term=".NET Core" scheme="http://www.seesharpsoftware.com.au/tags/NET-Core/"/>
    
    <category term="dotnet" scheme="http://www.seesharpsoftware.com.au/tags/dotnet/"/>
    
  </entry>
  
  <entry>
    <title>Distributed Logging with NServiceBus</title>
    <link href="http://www.seesharpsoftware.com.au/distributed-logging-with-nservicebus/"/>
    <id>http://www.seesharpsoftware.com.au/distributed-logging-with-nservicebus/</id>
    <published>2020-06-28T06:59:42.000Z</published>
    <updated>2022-05-02T03:58:25.468Z</updated>
    
    <content type="html"><![CDATA[<p>I recently had an interaction with an NServiceBus customer and noticed that they are pushing the log of their import process all the way to the UI. While this may be normal in some cases, but why do you put all the technical details, including exceptions, stack trace, in case of errors in that customer facing log window? The answer was: it is hard for us to gather all the relevant information from a distributed process that’s running in a handful of microservices. When something goes wrong, it is hard for us to gather all the relevant information. </p><p>It all boiled down to this: while each individual service capture all the detail of a successfull and failed job, the logs go into individual log files on those services. It is hard to connect these logs across different services. In a nutshell, distributed logging is hard. But does it have to be?<a id="more"></a></p><p>Let’s see how you can get a view of a distributed process by using a structured logging framework. In this example I’m using NServiceBus, Serilog and Seq.</p><h2 id="Using-Log-Context"><a href="#Using-Log-Context" class="headerlink" title="Using Log Context"></a>Using Log Context</h2><p>To understand the ‘context’ (pun intended) of a production error, you’re going to need a lot more information that just the exception and the stack trace. Imagine the error being thrown in a multi-tenant web application. Which customer request is causing this error? What are the request/header information for that header? </p><p>Typically the code that logs the message, would look something like this:</p><figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">static</span> ILog log = LogManager.GetLogger&lt;SubmitOrderHandler&gt;();</span><br><span class="line">...</span><br><span class="line">log.Info(<span class="string">$&quot;Received an order #<span class="subst">&#123;message.OrderNumber&#125;</span> for [<span class="subst">&#123;<span class="built_in">string</span>.Join(<span class="string">&quot;, &quot;</span>, message.ProductIds)&#125;</span>] products(s).&quot;</span>);</span><br></pre></td></tr></table></figure><p>And the output would look something like this:</p><p>Even if you use a logging server like Seq, it is still hard to understand which logs are related to the same workflow. </p><p><img src="/images/BlogPics/StructuredLogging-01.png" alt="Structured Logging"></p><p>But surely, we can do better. </p><h2 id="Connecting-your-messages"><a href="#Connecting-your-messages" class="headerlink" title="Connecting your messages"></a>Connecting your messages</h2><p>To connect your workflow, you need to choose an identifier that would connect all messages in your workflow. With the identifier flowing through your services you can later connect your log entries using a LogContext. Usually things like an Order ID, JobID and identifiers like that can be picked but it depends on your code.</p><p>With Serilog, the code that’d use the <code>OrderNumber</code> as the added context would look like this:</p><figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">using</span> (LogContext.PushProperty(<span class="keyword">nameof</span>(message.OrderNumber), message.OrderNumber))</span><br><span class="line">&#123;</span><br><span class="line">    log.Info(<span class="string">$&quot;Received an order #<span class="subst">&#123;message.OrderNumber&#125;</span> for [<span class="subst">&#123;<span class="built_in">string</span>.Join(<span class="string">&quot;, &quot;</span>, message.ProductIds)&#125;</span>] products(s).&quot;</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>We can immediately see the benefit. In Seq, now you can filter for a specific <code>OrderNumber</code> and see all the logs across the services related to that order number.</p><p><img src="/images/BlogPics/StructuredLogging-02.png" alt="Filtering Logs in Seq"></p><h2 id="Using-Enrichers"><a href="#Using-Enrichers" class="headerlink" title="Using Enrichers"></a>Using Enrichers</h2><p>Serilog supports ‘Enrichers’ which are independent modules of code adding context to the logs, similar to LogContexts. </p><p>Instead of the previous code-snipper, you can encapsulate that in an Enricher. With a bit of an extension method, you can tie that in to your NServiceBus message handler:</p><figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">Enrich</span>(<span class="params">LogEvent logEvent, ILogEventPropertyFactory propertyFactory</span>)</span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (msg <span class="keyword">is</span> IHaveCustomerInfo customerMsg)</span><br><span class="line">    &#123;</span><br><span class="line">        AddProperty(logEvent, propertyFactory, <span class="keyword">nameof</span>(customerMsg.ClientId), customerMsg.ClientId);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (msg <span class="keyword">is</span> IHaveOrderNumber orderMsg)</span><br><span class="line">    &#123;</span><br><span class="line">        AddProperty(logEvent, propertyFactory, <span class="keyword">nameof</span>(orderMsg.OrderNumber), orderMsg.OrderNumber);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>and the your message handler can now do this: </p><figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> logger = context.GetOrderWorkflowLogger(message);</span><br><span class="line">logger.Information(<span class="string">&quot;Received an order &#123;OrderNumber&#125; for &#123;ProductIds&#125; products(s).&quot;</span>, message.OrderNumber, message.ProductIds);     </span><br></pre></td></tr></table></figure><h2 id="Going-beyond-logging"><a href="#Going-beyond-logging" class="headerlink" title="Going beyond logging"></a>Going beyond logging</h2><p>Did you notice anything extra on the last screenshot? </p><p>If you don’t know, NServiceBus supports the concept of ‘ConversationID’ which has a similar purposes: connecting all messages in the same workflow. The way it works is that the first message being sent gets a new ConversationID and the subsequent messages sent in the (handler) context of that message automatically will get the same ID. This way you can identify a group of messages belong to the workflow. </p><p>When using Serilog in your NServiceBus endpoints, you should get a reference to the logger via the <code>IMessageHandlerContext</code> object. That way, all that information will also get logged which would be very useful for production use.</p><p>The library that does this for you out of the box is <code>NServiceBus.Serilog</code>. If you want to use NServiceBus and Serilog combination, you have to <a href="https://github.com/NServiceBusExtensions/NServiceBus.Serilog">give it a try</a>.</p><p><img src="/images/BlogPics/StructuredLogging-03.png" alt="Handler Context"></p><p>In fact, the conversation information is used in ServiceInsight to visualize the messages. If you are a NServiceBus platform, ServiceInsight can be used to visualize messages in a conversation.</p><p><img src="/images/BlogPics/StructuredLogging-04.png" alt="Sequence Diagram"></p><h2 id="In-closing"><a href="#In-closing" class="headerlink" title="In closing"></a>In closing</h2><p>If you are interesting in reading about distributed systems logging, <a href="https://jimmybogard.com/">Jimmy Bogard</a> has an exellent <a href="https://jimmybogard.com/building-end-to-end-diagnostics-visualizations-with-exporters/">series of posts</a> that covers a lot more.</p><p>I have used the NServiceBus showcase codebase for this post but I have somewhat modified it to use Serilog. You can find the modified code on <a href="https://github.com/HEskandari/NServiceBus.Showcase">this repository</a>.</p>]]></content>
    
    
    <summary type="html">&lt;p&gt;I recently had an interaction with an NServiceBus customer and noticed that they are pushing the log of their import process all the way to the UI. While this may be normal in some cases, but why do you put all the technical details, including exceptions, stack trace, in case of errors in that customer facing log window? The answer was: it is hard for us to gather all the relevant information from a distributed process that’s running in a handful of microservices. When something goes wrong, it is hard for us to gather all the relevant information. &lt;/p&gt;
&lt;p&gt;It all boiled down to this: while each individual service capture all the detail of a successfull and failed job, the logs go into individual log files on those services. It is hard to connect these logs across different services. In a nutshell, distributed logging is hard. But does it have to be?</summary>
    
    
    
    
    <category term="NServiceBus" scheme="http://www.seesharpsoftware.com.au/tags/NServiceBus/"/>
    
    <category term="SeriLog" scheme="http://www.seesharpsoftware.com.au/tags/SeriLog/"/>
    
    <category term="Seq" scheme="http://www.seesharpsoftware.com.au/tags/Seq/"/>
    
    <category term="Structured Logging" scheme="http://www.seesharpsoftware.com.au/tags/Structured-Logging/"/>
    
  </entry>
  
  <entry>
    <title>NServiceBus integration with Aspnet Core</title>
    <link href="http://www.seesharpsoftware.com.au/2019-12-12-NServiceBus-Aspnet-Core-Integration/"/>
    <id>http://www.seesharpsoftware.com.au/2019-12-12-NServiceBus-Aspnet-Core-Integration/</id>
    <published>2019-12-12T09:42:16.000Z</published>
    <updated>2022-05-02T04:00:59.663Z</updated>
    
    <content type="html"><![CDATA[<p>With .NET Core now becoming mainstream, you might ask how you can run NServiceBus endpoints in an asp.net process. After all, it sounds pretty trivial, but turns out maybe not as easy as it sounds. Let’s see why.<a id="more"></a></p><p><img src="/images/BlogPics/integration.jpg" alt="Integration"></p><h2 id="Running-On-Startup"><a href="#Running-On-Startup" class="headerlink" title="Running On Startup"></a>Running On Startup</h2><p>The code to start the endpoint would typically have two steps. The first step is to setup the endpoint using ‘EndpoingConfiguration’ object and the second step is to create, or potentially ‘start’ an endpoint. In NSB v6 and higher, the create and start are both an async method. Initialization of the endpoint during the startup of the WebHost / Generic Host would look like this:</p><figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">Startup</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">ConfigureServices</span>(<span class="params">IServiceCollection services</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        services.AddOptions();</span><br><span class="line">        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);</span><br><span class="line">      </span><br><span class="line">        EndpointConfiguration endpointConfig = CreateEndpointConfiguration(); <span class="comment">//&lt;-- configure the endpoint here</span></span><br><span class="line"></span><br><span class="line">        IEndpointInstance endpoint = Endpoint.Start(endpointConfig).GetAwaiter().GetResult();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>As it is obvious in the code above, you’d have to block the Start method call as it is async. It goes without saying that this is not a good practice and could cause issues like thread getting blocked or even deadlocks in certain situations. </p><p>More importantly, if you have message handlers in your process, when you start the endpoint it opens the flood gates and the handler will start receiving messages. This might be undesired as you are still initializing the application. The <code>ConfigureServices</code> stage is for preparing your services and not actually run anything.</p><h2 id="Running-async-tasks"><a href="#Running-async-tasks" class="headerlink" title="Running async tasks"></a>Running async tasks</h2><p>The proper way to run long running async tasks in aspnet core is to use <code>IHostedService</code> interface. The good thing about this interface is that it supports async already as both <code>StartAsync</code> and <code>StopAsync</code> methods are designed to support async method calls.</p><p>Starting NServiceBus as a background service would look something like this (this is a simplified version):</p><p>Note: there is a base class called <code>BackgroundService</code> implementing this interaface already, so you can inherit from that base class instead.</p><figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">NServiceBusServiceHost</span> : <span class="title">IHostedService</span></span><br><span class="line">&#123;</span><br><span class="line">    EndpointConfiguration _config;</span><br><span class="line">    TaskCompletionSource&lt;IEndpointInstance&gt; _endpointTcs;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">NServiceBusServiceHost</span>(<span class="params">EndpointConfiguration config</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        _config = config;</span><br><span class="line">        _endpointTcs = <span class="keyword">new</span> TaskCompletionSource&lt;IEndpointInstance&gt;(TaskCreationOptions.RunContinuationsAsynchronously);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">public</span> Task&lt;IEndpointInstance&gt; EndpointInstance =&gt; _endpointTcs.Task;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">async</span> Task <span class="title">StartAsync</span>(<span class="params">CancellationToken cancellationToken</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        <span class="keyword">try</span></span><br><span class="line">        &#123;</span><br><span class="line">            <span class="keyword">var</span> endpoint = <span class="keyword">await</span> Endpoint.Start(_config).ConfigureAwait(<span class="literal">false</span>);</span><br><span class="line">            _endpointTcs.TrySetResult(endpoint);</span><br><span class="line">        &#125;</span><br><span class="line">        catch (Exception e)</span><br><span class="line">        &#123;</span><br><span class="line">            _endpointTcs.TrySetException(e);</span><br><span class="line">            <span class="keyword">throw</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">async</span> Task <span class="title">StopAsync</span>(<span class="params">CancellationToken cancellationToken</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        <span class="keyword">var</span> endpoint = <span class="keyword">await</span> EndpointInstance.ConfigureAwait(<span class="literal">false</span>);</span><br><span class="line">        <span class="keyword">await</span> endpoint.Stop().ConfigureAwait(<span class="literal">false</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>And then we can easily plug in the hosted service in our Startup method like:</p><figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">services.AddHostedService&lt;NServiceBusServiceHost&gt;();</span><br></pre></td></tr></table></figure><p>And this, of course does not work. The problem is that the service expects the EndpointConfiguration object to be registered in the container. An alternative to that is to manually register the hosted service like so:</p><figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">services.AddSingleton&lt;IHostedService&gt;(provider =&gt; <span class="keyword">new</span> NServiceBusServiceHost(CreateEndpointConfiguration()));</span><br></pre></td></tr></table></figure><p>There are still other things to figure out though. For example, how do you send messages in your controllers? With this approach, you’ll need to inject the hosted service into your controller to use the <code>IEndpointInstance</code> interface. If your controller has direct dependency on <code>IEndpointInstance</code> (or <code>IMessageSession</code>) to send messages, it won’t work.</p><h2 id="Using-the-adapter"><a href="#Using-the-adapter" class="headerlink" title="Using the adapter"></a>Using the adapter</h2><p>As you can see, making it work is a lot of chore and figuring out all the little details would add up. Luckily, there are two packages to use. Why two packages, you may ask? We’ll get to that in a bit. Using these packages allow seamless integration between Asp.net Core and NServiceBus. The package essentially does the same thing as here, but also registers <code>IMessageSession</code> in the container as well. Your code would look like this:</p><figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">services.AddNServiceBus(CreateEndpointConfiguration());</span><br></pre></td></tr></table></figure><p>There are two packages to choose from to achieve this. There is the <code>Community.NServiceBus.WebHost</code> package, designed for .NET Core 2.x and there is the official <code>NServiceBus.Extensions.Hosting</code> that works for .NET Core 3.x. Why two packages, again? The reason is that there is race-condition in Asp.net Core 2.x which would cause <code>IMessageSession</code> not being available when the application is being initialized. The community package has a workaround for this to ‘make it work’ but the better option is to use the official package but you’ll need to be on .NET Core 3.x to do so.</p><p>The official documentation can be found <a href="https://docs.particular.net/nservicebus/hosting/extensions-hosting">online</a>.</p>]]></content>
    
    
    <summary type="html">&lt;p&gt;With .NET Core now becoming mainstream, you might ask how you can run NServiceBus endpoints in an asp.net process. After all, it sounds pretty trivial, but turns out maybe not as easy as it sounds. Let’s see why.</summary>
    
    
    
    
    <category term="netcore" scheme="http://www.seesharpsoftware.com.au/tags/netcore/"/>
    
    <category term="nservicebus" scheme="http://www.seesharpsoftware.com.au/tags/nservicebus/"/>
    
    <category term="aspnet" scheme="http://www.seesharpsoftware.com.au/tags/aspnet/"/>
    
  </entry>
  
  <entry>
    <title>Optimistic Concurrency in Sagas</title>
    <link href="http://www.seesharpsoftware.com.au/optimistic-concurrency-in-sagas/"/>
    <id>http://www.seesharpsoftware.com.au/optimistic-concurrency-in-sagas/</id>
    <published>2017-07-23T10:00:00.000Z</published>
    <updated>2022-05-02T04:08:46.781Z</updated>
    
    <content type="html"><![CDATA[<p>NServiceBus Sagas are a powerful feature that would allow you model long running processes without managing the state on your own or having to juggle correlating messages. Since they manage the state for you and messaging systems being distributed and things running concurrently, they also do concurrency control via Optimistic Concurrency.</p><a id="more"></a><p>If you have done database work before, you know that optimistic concurrency means if two things happen at the same time, one of them will fail. Armed with NServiceBus retries, we can easily recuperate from the ‘transient’ problems by merely retrying the offending message and eventually get it working since the second time - hopefully - no one has touched the state.</p><p>I was reviewing a code where the messages were being retired constantly during a batch import. Imagine importing data in batches via a remote HTTP service and the saga is completed when all the batches are imported successfully. The code looked something like this (skipping the saga signature):</p><figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">async</span> Task <span class="title">Handle</span>(<span class="params">ImportData message, IMessageHandlerContext context</span>)</span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    Data.PagesToImport = message.PagesToImport;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">foreach</span> (<span class="keyword">var</span> pageNo <span class="keyword">in</span> Enumerable.Range(<span class="number">1</span>, message.PagesToImport))</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">await</span> context.Send(<span class="keyword">new</span> ImportDataPage</span><br><span class="line">        &#123;</span><br><span class="line">            ImportID = Data.ImportID,</span><br><span class="line">            PageNo = pageNo</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">async</span> Task <span class="title">Handle</span>(<span class="params">ImportDataPage message, IMessageHandlerContext context</span>)</span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">await</span> remote.ImportDataPage(message.PageNo); <span class="comment">//Import the data from the remoteserver</span></span><br><span class="line"></span><br><span class="line">    Data.DataPagesImported++; <span class="comment">//Update our local state</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">await</span> CheckIfAllPagesImported(context);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">async</span> Task <span class="title">CheckIfAllPagesImported</span>(<span class="params">IMessageHandlerContext context</span>)</span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (Data.DataPagesImported == Data.PagesToImport)</span><br><span class="line">    &#123;</span><br><span class="line">        MarkAsComplete();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>Now the interesting thing that was happenning was because the calls to import the data were running concurrently. On one hand, this was a good thing as the call to get the data was a slow HTTP operation running slowly, but the saga was complaining about the concurrency, as 5 requests running at the same time, would clash if they finish around the same time when they are finished and need to update the saga’s state.</p><h2 id="First-stab-limiting-the-concurrency-level"><a href="#First-stab-limiting-the-concurrency-level" class="headerlink" title="First stab: limiting the concurrency level"></a>First stab: limiting the concurrency level</h2><p>So if the saga is complaining about too many messages touching the state at the same time what’s the first thing you’d try to do? Maybe dialing down on the concurrency level? That might make sense, since if we have less messages running at the same time, we’ll have less clashing as well. Doing this is like ‘erasing the problem’ though since the concurreny was desired. </p><p>Furthermore, customizing concurrency levels per message type is only possible by customizing the message processing pipeline as NServiceBus does not allow you to do that out of the box - and for good reasons.</p><h2 id="Second-stab-understanding-the-real-problem"><a href="#Second-stab-understanding-the-real-problem" class="headerlink" title="Second stab: understanding the real problem"></a>Second stab: understanding the real problem</h2><p>Taking a step back, I had to ask myself a question: why is this a problem? Didn’t we just say NServiceBus retries take care of the concurrency issues? Didn’t all the messages <em>eventually</em> succeed? The answer to that question was key.</p><p>The real problem this was causing was not the concurrency or the number of retires. The problem was in the fact that the remote HTTP calls are made again, since the whole message had to get retried. Let’s have a closer look at the code:</p><figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">await</span> remote.ImportDataPage(message.PageNo); <span class="comment">// &lt;- Remote HTTP Operation</span></span><br><span class="line"></span><br><span class="line">Data.DataPagesImported++; <span class="comment">// &lt;- Local Database Update</span></span><br></pre></td></tr></table></figure><p>See the problem? The problem lies in the way the transactional and non-transactional resources are mixed. You should <em>never</em> do that.</p><h2 id="Capturing-the-intent"><a href="#Capturing-the-intent" class="headerlink" title="Capturing the intent"></a>Capturing the intent</h2><p>How do we separate the two concerns then? By adding another level of indirection of course. Here it means sending a message to capture the intent rather than doing two things with the same message. This is a very important thing to remember. </p><p>Here’s how the final code would look like:</p><figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">async</span> Task <span class="title">Handle</span>(<span class="params">ImportData message, IMessageHandlerContext context</span>)</span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    Data.PagesToImport = message.PagesToImport;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">foreach</span> (<span class="keyword">var</span> pageNo <span class="keyword">in</span> Enumerable.Range(<span class="number">1</span>, message.PagesToImport))</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">await</span> context.Send(<span class="keyword">new</span> ImportDataPage</span><br><span class="line">        &#123;</span><br><span class="line">            ImportID = Data.ImportID,</span><br><span class="line">            PageNo = pageNo</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">await</span> CheckIfAllPagesImported(context); <span class="comment">//If there&#x27;s no data to import</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">async</span> Task <span class="title">Handle</span>(<span class="params">ImportDataPage message, IMessageHandlerContext context</span>)</span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">await</span> agent.ImportDataPage(message.PageNo);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">await</span> context.Publish(<span class="keyword">new</span> DataPageImported</span><br><span class="line">    &#123;</span><br><span class="line">        ImportID = Data.ImportID,</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">async</span> Task <span class="title">Handle</span>(<span class="params">DataPageImported message, IMessageHandlerContext context</span>)</span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    Data.DataPagesImported++;</span><br><span class="line">    <span class="keyword">await</span> CheckIfAllPagesImported(context);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">async</span> Task <span class="title">CheckIfAllPagesImported</span>(<span class="params">IMessageHandlerContext context</span>)</span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (Data.DataPagesImported == Data.PagesToImport)</span><br><span class="line">    &#123;</span><br><span class="line">        MarkAsComplete();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>As you can see, the act to update the internal state is separated from the act of fetching the data. Does this means that there would not be any concurrency issues? No. There still will be, but the conflicting message that gets ‘retried’ is only to update the internal state and would not need to rerun the whole import process to do so!</p>]]></content>
    
    
    <summary type="html">&lt;p&gt;NServiceBus Sagas are a powerful feature that would allow you model long running processes without managing the state on your own or having to juggle correlating messages. Since they manage the state for you and messaging systems being distributed and things running concurrently, they also do concurrency control via Optimistic Concurrency.&lt;/p&gt;</summary>
    
    
    
    
    <category term="NServiceBus" scheme="http://www.seesharpsoftware.com.au/tags/NServiceBus/"/>
    
    <category term="Sagas" scheme="http://www.seesharpsoftware.com.au/tags/Sagas/"/>
    
    <category term="Concurrency" scheme="http://www.seesharpsoftware.com.au/tags/Concurrency/"/>
    
  </entry>
  
  <entry>
    <title>Farsi Library v2.7 Available!</title>
    <link href="http://www.seesharpsoftware.com.au/farsilibrary-v2.7-now-available/"/>
    <id>http://www.seesharpsoftware.com.au/farsilibrary-v2.7-now-available/</id>
    <published>2017-02-28T09:00:00.000Z</published>
    <updated>2022-05-02T04:00:08.200Z</updated>
    
    <content type="html"><![CDATA[<p>The version 2.7 of Farsi Library is now released through Nuget. As stated in the roadmap last year, I’m now integrating the existing functionality into other 3rd party suite of controls. This version integrates with DevExpress controls and supports the new theme and animations. There are two packages targetting DevExpress version 15.2 and 16.1 so you need to pick the right version. Due to amount of breaking change in each major version, I will need to publish new releases targetting each major DevExpress versions. For minor versions you might be able to get away with assembly redirects, depending on the amount of breaking changes in them. </p><a id="more"></a><h2 id="New-Releases"><a href="#New-Releases" class="headerlink" title="New Releases"></a>New Releases</h2><p>The following packages are all now available through Nuget:</p><ul><li>FarsiLibrary.Utils for date calculations and helper functions only.</li><li>FarsiLibrary.Win for Windows Forms specific controls</li><li>FarsiLibrary.WPF for WPF based controls and themes</li><li>Farsi.Library.Win.DevExpress-v15.2 for extended controls that add Persian calendar support to DevExpress controls, targetting v15.2.</li><li>Farsi.Library.Win.DevExpress-v16.1 for extended controls that add Persian calendar support to DevExpress controls, targetting v16.1.</li></ul><h2 id="But-I-want-integration-with-the-other-frameworks…"><a href="#But-I-want-integration-with-the-other-frameworks…" class="headerlink" title="But I want integration with the other frameworks…"></a>But I want integration with the other frameworks…</h2><p>This library took shape out of my personal need over time and through various projects. I’m no longer using this as extensively as before but I still have some time - although limited - to allocate to this framework. Feel free to send your bug reports or pull requests through Github, if you face any issues or want to give me a hand.   </p>]]></content>
    
    
    <summary type="html">&lt;p&gt;The version 2.7 of Farsi Library is now released through Nuget. As stated in the roadmap last year, I’m now integrating the existing functionality into other 3rd party suite of controls. This version integrates with DevExpress controls and supports the new theme and animations. There are two packages targetting DevExpress version 15.2 and 16.1 so you need to pick the right version. Due to amount of breaking change in each major version, I will need to publish new releases targetting each major DevExpress versions. For minor versions you might be able to get away with assembly redirects, depending on the amount of breaking changes in them. &lt;/p&gt;</summary>
    
    
    
    
    <category term="DevExpress" scheme="http://www.seesharpsoftware.com.au/tags/DevExpress/"/>
    
    <category term="FarsiLibrary" scheme="http://www.seesharpsoftware.com.au/tags/FarsiLibrary/"/>
    
  </entry>
  
  <entry>
    <title>Farsi Library v2.6 Available!</title>
    <link href="http://www.seesharpsoftware.com.au/farsilibrary-v2.6-now-available/"/>
    <id>http://www.seesharpsoftware.com.au/farsilibrary-v2.6-now-available/</id>
    <published>2016-06-14T10:00:00.000Z</published>
    <updated>2022-05-02T04:00:11.587Z</updated>
    
    <content type="html"><![CDATA[<p>Back in 2003 I started to work on a library to use on my line of business applications to address the short-comings around Persian calendar and date controls with proper RightToLeft support. My needs were simple. I was developing business application that needed to be multi-lingual with correct rendering and date displays. Not much to ask, but even simple things like date calculations was not possible as there was not Persian calendar out of the box in .NET framework 1.1.</p><a id="more"></a><p>Fast-forward 13 years and things have changed quite a bit. Not only Microsoft added Persian Calendar on .NET Framework 2.0 but years after they finally <a href="https://msdn.microsoft.com/en-us/library/system.globalization.persiancalendar(v=vs.110).aspx">changed its behavior</a> in .NET Framework 4.6 so that the calculations are correct and consistent with the date calculations of Windows 10. This means more controls and libraries will start supporting the calendar just like libraries like <a href="http://nodatime.org/">NodaTime</a> already has.</p><h2 id="The-Road-Map"><a href="#The-Road-Map" class="headerlink" title="The Road Map"></a>The Road Map</h2><p>Farsi Library had its own date calculations based on the algorithm from day one. Even with proper support out of the box in .NET Framework, you still need things like helper functions and controls to make dates easier to work with.</p><p>On the control side of things, although I have had basic controls like Calendars and Date Pickers, component vendors like DevExpress provide vast array of controls, all of which now come with RightToLeft support. Now that doesn’t mean you can use them directly in your business application but it gives you a good foundation to build what you need.</p><p>I have decided to work on ‘extension’ controls off 3rd party components rather than developing new controls. This means that you will take a dependency on a 3rd party control like Telerik or DevExpress but if you are developing business application and need a sophisticated custom control like a Scheduler, changes are you already use a 3rd party control anyway.</p><h2 id="New-Releases"><a href="#New-Releases" class="headerlink" title="New Releases"></a>New Releases</h2><p>All the updates going forward are published through Nuget. Historically, only date calculation assembly was available on Nuget but from now on you can find the following packages:</p><ul><li>FarsiLibrary.Utils for date calculations and helper functions</li><li>FarsiLibrary.Win for Windows Forms specific controls</li><li>FarsiLibrary.WPF for WPF based controls and themes</li><li>Farsi.Library.Win.DevExpress for extended controls that add Persian calendar support to DevExpress controls.</li></ul><p>DevExpress controls package is updated to target v15.1 but you will need a DevExpress licence and accesss to use them with as they are not bundled together. More DevExpress controls will be available with proper Persian Calendar support.</p><h2 id="Release-2-6-Now-Available"><a href="#Release-2-6-Now-Available" class="headerlink" title="Release 2.6 Now Available"></a>Release 2.6 Now Available</h2><p>This is for the most part a maintanance release and an update to target .NET Framework 4.6. </p><p>There is only one breaking change in this release. The name “Resources” turns out to be a undocumented reserved-word in WPF and that broke Visual Studio designer support for WPF projects. As such, I had to rename the FarsiLibrary.Resources.dll to FarsiLibrary.Localization.dll. </p><p>There’s also a new build system using FAKE (F# Make) scripts and old custom MSBuild scripts are removed from the solution. This means you can easily grab the source code from GitHub and run the Build.cmd from the command prompt to build everything from the source code. </p>]]></content>
    
    
    <summary type="html">&lt;p&gt;Back in 2003 I started to work on a library to use on my line of business applications to address the short-comings around Persian calendar and date controls with proper RightToLeft support. My needs were simple. I was developing business application that needed to be multi-lingual with correct rendering and date displays. Not much to ask, but even simple things like date calculations was not possible as there was not Persian calendar out of the box in .NET framework 1.1.&lt;/p&gt;</summary>
    
    
    
    
    <category term="FarsiLibrary" scheme="http://www.seesharpsoftware.com.au/tags/FarsiLibrary/"/>
    
  </entry>
  
  <entry>
    <title>SQL Server service startup failure</title>
    <link href="http://www.seesharpsoftware.com.au/sql-server-service-startup-failure/"/>
    <id>http://www.seesharpsoftware.com.au/sql-server-service-startup-failure/</id>
    <published>2015-09-02T12:00:00.000Z</published>
    <updated>2022-05-02T04:00:14.936Z</updated>
    
    <content type="html"><![CDATA[<p>This has happened twice for me in last month so here’s how I document it since if something happens twice will happen more again.</p><a id="more"></a><p>Here’s how it started: I paved my machine and installed SQL 2012 Express for one of my projects. Once the installation went its smooth way and finished at the last step I got a warning that the Windows service can’t be started. Interestingly the installation was not rolled back and I was left with a SQL service that wouldn’t start. Event viewer wasn’t particularly helpful either. He’s how I’ve done my investigation which showed me the exact direction I needed to go.</p><p>To understand the issue, I had to run the SQL process <em>somehow</em> and see what’s happening. How do you do this? Pretty easy! You just check how Windows service is running:</p><p><img src="/images/BlogPics/SqlService.png" alt="SqlService"></p><p>So just copy that command into a command prompt, but before you run, we need to force the instance to start and put it in single user mode, so add the following switches to it:</p><p>C:\PathToYourSQLInstance\MSSQL\Binn\sqlservr.exe -sMSSQLSERVER /f /T3608</p><blockquote><p>Note that I installed my database as the default instance. This will be a repeating assumption.</p></blockquote><p>Once you run this, you get to see the logs which will tell you exactly what’s happening under the hood. Here are the interesting bits:</p><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">2015-09-01 19:37:19.92 spid12s     Database &#39;model&#39; cannot be opened due to inaccessible files or insufficient memory or disk space.  See the SQL Server errorlog for details.</span><br><span class="line"></span><br><span class="line">    2015-09-01 19:37:19.89 spid12s     Starting up database &#39;model&#39;.</span><br><span class="line">    2015-09-01 19:37:19.89 spid12s     Error: 17204, Severity: 16, State: 1.</span><br><span class="line">    2015-09-01 19:37:19.89 spid12s     FCB::Open failed: Could not open file E:\sql12_main_t.obj.x86Release\sql\mkmastr\databases\mkmastr.proj\model.mdf for file number 1.  OS error: 3(The system cannot find the path specified.).</span><br><span class="line">    2015-09-01 19:37:19.89 spid12s     Error: 5120, Severity: 16, State: 101.</span><br><span class="line">    2015-09-01 19:37:19.89 spid12s     Unable to open the physical file &quot;E:\sql12_main_t.obj.x86Release\sql\mkmastr\databases\mkmastr.proj\model.mdf&quot;. Operating system error 3: &quot;3(The system cannot find the path specified.)&quot;.</span><br></pre></td></tr></table></figure><p>See that E:\ drive and system can not find the path for model database? That looks to be the issue. I don’t even have an E: drive to begin with!</p><p>How do I fix it though? At this stage since the service is up in forced mode, you can connect to it. So bring up another command prompt and run this:</p><figure class="highlight cmd"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">SQLCMD -s .</span><br></pre></td></tr></table></figure><p>Now from here, you can run the following statement:</p><figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">SELECT</span> <span class="keyword">name</span>, physical_name, state_desc <span class="keyword">FROM</span> sys.master_files <span class="keyword">ORDER</span> <span class="keyword">BY</span> database_id;</span><br><span class="line">GO</span><br></pre></td></tr></table></figure><p>This will show you paths to the data file and log file for your databases. Mine was something like the following, which clearly shows that my main databases (temp, model, msdb) all have wrong paths:</p><figure class="highlight cmd"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="function">.E:\<span class="title">sql12_main_t.obj.x86Release</span>\<span class="title">sql</span>\<span class="title">mkmastr</span>\<span class="title">databases</span>\<span class="title">mkmastr.proj</span>\<span class="title">tempdb.mdf</span>  .<span class="title">ONLINE</span></span></span><br><span class="line"><span class="function">.<span class="title">E</span>:\<span class="title">sql12_main_t.obj.x86Release</span>\<span class="title">sql</span>\<span class="title">mkmastr</span>\<span class="title">databases</span>\<span class="title">mkmastr.proj</span>\<span class="title">templog.ldf</span> .<span class="title">ONLINE</span></span></span><br></pre></td></tr></table></figure><p>So the fix would be to change that path that’s pointing to the non-existing E: drive to a proper location, which these statements would take care of:</p><figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">ALTER</span> <span class="keyword">DATABASE</span> <span class="keyword">model</span> <span class="keyword">MODIFY</span> <span class="keyword">FILE</span> ( <span class="keyword">NAME</span> = modeldev, FILENAME = <span class="string">&#x27;C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\model.mdf&#x27;</span>);</span><br><span class="line">GO</span><br><span class="line"><span class="keyword">ALTER</span> <span class="keyword">DATABASE</span> <span class="keyword">model</span> <span class="keyword">MODIFY</span> <span class="keyword">FILE</span> ( <span class="keyword">NAME</span> = modellog, FILENAME = <span class="string">&#x27;C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\modellog.ldf&#x27;</span>);</span><br><span class="line">GO</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">ALTER</span> <span class="keyword">DATABASE</span> tempdb <span class="keyword">MODIFY</span> <span class="keyword">FILE</span> ( <span class="keyword">NAME</span> = tempdev, FILENAME = <span class="string">&#x27;C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\tempdb.mdf&#x27;</span>);</span><br><span class="line">GO</span><br><span class="line"><span class="keyword">ALTER</span> <span class="keyword">DATABASE</span> tempdb <span class="keyword">MODIFY</span> <span class="keyword">FILE</span> ( <span class="keyword">NAME</span> = templog, FILENAME = <span class="string">&#x27;C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\templog.ldf&#x27;</span>);</span><br><span class="line">GO</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">ALTER</span> <span class="keyword">DATABASE</span> MSDB <span class="keyword">MODIFY</span> <span class="keyword">FILE</span> ( <span class="keyword">NAME</span> = MSDBData, FILENAME = <span class="string">&#x27;C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\MSDBData.mdf&#x27;</span>);</span><br><span class="line">GO</span><br><span class="line"><span class="keyword">ALTER</span> <span class="keyword">DATABASE</span> MSDB <span class="keyword">MODIFY</span> <span class="keyword">FILE</span> ( <span class="keyword">NAME</span> = MSDBLog, FILENAME = <span class="string">&#x27;C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\MSDBLog.ldf&#x27;</span>);</span><br><span class="line">GO</span><br></pre></td></tr></table></figure><p>After doing this, I could start the service except I couldn’t login with my “sa” account. Fortunately you can use the same tecnique to reset the SA account’s password. Again run the service and connect to it like the above and run these:</p><figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">ALTER</span> LOGIN [sa] <span class="keyword">WITH</span> DEFAULT_DATABASE=[<span class="keyword">master</span>]</span><br><span class="line"><span class="keyword">GO</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">ALTER</span> LOGIN [sa] <span class="keyword">WITH</span> <span class="keyword">PASSWORD</span>=N<span class="string">&#x27;yoursapasswordgoeshere&#x27;</span></span><br><span class="line"><span class="keyword">GO</span></span><br></pre></td></tr></table></figure><p>And that’s that. One more thing to note is that even when I uninstalled SQL 2012 and installed SQL 2014 on the machine, exact same thing happened again. Hope this saves someone from a headache.</p>]]></content>
    
    
    <summary type="html">&lt;p&gt;This has happened twice for me in last month so here’s how I document it since if something happens twice will happen more again.&lt;/p&gt;</summary>
    
    
    
    
    <category term="VisualStudio" scheme="http://www.seesharpsoftware.com.au/tags/VisualStudio/"/>
    
    <category term="SQLServer" scheme="http://www.seesharpsoftware.com.au/tags/SQLServer/"/>
    
  </entry>
  
  <entry>
    <title>DDD - Part Three - Domain Events</title>
    <link href="http://www.seesharpsoftware.com.au/ddd-part-three-domain-events/"/>
    <id>http://www.seesharpsoftware.com.au/ddd-part-three-domain-events/</id>
    <published>2015-02-10T05:50:42.000Z</published>
    <updated>2022-05-02T04:00:01.547Z</updated>
    
    <content type="html"><![CDATA[<p>Domain event is a very useful concept in Domain Driven Design that allows you to separate concerns in your domain via events. You can also offload the side effects of the actions in your domain to an event handler and let that run asynchronously. For things like sending emails and notifications this makes perfect sense since those are inherently asynchronous anyway. </p><a id="more"></a><p><em>Nitpicker’s Corner: I understand that if you can live with Eventual Consistency, you can do pretty much everything in your domain with events and commands. In this post, I’m assuming Eventual Consistency isn’t what you are after and you want a transactional boundary.</em></p><p>If you ask what is exactly a Domain Event, here’s Marting Fowler’s <a href="http://martinfowler.com/eaaDev/DomainEvent.html">definition</a>:</p><blockquote><p>The essence of a Domain Event is that you use it to capture things that can trigger a change to the state of the application you are developing. These event objects are then processed to cause changes to the system…</p></blockquote><p>Depending on your domain, sometimes you can’t live with inconsistencies (or eventual consistency), so the events you raise should be handled in the same unit of work as the action on your <a href="http://martinfowler.com/bliki/DDD_Aggregate.html">Aggregate Root</a>. Having said that, sometimes it conceptually makes sense to have an asynchronous event handler run after the main transaction is committed (and we’ll come back to this). Things like sending emails or communicating with a third party system which is inherently asynchronous and network bound can be done in this way. Let’s see how both can be done.</p><p>Since these events run in the same unit of work, they are very easy to manage due to lack of eventual consistency. Essentially, if you roll back the main transaction, the events that are raised are rolled back as well, as if nothing has happened. Let’s see an example:</p><figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">Order</span> : <span class="title">AggregateRoot</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">public</span> Customer Customer &#123; <span class="keyword">get</span>; <span class="keyword">set</span>; &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Approve</span>(<span class="params"></span>) </span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        <span class="comment">//Removed for brevity</span></span><br><span class="line">        Raise(<span class="keyword">new</span> OrderApproved(<span class="keyword">this</span>));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">OrderApproved</span> : <span class="title">IDomainEvent</span> <span class="comment">//Marker interface</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">public</span> Order ApprovedOrder &#123; <span class="keyword">get</span>; <span class="keyword">private</span> <span class="keyword">set</span>; &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">OrderApproved</span>(<span class="params">Order order</span>) </span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        ApprovedOrder = order;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">PreferredCustomerCalculator</span> : <span class="title">IHandle</span>&lt;<span class="title">OrderApproved</span>&gt;</span><br><span class="line">&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">Handle</span>(<span class="params">OrderApproved @<span class="keyword">event</span></span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        <span class="keyword">var</span> order = @event.ApprovedOrder;</span><br><span class="line">        <span class="keyword">var</span> customer = order.Customer; <span class="comment">//&lt;-- Owner of the order, referencing Customer class.</span></span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span>(SatisfiesPreferredCustomerCriteria(customer))</span><br><span class="line">        &#123;</span><br><span class="line">            customer.Preferred = <span class="literal">true</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>This is basically the gist of it, but there are a few details that you may miss at first glance. First, from performance aspects, since this runs within the same transaction (as I said the event handler is not asynchronous in this example) and we have a long running operation, there is higher chances of deadlocks and timeouts, but hey, the benefit is having consistency within the boundary of the transaction scope.</p><p>The main thing here, is that it is not clear ‘how’ the event is raised. What’s the magic to the ‘Raise’ method? The Raise method is simple really, it just adds the events you give to it to an in-memory collection of events. So who raises the event, I hear you ask? This is done somewhere in the bowls of our DbContext. Ideally, we want the event to be raised only when the object graph is persisted in the database, but the transaction is still not committed so that we can roll back, if need be. This way we can do our event processing and database interactions in one transaction to get consistency. Here’s the missing piece of the puzzle:</p><figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">DomainEvents</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">readonly</span> <span class="title">Dictionary</span>&lt;<span class="title">Type</span>, <span class="title">IList</span>&lt;<span class="title">Type</span>&gt;&gt; HandlerTypes</span> = <span class="keyword">new</span> Dictionary&lt;Type, IList&lt;Type&gt;&gt;();  <span class="comment">//Subscription information</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">Subscribe</span>(<span class="params">Type eventType, Type handlerType</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        <span class="comment">//On application startup, subscribe all the event</span></span><br><span class="line">        <span class="comment">//handlers to the respective events. You&#x27;ll need some sort</span></span><br><span class="line">        <span class="comment">//Of subscription storage for them, but in-memory </span></span><br><span class="line">        <span class="comment">//subscription e.g. a dictionary, may work fine for simple scenarios.</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">Publish</span>&lt;<span class="title">T</span>&gt;(<span class="params">T @<span class="keyword">event</span></span>) <span class="keyword">where</span> T : <span class="keyword">class</span>, IDomainEvent</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        <span class="keyword">var</span> handlerTypes = GetHandlersForEvent(@event.GetType()).ToList();</span><br><span class="line">        <span class="keyword">if</span> (!handlerTypes.Any()) <span class="keyword">return</span>;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">foreach</span> (<span class="keyword">var</span> handlerType <span class="keyword">in</span> handlerTypes)</span><br><span class="line">            ExecuteHandler(@event, handlerType);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">ExecuteHandler</span>(<span class="params">IDomainEvent @<span class="keyword">event</span>, Type handlerType</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        <span class="keyword">var</span> handler = (<span class="built_in">dynamic</span>)Container.Resolve(handlerType); <span class="comment">//Resolve the event handler from the container.</span></span><br><span class="line">        handler.Handle((<span class="built_in">dynamic</span>)@event); <span class="comment">//Use of dynamics instead of casting and reflection makes it a bit easier.</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> IEnumerable&lt;Type&gt; <span class="title">GetHandlersForEvent</span>(<span class="params">Type eventType</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        <span class="keyword">var</span> implementedTypes = eventType.GetInterfaces().Union(<span class="keyword">new</span>[] &#123; eventType &#125;); <span class="comment">// Event type + implemented interfaces</span></span><br><span class="line"></span><br><span class="line">        <span class="keyword">foreach</span> (<span class="keyword">var</span> implementedType <span class="keyword">in</span> implementedTypes)</span><br><span class="line">        &#123;</span><br><span class="line">            IList&lt;Type&gt; handlerTypes;</span><br><span class="line">            <span class="keyword">if</span> (!HandlerTypes.TryGetValue(implementedType, <span class="keyword">out</span> handlerTypes)) <span class="keyword">continue</span>;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">foreach</span> (<span class="keyword">var</span> handlerType <span class="keyword">in</span> handlerTypes)</span><br><span class="line">                <span class="keyword">yield</span> <span class="keyword">return</span> handlerType;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>The other thing to note here is that since the event processing will be done in the same transaction, the more you add handlers for an event, the more time it is going to take to complete a transaction. What’s even worse is that it may not be obvious - due to decouple nature of event and event handler - that you’re adding more work to your transactions.</p><p>It is not all bad though. If you can live with <a href="http://martinfowler.com/bliki/CQRS.htmlbliki/CQRS.html">Eventual Consistency</a>, you can offload some your event handlers to work asynchronously. This means, even the main work is done within the transaction and the side effects are done in subsequent / separate transactions. On next post we’ll see how this works.</p>]]></content>
    
    
    <summary type="html">&lt;p&gt;Domain event is a very useful concept in Domain Driven Design that allows you to separate concerns in your domain via events. You can also offload the side effects of the actions in your domain to an event handler and let that run asynchronously. For things like sending emails and notifications this makes perfect sense since those are inherently asynchronous anyway. &lt;/p&gt;</summary>
    
    
    
    
    <category term="EntityFramework" scheme="http://www.seesharpsoftware.com.au/tags/EntityFramework/"/>
    
    <category term="DDD" scheme="http://www.seesharpsoftware.com.au/tags/DDD/"/>
    
  </entry>
  
  <entry>
    <title>JSON Serialization in WebAPI</title>
    <link href="http://www.seesharpsoftware.com.au/json-serilization-in-web-api/"/>
    <id>http://www.seesharpsoftware.com.au/json-serilization-in-web-api/</id>
    <published>2015-01-13T10:41:17.000Z</published>
    <updated>2022-05-02T04:01:03.443Z</updated>
    
    <content type="html"><![CDATA[<p>If you’ve worked with JSON endpoints and WebAPI, you know how seamlessly it works when sending out objects that will be serialized into JSON. <a id="more"></a> An example would be something like this:</p><figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">Account</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="built_in">string</span> FirstName &#123; <span class="keyword">get</span>; <span class="keyword">set</span>; &#125;</span><br><span class="line">    <span class="keyword">public</span> <span class="built_in">string</span> LastName &#123; <span class="keyword">get</span>; <span class="keyword">set</span>; &#125;</span><br><span class="line">    <span class="keyword">public</span> <span class="built_in">string</span> Fullname &#123; <span class="keyword">get</span> &#123; <span class="keyword">return</span> FirstName + <span class="string">&quot; &quot;</span> + LastName; &#125; &#125;     </span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">AccountsController</span> : <span class="title">ApiController</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="built_in">object</span> <span class="title">Get</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> Account &#123;FirstName = <span class="string">&quot;John&quot;</span>, LastName = <span class="string">&quot;Doe&quot;</span>, AccountNo = <span class="number">777</span>&#125;;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>And when you issue a request with <a href="http://en.wikipedia.org/wiki/List_of_HTTP_header_fields">accept header</a> of application/json, you’ll get this:</p><figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">    FirstName: &quot;John&quot;</span><br><span class="line">    LastName: &quot;Doe&quot;</span><br><span class="line">    Fullname: &quot;John Doe&quot;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>Which is all good and dandy. In our case, however, the object we were trying to work with was behaving differently. We didn’t have the source code for that object either, but the only difference we could pick was this:</p><figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">    k__BackingField: &quot;John&quot;</span><br><span class="line">    k__BackingField: &quot;Doe&quot;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>What the….? Two issues here, if you’ve missed it. The name of the properties are totally messed up and the readonly property is not even serialized. The second issue was actually a default behavior when WebAPI was in beta versions, but it should work out of the box with the released / latest versions which we were using. And could really a <a href="http://msdn.microsoft.com/en-us/library/system.serializableattribute(v=vs.110).aspx">SerializableAttribute</a> make that big a difference?</p><p>Trying to serialize the object that had the SerializableAttribute with json, we could see that the outcome is as expected:</p><figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">JsonConvert.SerializeObject(<span class="keyword">new</span> Account &#123;FirstName = <span class="string">&quot;John&quot;</span>, LastName = <span class="string">&quot;Doe&quot;</span>&#125;); <span class="comment">// &lt;- This worked fine</span></span><br></pre></td></tr></table></figure><p>So what’s the issue? Isn’t Newtonsoft JSON library used in WebAPI out of the box?</p><h2 id="The-solution"><a href="#The-solution" class="headerlink" title="The solution"></a>The solution</h2><p>After some digging, it turns out that WebAPI in fact is not using the DefaultContractResolver from Newtonsoft.Json library directly, but rather a customized one, although slightly. The one used by the WebAPI out of the box is <code>System.Net.Http.Formatting.JsonContractResolver</code> class. If you have a peek through the code, you’ll see something interesting.</p><figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">JsonContractResolver</span> : <span class="title">DefaultContractResolver</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">JsonContractResolver</span>(<span class="params">MediaTypeFormatter formatter</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        IgnoreSerializableAttribute = <span class="literal">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>That’s suspiciously related to what seems to be our issue here, isn’t it? So the solution was to derive from JsonContractResolver and set that flag to true!</p><figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">CustomContractResolver</span> : <span class="title">System.Net.Http.Formatting.JsonContractResolver</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">CustomContractResolver</span>(<span class="params"></span>) : <span class="title">base</span>(<span class="params"><span class="keyword">new</span> JsonMediaTypeFormatter(</span>))</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        IgnoreSerializableAttribute = <span class="literal">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><h2 id="The-reasoning"><a href="#The-reasoning" class="headerlink" title="The reasoning"></a>The reasoning</h2><p>This behavior apparently has introduced in JSON.NET version 4.5. From this version, the fields are serialized instead of properties but there are a couple of ways to change this behavior depending if you have access to the source code of not. You can read more about it <a href="http://james.newtonking.com/archive/2012/04/11/json-net-4-5-release-2-serializable-support-and-bug-fixes">here</a>.</p>]]></content>
    
    
    <summary type="html">&lt;p&gt;If you’ve worked with JSON endpoints and WebAPI, you know how seamlessly it works when sending out objects that will be serialized into JSON.</summary>
    
    
    
    
    <category term="WebAPI" scheme="http://www.seesharpsoftware.com.au/tags/WebAPI/"/>
    
    <category term="Json" scheme="http://www.seesharpsoftware.com.au/tags/Json/"/>
    
  </entry>
  
  <entry>
    <title>DDD - Part Two - Value Object Persistence</title>
    <link href="http://www.seesharpsoftware.com.au/ddd-part-two-value-object-persistence/"/>
    <id>http://www.seesharpsoftware.com.au/ddd-part-two-value-object-persistence/</id>
    <published>2014-11-26T08:55:04.000Z</published>
    <updated>2022-05-02T04:01:07.216Z</updated>
    
    <content type="html"><![CDATA[<p>In DDD, the value object is used when your entity conceptually does not have an identity and it is all about the data. Now the question of something being a value object or an entity - where we care about the actual Id - is a business question but think about an address in a ordering management system where a customer has addresses. You probably don’t care about the address as something on its own, so you don’t care about it’s identity and as such, two addresses are the same if their values are the same. Another away about the value object, is that it is immutable, meaning if you want to change an address, you need to create a new one and replace an existing address as it is not possible to change an existing address.</p><a id="more"></a><p>Now ORMs in general are not happy with these approach as they mostly rely on tables and Ids to store objects. To map these objects and store them in our database there are two scenarios: Storing an entity with a value object that’s not a collection and Storing it with a collection of value objects.</p><p>Taking a Customer and an Address as the example, from the domain perspective, it’d look like this:</p><figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">Address</span> </span><br><span class="line">&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Address</span>(<span class="params"><span class="built_in">string</span> streetType, <span class="built_in">string</span> street, <span class="built_in">int</span> number</span>) </span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        StreetType = streetType;</span><br><span class="line">        Street = street;</span><br><span class="line">        Number = number;</span><br><span class="line">    &#125;</span><br><span class="line"> </span><br><span class="line">    <span class="keyword">public</span> <span class="built_in">string</span> Street &#123; <span class="keyword">get</span>; <span class="keyword">private</span> <span class="keyword">set</span>; &#125;</span><br><span class="line">    <span class="keyword">public</span> <span class="built_in">string</span> StreetType &#123; <span class="keyword">get</span>; <span class="keyword">private</span> <span class="keyword">set</span>; &#125;</span><br><span class="line">    <span class="keyword">public</span> <span class="built_in">int</span> Number &#123; <span class="keyword">get</span>; <span class="keyword">private</span> <span class="keyword">set</span>; &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">Customer</span> </span><br><span class="line">&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Customer</span>(<span class="params">Address postal, Address mailing</span>) </span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        Postal = postal;</span><br><span class="line">        Mailing = mailing;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">public</span> Address Postal &#123; <span class="keyword">get</span>; <span class="keyword">private</span> <span class="keyword">set</span>; &#125;</span><br><span class="line">    <span class="keyword">public</span> Address Mailing &#123; <span class="keyword">get</span>; <span class="keyword">private</span> <span class="keyword">set</span>; &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>Reiterating that we don’t care about the Id, it’d make sense to store this somewhere where we don’t need an Id. If you’re using EntityFramework, it is not possible to store the ‘entity’ (as in an object that’s stored in the database table) without having an ID. If you try to store the address in its own table, you still need an Id and custom mapping (we’ll get to this in a minute), otherwise as in the example above, you can store it as a part of the Customer. To achieve this you’ll need to register your value object as a complex type either by using the <code>[ComplexType]</code> attribute or like this:</p><figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">MyDataContext</span> : <span class="title">DbContext</span> </span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">public</span> IDbSet&lt;Customer&gt; Customers &#123; <span class="keyword">get</span>; <span class="keyword">set</span>; &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">override</span> <span class="keyword">void</span> <span class="title">OnModelCreating</span>(<span class="params">DbModelBuilder modelBuilder</span>) </span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        modelBuilder.ComplexType&lt;Address&gt;();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>Now when you store a Customer, Address properties are stored as fields in the customer table, e.g. Customer table would have fields such as Postal_Street, Postal_StreetType and Mailing_Street, Mailing_StreetType, etc.</p><p>The ComplexTypes come with a caveat: They can not be null. You’ll have to new up all the complex type in your constructor. So if they can not be null - much like how an Struct would behave - how would you describe the lack of a value?</p><h2 id="Lack-of-a-Value"><a href="#Lack-of-a-Value" class="headerlink" title="Lack of a Value"></a>Lack of a Value</h2><p>In value object world, what does it mean to not have a value? Specially if you use Structs, there’s no way to have a null value object. In fact when your value objects are not a collection, EntityFramework would not let you store them as null (where as all the value object fields are set to null). To work around this you can use Null Object pattern. A customer who doesn’t have a mailing address would be constructed like this:</p><figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> postalAddress = <span class="keyword">new</span> Address(blah blah);</span><br><span class="line"><span class="keyword">var</span> customerWithJustPostalAddress = <span class="keyword">new</span> Customer(postalAddress, Address.Null());</span><br></pre></td></tr></table></figure><p>and under the hood, the Null static method would just return a new object, so to make EF happy. This is kind of the same as how ‘Empty’ or lack of value is express across .NET platform (remember String.Empty?), the complete implementation of the address class would be like this:</p><figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">Address</span> </span><br><span class="line">&#123;</span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="title">Address</span>(<span class="params"></span>) </span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">    &#125;</span><br><span class="line"> </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Address</span>(<span class="params"><span class="built_in">string</span> streetType, <span class="built_in">string</span> street, <span class="built_in">int</span> number</span>) </span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        StreetType = streetType;</span><br><span class="line">        Street = street;</span><br><span class="line">        Number = number;</span><br><span class="line">    &#125;</span><br><span class="line">     </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> Address <span class="title">Null</span>(<span class="params"></span>) </span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">         <span class="keyword">return</span> <span class="keyword">new</span> Address();</span><br><span class="line">    &#125;</span><br><span class="line"> </span><br><span class="line">    <span class="keyword">public</span> <span class="built_in">string</span> Street &#123; <span class="keyword">get</span>; <span class="keyword">private</span> <span class="keyword">set</span>; &#125;</span><br><span class="line">    <span class="keyword">public</span> <span class="built_in">string</span> StreetType &#123; <span class="keyword">get</span>; <span class="keyword">private</span> <span class="keyword">set</span>; &#125;</span><br><span class="line">    <span class="keyword">public</span> <span class="built_in">int</span> Number &#123; <span class="keyword">get</span>; <span class="keyword">private</span> <span class="keyword">set</span>; &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">implicit</span> <span class="keyword">operator</span> <span class="title">string</span>(<span class="params">Address address</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">string</span>.Format(<span class="string">&quot;No. &#123;0&#125; &#123;1&#125; &#123;2&#125;&quot;</span>, Number, Street, StreetType);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>If you need to check the null object being null or not, you can achieve it by checking all the fields being set to null. It may not be ideal, but the question you probably ask yourself if you are doing it is that if the thing you are modelling is a even a value object?</p><blockquote><p>You might ask, what’s the private constructor for? Turns out, EntityFramework needs a parameterless constructor when it hydrates the object from the database. It does not have to be public though, so having it as private helps to encapsulate the entity/value objects.</p></blockquote><h2 id="Storing-Collections"><a href="#Storing-Collections" class="headerlink" title="Storing Collections"></a>Storing Collections</h2><p>When you have a collection of value objects things are different. You can’t store them as a part of your entity and you have to store them in a joined table. Take a look at this example:</p><figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">Customer</span> </span><br><span class="line">&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Customer</span>(<span class="params">IList&lt;Address&gt; addresses</span>) </span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        Addresses = addresses;</span><br><span class="line">    &#125;</span><br><span class="line">   </span><br><span class="line">   <span class="keyword">public</span> IList&lt;Address&gt; Addresses &#123; <span class="keyword">get</span>; <span class="keyword">private</span> <span class="keyword">set</span>; &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>Here, the addresses should be stored in a separate joined table, while conceptually we don’t care about such a thing as PrimaryKey for our collection of value objects. Our lives would have been much easier if we were using a document database, or a more extensible ORM like NHibernate but in EntityFramework it is not possible to have a table with no PrimaryKey.</p><p>The dilemma here is that you want to have your Id for the value object private, since that’s just an implementation detail, but still for mapping and persistence purpose you need to expose it. So if we’re going to store our Address as a collection, this code snippet wouldn’t work:</p><figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">Address</span> </span><br><span class="line">&#123;</span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="title">Address</span>(<span class="params"></span>) </span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">    &#125;</span><br><span class="line"> </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Address</span>(<span class="params"><span class="built_in">string</span> streetType, <span class="built_in">string</span> street, <span class="built_in">int</span> number</span>) </span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        StreetType = streetType;</span><br><span class="line">        Street = street;</span><br><span class="line">        Number = number;</span><br><span class="line">    &#125;</span><br><span class="line">     </span><br><span class="line">    <span class="keyword">private</span> <span class="built_in">int</span> Id &#123; <span class="keyword">get</span>; <span class="keyword">private</span> <span class="keyword">set</span>; &#125; <span class="comment">// &lt;-- Note the private property</span></span><br><span class="line">    </span><br><span class="line">    <span class="comment">//Rest of properties removed for brevity</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">AddressConfiguration</span> : <span class="title">EntityTypeConfiguration</span>&lt;<span class="title">Address</span>&gt; </span><br><span class="line">&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">ComponentConfiguration</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        HasKey(a =&gt; a.Id).Property(a =&gt; a.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); <span class="comment">// &lt;-- Compilation error because Id is private</span></span><br><span class="line">        </span><br><span class="line">        <span class="comment">//Rest of the mapping</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">MyDataContext</span> : <span class="title">DbContext</span> </span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">public</span> IDbSet&lt;Customer&gt; Customers &#123; <span class="keyword">get</span>; <span class="keyword">set</span>; &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">override</span> <span class="keyword">void</span> <span class="title">OnModelCreating</span>(<span class="params">DbModelBuilder modelBuilder</span>) </span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        modelBuilder.Configurations.Add(<span class="keyword">new</span> AddressConfiguration());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>Although you’ll get a compilation error with this code, there are couple of things to note. If you look close enough, we no longer register our address as a ComplexType, but rather as an entity (sigh) but since you will not directly access a value object, we’re not exposing it on the DataContext. The other thing is that we need a way of configuring that Id property to be auto-generated. Since the code does not compile, how do we make it work? There are two ways of fixing this. One way would be to moving that Id into a base class and exposing it so that we can do our mapping (yuck!) and the other way is to move the configuration/mapping code into our entity/value object so that they can access the private property (yuck!). Since there’s no proper solution to this Both workarounds left something to be desired but see which one works for you and pick one. </p><p>You still need to generate a unique key for that PrimaryKey but since you don’t care, you can use what your database gives you like <a href="http://msdn.microsoft.com/en-au/library/ff878058.aspx">Sequence</a> or <a href="http://msdn.microsoft.com/en-us/library/ms189838.aspx">Identity</a>. On next posts we’ll see which ID generation strategy works better with EntityFramework.</p>]]></content>
    
    
    <summary type="html">&lt;p&gt;In DDD, the value object is used when your entity conceptually does not have an identity and it is all about the data. Now the question of something being a value object or an entity - where we care about the actual Id - is a business question but think about an address in a ordering management system where a customer has addresses. You probably don’t care about the address as something on its own, so you don’t care about it’s identity and as such, two addresses are the same if their values are the same. Another away about the value object, is that it is immutable, meaning if you want to change an address, you need to create a new one and replace an existing address as it is not possible to change an existing address.&lt;/p&gt;</summary>
    
    
    
    
    <category term="EntityFramework" scheme="http://www.seesharpsoftware.com.au/tags/EntityFramework/"/>
    
    <category term="DDD" scheme="http://www.seesharpsoftware.com.au/tags/DDD/"/>
    
  </entry>
  
  <entry>
    <title>F# Type Providers</title>
    <link href="http://www.seesharpsoftware.com.au/fsharp-type-providers/"/>
    <id>http://www.seesharpsoftware.com.au/fsharp-type-providers/</id>
    <published>2014-11-19T00:24:58.000Z</published>
    <updated>2022-05-02T04:01:10.718Z</updated>
    
    <content type="html"><![CDATA[<p>You’re going to think I’m jumping on the F# bandwagon as well. Well kind of but that’s not the point of this post. The thing is, people ask me all the time: Why should I even care about F#? I have my own C# language that I love, why go through the burden of learning another language, and more importantly, another way of thinking, as functional programming is not only about the language but more conceptual way of thinking. </p><a id="more"></a><p>At the end of the day, you may say, these are all languages on top of .NET stack and compile into IL so there’s really not THAT much difference, is there?? Just show me one thing that I can do with F# and I can’t do with C#?</p><p>Turns out, there are a few things that you can’t do with C#. Among the things that is not possible to do - at least not at this point in time - is what <a href="http://msdn.microsoft.com/en-us/library/hh156509.aspx">Type Provider</a> gives you. Let’s quickly see what they are.</p><h2 id="What-is-a-type-provider"><a href="#What-is-a-type-provider" class="headerlink" title="What is a type provider"></a>What is a type provider</h2><p>Essentially, type provider provide type information (wasn’t that obvious?) to the compiler as you write your code. If you’ve ever had a joy of working with WebServices (WSDLs), XML or CSV files and things of that nature you probably had to write or generate some sort of class hierarchy to represent that structure and the use that to do what you need. A type provider will do all that for you just by having a look at a schema - that being a sample XML / CSV file with the same structure or the actual WSDL over the internet - and it will generate all the types you need to work with it. Best of all, it is all statically typed, which means once your schema is changed your code automatically won’t compile. This is unlike the WSDL code generation approach that you’d have to go with, where as you’d have to regenerate the code manually to get compilation errors.</p><h2 id="Where-do-I-use-it"><a href="#Where-do-I-use-it" class="headerlink" title="Where do I use it"></a>Where do I use it</h2><p>As said, a simple usage would be generating a wrapper for your XML / CSV files to work with. But there are even more interesting things you can do. When it comes down to interconnected data structures like <a href="http://dbpedia.org/">DBPedia</a>, <a href="http://data.worldbank.org/">WorldBank</a> and <a href="https://www.freebase.com/">Freebase</a>, generating and working with a huge API is probably not the best way, but with Type Providers for all of these rich information data sources, you can work with them as if there are statically type APIs for them. </p><h2 id="Where-do-I-go-from-here"><a href="#Where-do-I-go-from-here" class="headerlink" title="Where do I go from here"></a>Where do I go from here</h2><p>This was barely even a definition of Type Providers. If you want to learn a bit more and see some samples, you can view my talk about F# Type Providers from at the Sydney F# User Group that is now online and you can watch it here.</p><p><a href="https://www.youtube.com/watch?v=l_NWcNf0cSE" title="Type Providers in F#"><img src="https://img.youtube.com/vi/l_NWcNf0cSE/0.jpg" alt="Type Providers in F#"></a></p>]]></content>
    
    
    <summary type="html">&lt;p&gt;You’re going to think I’m jumping on the F# bandwagon as well. Well kind of but that’s not the point of this post. The thing is, people ask me all the time: Why should I even care about F#? I have my own C# language that I love, why go through the burden of learning another language, and more importantly, another way of thinking, as functional programming is not only about the language but more conceptual way of thinking. &lt;/p&gt;</summary>
    
    
    
    
    <category term="F#" scheme="http://www.seesharpsoftware.com.au/tags/F/"/>
    
    <category term="Videos" scheme="http://www.seesharpsoftware.com.au/tags/Videos/"/>
    
  </entry>
  
  <entry>
    <title>DDD - Part One - Value Objects</title>
    <link href="http://www.seesharpsoftware.com.au/ddd-part-one-value-objects/"/>
    <id>http://www.seesharpsoftware.com.au/ddd-part-one-value-objects/</id>
    <published>2014-11-11T04:40:42.000Z</published>
    <updated>2022-05-02T04:00:53.903Z</updated>
    
    <content type="html"><![CDATA[<p>In this series, I’m going to write about some of the challenges we’ve been facing with DDD. If you want to adapt DDD on .NET stack, this hopefully will be useful for you. Along with concepts I’ll talk about what works (or doesn’t) well with EntityFramework, but most of it will still be useful with other ORMs - or even without one.</p><a id="more"></a><h2 id="Value-Objects"><a href="#Value-Objects" class="headerlink" title="Value Objects"></a>Value Objects</h2><p>So let’s start with something that might be basic. Value Objects, if you have read the Blue or Red book, is a well defined concept. Martin Fowler puts it really well:</p><blockquote><p>I described Value Object as a small object such as a Money or date range object. Their key property is that they follow value semantics rather than reference semantics.</p></blockquote><p>This is a very simple, yet powerful concept, even if you don’t do <a href="http://en.wikipedia.org/wiki/Domain-driven_design">DDD</a>, you probably will see the benefit of using this. Let me give you an example. Let’s suppose you have a Customer object that has an email address. You’d want to validate the email address to be in a correct format. A naive way of doing it would be validating the string on the UI (being a web or desktop type of application doesn’t really matter) by your validation framework, and then assuming that the string is in valid form. This approach leads to data corruption and still some other layer bypassing the UI is able to work around the validation. Some other would do that on the entity level, something like:</p><figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">Customer</span> </span><br><span class="line">&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Customer</span>(<span class="params"><span class="built_in">string</span> name, <span class="built_in">string</span> email</span>) </span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        ValidateEmail(email);</span><br><span class="line">        <span class="comment">//Do the work</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">UpdateEmailAddress</span>(<span class="params"><span class="built_in">string</span> email</span>) </span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        ValidateEmail(email)</span><br><span class="line">        <span class="comment">//Do the work</span></span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>But what if now you need to pass that customer to a service needs to send the actual email, do the service assumes then that the email is already validated? do you validate that again? If you think there must be a better way of doing this, well there is. Using the value objects, you put the validation inside a class for that concept and ensure that whenever you have an object that has got created, it is in a correct state. Not allowing the objects to be in an invalid state is a very powerful thing to have, so basically you wouldn’t need a validator framework or such, at least not on your domain level. When the object is created you can trust that it has satisfied the validity criteria.</p><p>With the Value Object approach, the above code looks something like this:</p><figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">Email</span> </span><br><span class="line">&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Email</span>(<span class="params"><span class="built_in">string</span> <span class="keyword">value</span></span>) </span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        ValidateEmail(<span class="keyword">value</span>);</span><br><span class="line">        Value = <span class="keyword">value</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="built_in">string</span> Value &#123; <span class="keyword">get</span>; <span class="keyword">private</span> <span class="keyword">set</span>; &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">ValidateEmail</span>(<span class="params"><span class="built_in">string</span> <span class="keyword">value</span></span>) </span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        <span class="keyword">if</span>(EmailIsNotValid) <span class="comment">//Validate however makes sense</span></span><br><span class="line">           <span class="keyword">throw</span> <span class="keyword">new</span> DomainRuleViolatedException(<span class="string">&quot;Provided value is not a valid email address.&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>One thing to note here is that the Email value object here is immutable and that is a general heuristic.</p><p>There’s still room for improvements. Chances are, you are going to persist this email address, or pass it down to a service that sends an email, one thing that changes your experience with value objects is implicit conversion. To think about this, the email address is in nature a string and can be stored and passed around as such, so we can implement a implicit type conversion to a string:</p><figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">Email</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Email</span>(<span class="params"><span class="built_in">string</span> <span class="keyword">value</span></span>) </span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        ValidateEmail(<span class="keyword">value</span>);</span><br><span class="line">        Value = <span class="keyword">value</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="built_in">string</span> Value &#123; <span class="keyword">get</span>; <span class="keyword">private</span> <span class="keyword">set</span>; &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">ValidateEmail</span>(<span class="params"><span class="built_in">string</span> <span class="keyword">value</span></span>) </span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        <span class="keyword">if</span>(EmailIsNotValid) <span class="comment">//Validate however makes sense</span></span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> DomainViolatedException(<span class="string">&quot;Provided value is not a valid email address.&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">implicit</span> <span class="keyword">operator</span> <span class="title">string</span>(<span class="params">Email email</span>) </span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        <span class="keyword">return</span> email.Value;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>Note that <a href="http://msdn.microsoft.com/en-us/library/z5z9kes2.aspx">Implicit conversion</a> can be a double edged sword. Use it scarcely or you might end up in a situation where the conversion automagically happens and you’ll be clueless on why something is working the way it is.</p><p>Now you can pass it to your ORM as a string, or directly pass it to an API that’d require an string and the conversion from already valid email address to a string is automatically done for you. </p><p>There are numerous examples where the value object pattern is useful, things such as dates and date ranges where the date conceptually should always be in the past or future, or a concept of a numeric value where the value should always be a positive number or in a certain range.</p><p>Another thing to note here is that to be able to assign value objects by value (pardon the pun), you’ll need to use Structs and not Classes. The great example of a value object in struct is the System.DateTime. The reason for going with Struct is that inherently you can assign them by value and not by reference which aligns correctly with our concept of Value Objects. I’m not going to use Structs in these series since they don’t play well with EntityFramework.</p>]]></content>
    
    
    <summary type="html">&lt;p&gt;In this series, I’m going to write about some of the challenges we’ve been facing with DDD. If you want to adapt DDD on .NET stack, this hopefully will be useful for you. Along with concepts I’ll talk about what works (or doesn’t) well with EntityFramework, but most of it will still be useful with other ORMs - or even without one.&lt;/p&gt;</summary>
    
    
    
    
    <category term="EntityFramework" scheme="http://www.seesharpsoftware.com.au/tags/EntityFramework/"/>
    
    <category term="DDD" scheme="http://www.seesharpsoftware.com.au/tags/DDD/"/>
    
  </entry>
  
  <entry>
    <title>Object Encapsulation With EntityFramework</title>
    <link href="http://www.seesharpsoftware.com.au/object-encapsulation-with-entityframework/"/>
    <id>http://www.seesharpsoftware.com.au/object-encapsulation-with-entityframework/</id>
    <published>2014-04-30T01:17:38.000Z</published>
    <updated>2022-05-02T04:01:21.616Z</updated>
    
    <content type="html"><![CDATA[<p>One of the four fundamentals of <a href="http://en.wikipedia.org/wiki/Object-oriented_programming">Object-Oriented Programing</a> is <a href="http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming">Encapsulation</a> which is defined as: “A language mechanism for restricting access to some of the object’s components”. This would help us separate the internal implementation from the publicly accessible surface of the object. The idea is to hide how the object actually work from the outside world, so that we can change the internal without breaking anything as the object still looks the same from the outside.</p><a id="more"></a><p>Sometimes we just ignore this and expose the object’s internal, this is true specially when we come up with a limitation such as serialization and persistence in the frameworks that we use.</p><p>Entity Framework as of version six, has some limitations that can be worked around, in this post, I’ll give you some hints on how to apply encapsulation and information hiding on your domain objects, while letting EntityFramework do its work.</p><h2 id="Object-Construction"><a href="#Object-Construction" class="headerlink" title="Object Construction"></a>Object Construction</h2><p>EntityFramework needs a parameterless constructor to construct an object when it needs to instantiate the object before hydrating the object. You might think that you need a public parameterless constructor (a.k.a <a href="http://en.wikipedia.org/wiki/Nullary_constructor">nullary constructor</a>) but that’s not true. You can get away with private constructor. This helps with encapsulation as the object can only be constructed by user of the code (e.g. your application) correctly.</p><figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">Product</span> </span><br><span class="line">&#123;</span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="title">Product</span>(<span class="params"></span>) </span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Product</span>(<span class="params"><span class="built_in">string</span> name</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        Name = name;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="built_in">string</span> Name &#123; <span class="keyword">get</span>; <span class="keyword">private</span> <span class="keyword">set</span>;&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>As you can see from the code, there’s no way you can create an invalid Product object. This class works perfectly fine in EntityFramework as well.</p><h2 id="Collection-Mapping"><a href="#Collection-Mapping" class="headerlink" title="Collection Mapping"></a>Collection Mapping</h2><p>Your domain entities might have collection that need persistence, but when you expose your collection as IList or ICollection, entries can be added directly from the outside world to the collection. Although you can enforce proper construction of the object by using the right constructors, this still doesn’t make it right.</p><p>Let’s take the above Product class as an example. If you want to keep history of the name changes, how would you do that? Here’s one way of doing that:</p><figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br></pre></td><td class="code"><pre><span class="line">    <span class="keyword">public</span> <span class="keyword">class</span> <span class="title">Product</span> </span><br><span class="line">    &#123;</span><br><span class="line">        <span class="function"><span class="keyword">private</span> <span class="title">Product</span>(<span class="params"></span>) </span></span><br><span class="line"><span class="function"></span>        &#123;</span><br><span class="line">            NameHistory = <span class="keyword">new</span> List&lt;ProductNameHistory&gt;();</span><br><span class="line">        &#125;</span><br><span class="line">    </span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="title">Product</span>(<span class="params"><span class="built_in">string</span> name</span>)</span></span><br><span class="line"><span class="function"></span>        &#123;</span><br><span class="line">            Name = name;</span><br><span class="line">        &#125;</span><br><span class="line">    </span><br><span class="line">        <span class="keyword">public</span> <span class="built_in">string</span> Name &#123; <span class="keyword">get</span>; <span class="keyword">private</span> <span class="keyword">set</span>;&#125;</span><br><span class="line">    </span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">ChangeName</span>(<span class="params"><span class="built_in">string</span> newName</span>)</span></span><br><span class="line"><span class="function"></span>        &#123;</span><br><span class="line">            NameHistory.Add(<span class="keyword">new</span> ProductNameHistory(Name, newName));</span><br><span class="line">            Name = newName;</span><br><span class="line">        &#125;</span><br><span class="line">    </span><br><span class="line">        <span class="keyword">private</span> IList&lt;ProductNameHistory&gt; NameHistory &#123; <span class="keyword">get</span>; <span class="keyword">set</span>; &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">class</span> <span class="title">ProductNameHistory</span></span><br><span class="line">    &#123;</span><br><span class="line">        <span class="function"><span class="keyword">private</span> <span class="title">ProductNameHistory</span>(<span class="params"></span>) </span></span><br><span class="line"><span class="function"></span>        &#123;</span><br><span class="line">        &#125;</span><br><span class="line">    </span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="title">ProductNameHistory</span>(<span class="params"><span class="built_in">string</span> oldName, <span class="built_in">string</span> newName</span>)</span></span><br><span class="line"><span class="function"></span>        &#123;</span><br><span class="line">            OldName = oldName;</span><br><span class="line">            NewName = newName;</span><br><span class="line">        &#125;</span><br><span class="line">    </span><br><span class="line">        <span class="keyword">public</span> <span class="built_in">string</span> OldName &#123; <span class="keyword">get</span>; <span class="keyword">private</span> <span class="keyword">set</span>; &#125;</span><br><span class="line">        <span class="keyword">public</span> <span class="built_in">string</span> NewName &#123; <span class="keyword">get</span>; <span class="keyword">private</span> <span class="keyword">set</span>; &#125;</span><br><span class="line">    &#125;</span><br><span class="line">``` </span><br><span class="line"></span><br><span class="line">Now <span class="keyword">this</span> looks fine, except it does <span class="keyword">not</span> work well <span class="keyword">with</span> EntityFramework <span class="keyword">as</span> it won<span class="string">&#x27;t store private collections/lists. A way to get around it is by creating [EntityTypeConfiguration][4] class for your entity, but because the HasMany method accepts an expression, it needs the collection to be public, which brings us back to where we were. As a workaround, you can move your EntityTypeConfiguration class to reside inside the entity, although not ideal, but that way you can access the private members to do the mapping.</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">Also if you still want to expose the collection for reading purposes, you can benefit from not-so-new readonly collection interfaces like `IReadOnlyList&lt;T&gt;` and expose your internal collection as readonly which makes it impossible to manipulate:</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">```cs</span></span><br><span class="line"><span class="string">    public class Product</span></span><br><span class="line"><span class="string">    &#123;</span></span><br><span class="line"><span class="string">        private Product()</span></span><br><span class="line"><span class="string">        &#123;</span></span><br><span class="line"><span class="string">            NameHistory = new List&lt;ProductNameHistory&gt;();</span></span><br><span class="line"><span class="string">        &#125;</span></span><br><span class="line"><span class="string">    </span></span><br><span class="line"><span class="string">        public Product(string name)</span></span><br><span class="line"><span class="string">        &#123;</span></span><br><span class="line"><span class="string">            Name = name;</span></span><br><span class="line"><span class="string">        &#125;</span></span><br><span class="line"><span class="string">    </span></span><br><span class="line"><span class="string">        public string Name &#123; get; private set; &#125;</span></span><br><span class="line"><span class="string">    </span></span><br><span class="line"><span class="string">        public void ChangeName(string newName)</span></span><br><span class="line"><span class="string">        &#123;</span></span><br><span class="line"><span class="string">            NameHistory.Add(new ProductNameHistory(Name, newName));</span></span><br><span class="line"><span class="string">            Name = newName;</span></span><br><span class="line"><span class="string">        &#125;</span></span><br><span class="line"><span class="string">    </span></span><br><span class="line"><span class="string">        private IList&lt;ProductNameHistory&gt; NameHistory &#123; get; set; &#125;</span></span><br><span class="line"><span class="string">    </span></span><br><span class="line"><span class="string">        public IReadOnlyList&lt;ProductNameHistory&gt; History</span></span><br><span class="line"><span class="string">        &#123;</span></span><br><span class="line"><span class="string">            get &#123; return new ReadOnlyCollection&lt;ProductNameHistory&gt;(NameHistory); &#125;</span></span><br><span class="line"><span class="string">        &#125;</span></span><br><span class="line"><span class="string">    </span></span><br><span class="line"><span class="string">        public class ProductEntityTypeConfiguration : EntityTypeConfiguration&lt;Product&gt;</span></span><br><span class="line"><span class="string">        &#123;</span></span><br><span class="line"><span class="string">            public ProductEntityTypeConfiguration()</span></span><br><span class="line"><span class="string">            &#123;</span></span><br><span class="line"><span class="string">                HasMany(c =&gt; c.NameHistory);</span></span><br><span class="line"><span class="string">            &#125;</span></span><br><span class="line"><span class="string">        &#125;</span></span><br><span class="line"><span class="string">    &#125;</span></span><br></pre></td></tr></table></figure><p>Although encapsulation and OO design practices in general are key, there’s more than just that when it comes to properly designing a domain. Since this is more a <a href="http://en.wikipedia.org/wiki/Domain-driven_design">DDD</a> topic, I’ll keep it for another post.</p>]]></content>
    
    
    <summary type="html">&lt;p&gt;One of the four fundamentals of &lt;a href=&quot;http://en.wikipedia.org/wiki/Object-oriented_programming&quot;&gt;Object-Oriented Programing&lt;/a&gt; is &lt;a href=&quot;http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming&quot;&gt;Encapsulation&lt;/a&gt; which is defined as: “A language mechanism for restricting access to some of the object’s components”. This would help us separate the internal implementation from the publicly accessible surface of the object. The idea is to hide how the object actually work from the outside world, so that we can change the internal without breaking anything as the object still looks the same from the outside.&lt;/p&gt;</summary>
    
    
    
    
    <category term="EntityFramework" scheme="http://www.seesharpsoftware.com.au/tags/EntityFramework/"/>
    
    <category term="DDD" scheme="http://www.seesharpsoftware.com.au/tags/DDD/"/>
    
  </entry>
  
  <entry>
    <title>Better Testability with Static Classes</title>
    <link href="http://www.seesharpsoftware.com.au/better-testability-with-static-classes/"/>
    <id>http://www.seesharpsoftware.com.au/better-testability-with-static-classes/</id>
    <published>2014-02-10T19:00:20.000Z</published>
    <updated>2022-05-02T04:01:25.734Z</updated>
    
    <content type="html"><![CDATA[<p>If you’ve been following me, you know by now that recently I’ve been dedicating my extra time enhancing <a href="http://particular.net/ServiceInsight">ServiceInsight</a> application. For those of you living under a rock, it is a part of <a href="http://particular.net/nservicebus">NServiceBus</a> suite of applications and the focus there is to give you a better tooling so that you’ll have a much better experience using NServiceBus framework. Among the few tools we are building are ServicePulse which is designed for DevOps and ServiceInsight which is targeted mostly for average Joe developers. <a id="more"></a> Now these two tools should be able to interact with each other so that when you see there’s an error message in ServicePulse, you can open that message in ServiceInsight and see more developer friendly information regarding that error to find out what has caused it. You can read more about the implementation of this feature <a href="http://docs.particular.net/ServiceInsight/application-invocation">here</a>, but here I’m talking about an issue I had creating and testing it, which hopefully is helpful to someone as well.</p><p>When building the invocation of ServiceInsight, I needed to read passed in parameters through the command line. So everyone with a bit of .NET knowledge knows that you can get the arguments like this:</p><figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">Program</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">Main</span>(<span class="params"><span class="built_in">string</span>[] args</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">    <span class="comment">//args has the arguments passed in.</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>There’s another way of accessing passed in command line arguments, which is probably useful if you’re creating a WPF application or need to access to command line arguments later and not as soon as the app launches. You can access them through System.Environment object and it looks like this:</p><figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">App</span> : <span class="title">Application</span></span><br><span class="line">&#123;</span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">override</span> <span class="keyword">void</span> <span class="title">OnStartup</span>(<span class="params">StartupEventArgs e</span>)</span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line"><span class="keyword">var</span> args = System.Environment.GetCommandLineArgs();</span><br><span class="line"><span class="comment">//Almost the same as before</span></span><br><span class="line">&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>Now how would you test this? I’m aware of all the good Command Line parsing libraries out there, but it’d be an overkill, but you still need to parse the argument, and that’s going to need some unit testing. To make the story short, I came up with a parser and wrap that on an interface, so I had something like this:</p><figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">CommandLineArgParser</span> : <span class="title">ICommandLineArgParser</span></span><br><span class="line">&#123;</span><br><span class="line"><span class="function"><span class="keyword">public</span> ParseResults <span class="title">Parse</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line"><span class="keyword">var</span> args = System.Environment.GetCommandLineArgs();</span><br><span class="line"><span class="comment">//do its thing and return the result</span></span><br><span class="line">&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>Now how would you test this thing? Because of the fact that it is using a static object (here System.Environment) and particularly it is a System object, you can’t just mock that, so how would you write any unit tests to ensure your parsing is doing what you intended?</p><p>First obvious way is to create an interface and a wrapper around the Environment object and then use the interface. That comes with the burden of creating the wrapper, which depending on the situation, is a lot of unnecessary code to write. But is there anther more generic solution? Turns out, there is one!</p><p>How about creating an interface, then on runtime, creating something similar to the wrapper: a class that would implement the interface and then delegate all the calls to the static class? Here’s how you can do it using a Autofac Module:</p><figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title">IEnvironment</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="function"><span class="built_in">string</span>[] <span class="title">GetCommandLineArgs</span>(<span class="params"></span>)</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">InterfacesModule</span> : <span class="title">Module</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">readonly</span> ProxyGenerator _generator;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">InterfacesModule</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        _generator = <span class="keyword">new</span> ProxyGenerator();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">override</span> <span class="keyword">void</span> <span class="title">Load</span>(<span class="params">ContainerBuilder builder</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        builder.RegisterInstance(GenerateInterfaceProxyForType&lt;IEnvironment&gt;(<span class="keyword">typeof</span> (Environment))).As&lt;IEnvironment&gt;();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="built_in">object</span> <span class="title">GenerateInterfaceProxyForType</span>&lt;<span class="title">T</span>&gt;(<span class="params">Type implementation</span>) <span class="keyword">where</span> T : <span class="keyword">class</span></span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        <span class="keyword">return</span> _generator.CreateInterfaceProxyWithoutTarget&lt;T&gt;(<span class="keyword">new</span> CallForwarderInterceptor(implementation));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">CallForwarderInterceptor</span> : <span class="title">IInterceptor</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">readonly</span> <span class="built_in">object</span> _target;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">readonly</span> Type _targetType;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">CallForwarderInterceptor</span>(<span class="params">Type targetType</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        _targetType = targetType;</span><br><span class="line">        _target = <span class="literal">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">CallForwarderInterceptor</span>(<span class="params"><span class="built_in">object</span> target</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        _targetType = target.GetType();</span><br><span class="line">        _target = target;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">Intercept</span>(<span class="params">IInvocation invocation</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        <span class="keyword">var</span> targetMethod = invocation.Method;</span><br><span class="line">        <span class="keyword">var</span> argumentTypes = invocation.Arguments.Select(a =&gt; a.GetType()).ToArray();</span><br><span class="line">        <span class="keyword">var</span> matchingTypeMethods = _targetType.GetMethods().Where(m =&gt;</span><br><span class="line">        &#123;</span><br><span class="line">            <span class="keyword">var</span> parameterInfos = m.GetParameters();</span><br><span class="line"></span><br><span class="line">            <span class="keyword">return</span> m.Name == targetMethod.Name &amp;&amp;</span><br><span class="line">                             argumentTypes.Length == parameterInfos.Length &amp;&amp;</span><br><span class="line">                             parameterInfos.Select((p, i) =&gt; <span class="keyword">new</span> &#123; p.ParameterType, Index = i &#125;)</span><br><span class="line">                                           .All(p =&gt; p.ParameterType.IsAssignableFrom(argumentTypes[p.Index]));</span><br><span class="line">        &#125;).ToList();</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (matchingTypeMethods.Count == <span class="number">0</span>) <span class="keyword">return</span>;</span><br><span class="line"></span><br><span class="line">        <span class="built_in">object</span> result;</span><br><span class="line">        <span class="keyword">if</span> (targetMethod.IsGenericMethod)</span><br><span class="line">        &#123;</span><br><span class="line">            result = matchingTypeMethods.Single(m =&gt; m.IsGenericMethodDefinition)</span><br><span class="line">                                        .MakeGenericMethod(targetMethod.GetGenericArguments())</span><br><span class="line">                                        .Invoke(_target, invocation.Arguments);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">else</span></span><br><span class="line">        &#123;</span><br><span class="line">            result = matchingTypeMethods.Single(m =&gt; !m.IsGenericMethodDefinition).Invoke(_target, invocation.Arguments);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        invocation.ReturnValue = result;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>The magic is in the CallForwarderInterceptor, which is a <a href="http://www.castleproject.org/projects/dynamicproxy">DynamicProxy</a> interceptor. What it does is that it generates a proxy to the interface and when you make a method call at runtime on the proxy object (the interface), it looks for a method with exact matching arguments and output and then it’d call that method, get the result and return it as a part of the original method call. Pretty neat, if you ask me. The implementation posted here, works with either generic or non-generic classes alike and is not limited only to static classes.</p>]]></content>
    
    
    <summary type="html">&lt;p&gt;If you’ve been following me, you know by now that recently I’ve been dedicating my extra time enhancing &lt;a href=&quot;http://particular.net/ServiceInsight&quot;&gt;ServiceInsight&lt;/a&gt; application. For those of you living under a rock, it is a part of &lt;a href=&quot;http://particular.net/nservicebus&quot;&gt;NServiceBus&lt;/a&gt; suite of applications and the focus there is to give you a better tooling so that you’ll have a much better experience using NServiceBus framework. Among the few tools we are building are ServicePulse which is designed for DevOps and ServiceInsight which is targeted mostly for average Joe developers.</summary>
    
    
    
    
    <category term="DynamicProxy" scheme="http://www.seesharpsoftware.com.au/tags/DynamicProxy/"/>
    
  </entry>
  
  <entry>
    <title>SQL Server Transport for NServiceBus</title>
    <link href="http://www.seesharpsoftware.com.au/sql-server-transport-for-nservicebus/"/>
    <id>http://www.seesharpsoftware.com.au/sql-server-transport-for-nservicebus/</id>
    <published>2013-09-16T00:10:13.000Z</published>
    <updated>2022-05-02T04:01:29.213Z</updated>
    
    <content type="html"><![CDATA[<p>You may have noticed in NServiceBus release note that there are a few <a href="http://particular.net/blog/nservicebus-v4.0-release-notes">new transports available on v4.0</a>. This means you no longer need to choose MSMQ as your transport and can choose from other well reputed queue engines such as ActiveMQ and RabbitMQ. <a id="more"></a> But among all, and even more interestingly, there’s another transport called Sql Transport. Yes, you heard it right! It actually uses a Sql Server database to store the messages and it basically mimics the Queue. You may well argue that putting something - here the database - in the middle of everything is more of a broker architecture and not a Bus, wouldn’t that make the name - NServiceBus - irrelevant? What’s going on? The reasoning behind it is that although this “is” a broker architecture, you may still find yourself in situations where you want to use a database to store your messages, your sagas as well as your application required data. Whatever the reason, fret not, NServiceBus got all your bases covered. Let’s see how you use this transport and how it behaves.</p><p>Whether you use NServiceBus host or run in in-proc you can use the SqlTransport, but configuration is a bit different. To configure your endpoint when running using the host, you simple need an aditional interface on your EndpointConfig class.</p><figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">EndpointConfig</span> : <span class="title">IConfigureThisEndpoint</span>, <span class="title">AsA_Publisher</span>, <span class="title">UsingTransport</span>&lt;<span class="title">SqlServer</span>&gt; &#123; &#125;</span><br></pre></td></tr></table></figure><p>To do the same thing when running the bus in-proc you need to use fluent configuration:</p><figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">Init</span>(<span class="params"></span>) </span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    NServiceBus.Configure</span><br><span class="line">               .With()</span><br><span class="line">               .DefaultBuilder()</span><br><span class="line">               .UseTransport&lt;SqlServer&gt;(<span class="string">&quot;YourOptionalConnectionStringName&quot;</span>) </span><br><span class="line">               .UnicastBus()</span><br><span class="line">               .CreateBus();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>Once application is started, if you have auto installation of queues enabled, it will generate required tables for you, including Audit and Error queue/tables.</p><p><img src="/images/BlogPics/QueueTables.png" alt="Queue Tables"></p><p>Now suppose something has gone wrong, you have fixed the problem, and you need to return the message to the original queue to process it again, what should you do? You probably have used “ReturnToSource” executable or the Powershell CmdLet, but as bad as it sounds, it is not going to help you here, but fret not! Since you use a database, it should be trivial to remove a record from one table and insert it in another table, right? If you don’t think so, <a href="https://github.com/jerrosenberg/NServiceBus/commit/9dbb2a7d6b162607a5f1b134013fc7e0c0e0ebbf">this StoredProc</a> should be good enough to get you started but if you are looking for better tooling, <a href="http://particular.net/serviceinsight">ServiceInsight</a> (already pre-release) supports returning the message to the source queue functionality and is transport agnostic.</p>]]></content>
    
    
    <summary type="html">&lt;p&gt;You may have noticed in NServiceBus release note that there are a few &lt;a href=&quot;http://particular.net/blog/nservicebus-v4.0-release-notes&quot;&gt;new transports available on v4.0&lt;/a&gt;. This means you no longer need to choose MSMQ as your transport and can choose from other well reputed queue engines such as ActiveMQ and RabbitMQ.</summary>
    
    
    
    
    <category term="NServiceBus" scheme="http://www.seesharpsoftware.com.au/tags/NServiceBus/"/>
    
  </entry>
  
  <entry>
    <title>ServiceInsight for NServiceBus Beta-2 Available Now</title>
    <link href="http://www.seesharpsoftware.com.au/serviceinsight-for-nservicebus-beta-two-available-now/"/>
    <id>http://www.seesharpsoftware.com.au/serviceinsight-for-nservicebus-beta-two-available-now/</id>
    <published>2013-07-26T13:01:01.000Z</published>
    <updated>2022-05-02T04:01:32.876Z</updated>
    
    <content type="html"><![CDATA[<p>If you’ve been following this blog, you’ve noticed that it has gone radio silent for some time. The reason was that I was spending most of my time on developing <a href="http://particular.net/ServiceInsight">ServiceInsight</a> application. I’m happy to announce that Beta-2 is now available and you can <a href="http://particular.net/downloads">grab it from here</a>. <a id="more"></a></p><h2 id="History"><a href="#History" class="headerlink" title="History"></a>History</h2><p>Allow me to give you some background on where <a href="http://particular.net/ServiceInsight">ServiceInsight</a> came from. If you have used <a href="http://particular.net/nservicebus">NServiceBus</a> - or any other tool relying on <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms711472(v=vs.85).aspx">MSMQ</a> transport - you must have used the limited built-in MSMQ tooling (if you can even call it that) that comes out of the box. It is so annoying even if you want to simply see a message in the queue. To top it off, if you have an error in your messaging system, like an exception in the message processing pipeline, you won’t even find out why by looking at the message/queue and probably have to check your logs to find out why something is not working, because in this case NServiceBus keeps that extra data as a part of the message header and it is not in the message body in the first place. So fed up with all the problems, I started creating a tool that could help develop my NServiceBus based solution easier.</p><p>The initial version which was more of a proof of concept, provided not only viewing of the messages in the queue, but more generic operations like creating queues, purging queues, and removing messages. After starting to building on top of just basic queue management functionality, the great minds behind NServiceBus came up with even a better solution! Why directly interface with the transports like MSMQ? It has its own limitations and you need to <a href="http://particular.net/blog/nservicebus-v4.0-release-notes">support multiple transports</a> just like NServiceBus does. That’s how <a href="https://github.com/NServiceBus/Management">Management API</a> came into existence. It is a <a href="http://en.wikipedia.org/wiki/Representational_state_transfer">RESTful API</a> that’d allow you query the endpoints and messages in the system and ServiceInsight, among other tools, uses that to achieve the same functionality that I created for MSMQ, and even more. The good thing is that, going forward it’d support all other NServiceBus transports so you’d have seamless functionality regardless of the transport you choose, but there’s also a caveat: this is only available if you use NServiceBus v4.0 and higher.</p><h2 id="What-is-ServiceInsight"><a href="#What-is-ServiceInsight" class="headerlink" title="What is ServiceInsight?"></a>What is ServiceInsight?</h2><p>Current beta version contains features that a developer would use on a daily basis. Things like viewing a message body in a queue, the header information and even ability to search for a specific message based on the Id or a field inside the message body is also there and it all should make your life as a developer lot easier. There’s also a killer feature: Ever wondered what has caused message x to be generated? Every developer with his share of asynchronous messaging knows how hard it may be to find out what’s going on just by looking at the code or messages coming and going out of the system. The good thing is that now ServiceInsight would give you the big picture:</p><p><img src="/images/BlogPics/ServiceInsight.png" alt="ServiceInsight"></p><p>So you can see why a message was generated, how much time processing of the message has taken and even see that it has ended up with an error. This all should boost up your productivity.</p><h2 id="Do-I-have-to-use-the-latest"><a href="#Do-I-have-to-use-the-latest" class="headerlink" title="Do I have to use the latest?"></a>Do I have to use the latest?</h2><p>You’d still get some benefits from ServiceInsight even if you’re on previous versions of NServiceBus. The Queue Explorer, as we call it, would give you almost all MSMQ tooling that you need, but naturally since it uses MSMQ api under the hood, it comes with its limitation too, so you may not be able to connect to a remote queue if you don’t have proper permission on your domain setup, or if you don’t have MSMQ installed locally. Since the main audience of this tool at this stage are the developers, the limitations should not be surprising. Having said that, we strongly urge you to try the latest and greatest of what NServiceBus offers so that you can also use ServiceInsight at its best.</p><h2 id="What’s-vNext"><a href="#What’s-vNext" class="headerlink" title="What’s vNext?"></a>What’s vNext?</h2><p>There are a lot in the works for ServiceInsight already. As I mentioned, next versions will support other transports like <a href="http://activemq.apache.org/">ActiveMQ</a>, <a href="http://www.rabbitmq.com/">RabbitMQ</a> and even the SQL Transport. More useful information for messages and endpoints will be surfaced through ServiceInsight as well as visualization of SLAs and message processing timeline so that you have all those information at your fingertips.</p><p>Should you happen to use ServiceInsight, we really appreciate your feedbacks and thoughts and the feature you’d like to see in vNext, so keep them coming!</p><p>If you’re interested in seeing a short introductory video on ServiceInsight to find out more about it and see major features of v1.0, you can check out <a href="http://player.vimeo.com/video/68326113?title=0&amp;byline=0&amp;portrait=0&amp;autoplay=1">this video</a>.</p>]]></content>
    
    
    <summary type="html">&lt;p&gt;If you’ve been following this blog, you’ve noticed that it has gone radio silent for some time. The reason was that I was spending most of my time on developing &lt;a href=&quot;http://particular.net/ServiceInsight&quot;&gt;ServiceInsight&lt;/a&gt; application. I’m happy to announce that Beta-2 is now available and you can &lt;a href=&quot;http://particular.net/downloads&quot;&gt;grab it from here&lt;/a&gt;.</summary>
    
    
    
    
    <category term="NServiceBus" scheme="http://www.seesharpsoftware.com.au/tags/NServiceBus/"/>
    
    <category term="ServiceInsight" scheme="http://www.seesharpsoftware.com.au/tags/ServiceInsight/"/>
    
  </entry>
  
  <entry>
    <title>DevExpress Scheduler and Hijri Shamsi Calendar</title>
    <link href="http://www.seesharpsoftware.com.au/devexpress-scheduler-and-hijri-shamsi-calendar/"/>
    <id>http://www.seesharpsoftware.com.au/devexpress-scheduler-and-hijri-shamsi-calendar/</id>
    <published>2012-07-11T04:19:24.000Z</published>
    <updated>2022-05-02T04:01:36.377Z</updated>
    
    <content type="html"><![CDATA[<p>The level of customization that Silverlight comes with - even when you don’t have access to the source code of the control you are using - is simply amazing. Those who experienced WinForms control customization or control centric web frameworks like ASP.NET already know how much trouble they face when customizing a 3rd party control, if there is any customization support at all. <a id="more"></a> In fact people have been asking <a href="http://www.devexpress.com/">DevExpress</a> to add RightToLeft support to their WinForms suite of controls, which is <a href="https://twitter.com/JMBucknall/status/202179721969143808">not going to happen</a> for the same reason: it is hard to modify how a control looks without touching the other behavioral logics inside because those two are mixed together. Since in Silverlight and WPF the logic is completely kept separate from the presentation, you could twist the look and feel and make the control look how you want it to look.</p><p>A good example would be adding <a href="http://en.wikipedia.org/wiki/Iranian_calendars">Hijri Shamsi calendar</a> support to DevExpress scheduler controls. This now can be done by retemplating the whole Scheduler control and using date calculation support of my <a href="https://github.com/HEskandari/FarsiLibrary">FarsiLibrary</a> project. The best part is that unlike WinForms, the source code is not needed at all and you can apply this to the out of the box control directly.</p><p><img src="/images/BlogPics/DXCalendar.png" alt="DevExpress Scheduler control with Farsi / Hijri Shamsi calendar support"></p><p>Microsoft abandoning Silverlight platform in favour of HTML 5 makes my heart ache. Will there be that level of customization support in HTML 5 applications (and controls, maybe someday) is left to be seen.</p>]]></content>
    
    
    <summary type="html">&lt;p&gt;The level of customization that Silverlight comes with - even when you don’t have access to the source code of the control you are using - is simply amazing. Those who experienced WinForms control customization or control centric web frameworks like ASP.NET already know how much trouble they face when customizing a 3rd party control, if there is any customization support at all.</summary>
    
    
    
    
    <category term="DevExpress" scheme="http://www.seesharpsoftware.com.au/tags/DevExpress/"/>
    
    <category term="FasriLibrary" scheme="http://www.seesharpsoftware.com.au/tags/FasriLibrary/"/>
    
  </entry>
  
  <entry>
    <title>Deferred Message Processing in NServiceBus</title>
    <link href="http://www.seesharpsoftware.com.au/deferred-message-processing-in-nservicebus/"/>
    <id>http://www.seesharpsoftware.com.au/deferred-message-processing-in-nservicebus/</id>
    <published>2012-06-27T15:54:25.000Z</published>
    <updated>2022-05-02T04:01:18.092Z</updated>
    
    <content type="html"><![CDATA[<p>When working on a project using <a href="http://www.nservicebus.com/">NServiceBus</a>, we came up with an interesting requirement. The messages in the queue should be processed only in certain time frames. The reason is that message handler is making a webservice call and the other party is only available at certain times and system is not even allowed to make a call during the outage window. <a id="more"></a> You can easily achieve this using Bus.Defer feature in version 3.0 of NServiceBus, but that would put the message at the back of the queue and would change the order of the messages which was very important from business perspective in our case. So we had to roll up our sleeves and dig a bit deeper. It turned out NServiceBus is using an ITransport interface to process the messages in the queue. The implementation that comes with NServiceBus is named TransactionalTransport. This is the class that handles the processing threads under the hood, so what if we set the number of processing threads to zero for a while, and when we need to resume processing, set it back to the default value (one or more threads)?</p><p><a href="http://www.udidahan.com/">Udi</a> suggests that you shouldn’t actually use this, if possible. Instead send the message to the remote queue and let the other end worry about how and when to process it, but this may not work if you’re working in a locked down environment or your customer would simply play it by their rules.</p><p>Okay here’s the code snippet if you’re interested.</p><figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">abstract</span> <span class="keyword">class</span> <span class="title">BaseCommandHandler</span>&lt;<span class="title">T</span>&gt; : <span class="title">IHandleMessages</span>&lt;<span class="title">T</span>&gt;</span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">private</span> TimeSpan _wait = TimeSpan.FromSeconds(<span class="number">30</span>);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> TimeSpan DefaultWait</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">get</span> &#123; <span class="keyword">return</span> _wait; &#125;</span><br><span class="line">        <span class="keyword">set</span> &#123; _wait = <span class="keyword">value</span>; &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">virtual</span> IBus Bus &#123; <span class="keyword">get</span>; <span class="keyword">set</span>; &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">virtual</span> ITransport Transport &#123; <span class="keyword">get</span>; <span class="keyword">set</span>; &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">virtual</span> <span class="keyword">void</span> <span class="title">Handle</span>(<span class="params">T message</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        <span class="keyword">if</span> (CanProcessMessage())</span><br><span class="line">        &#123;</span><br><span class="line">            ProcessMessage(message);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">else</span></span><br><span class="line">        &#123;</span><br><span class="line">            PauseProcessing(DefaultWait);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">abstract</span> <span class="keyword">void</span> <span class="title">ProcessMessage</span>(<span class="params">T message</span>)</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">virtual</span> <span class="built_in">bool</span> <span class="title">CanProcessMessage</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">PauseProcessing</span>(<span class="params"><span class="built_in">double</span> interval</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        Transport.PauseProcessing();</span><br><span class="line">        Spin(interval);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">Spin</span>(<span class="params"><span class="built_in">double</span> interval</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        <span class="keyword">var</span> timer = <span class="keyword">new</span> Timer(interval) &#123; Enabled = <span class="literal">true</span> &#125;;</span><br><span class="line">        timer.Elapsed += OnSpinnigFinished;</span><br><span class="line">        timer.Start();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">OnSpinnigFinished</span>(<span class="params"><span class="built_in">object</span> sender, ElapsedEventArgs elapsedEventArgs</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        <span class="keyword">var</span> timer = (Timer) sender;</span><br><span class="line">        timer.Enabled = <span class="literal">false</span>;</span><br><span class="line">        timer.Dispose();</span><br><span class="line">        Transport.ResumeProcessing();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">class</span> <span class="title">TransportExtensions</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">PauseProcessing</span>(<span class="params"><span class="keyword">this</span> ITransport transport</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        transport.AbortHandlingCurrentMessage();</span><br><span class="line">        transport.ChangeNumberOfWorkerThreads(<span class="number">0</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">ResumeProcessing</span>(<span class="params"><span class="keyword">this</span> ITransport transport</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        transport.ChangeNumberOfWorkerThreads(<span class="number">1</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>]]></content>
    
    
    <summary type="html">&lt;p&gt;When working on a project using &lt;a href=&quot;http://www.nservicebus.com/&quot;&gt;NServiceBus&lt;/a&gt;, we came up with an interesting requirement. The messages in the queue should be processed only in certain time frames. The reason is that message handler is making a webservice call and the other party is only available at certain times and system is not even allowed to make a call during the outage window.</summary>
    
    
    
    
    <category term="NServiceBus" scheme="http://www.seesharpsoftware.com.au/tags/NServiceBus/"/>
    
  </entry>
  
</feed>
