<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
  <title>Ajeet Yelandur&#39;s Blog</title>
  
  <subtitle>Discovering code</subtitle>
  <link href="/atom.xml" rel="self"/>
  
  <link href="https://www.ajeetyelandur.com/"/>
  <updated>2019-12-08T12:34:21.379Z</updated>
  <id>https://www.ajeetyelandur.com/</id>
  
  <author>
    <name>Ajeet Yelandur</name>
    
  </author>
  
  <generator uri="http://hexo.io/">Hexo</generator>
  
  <entry>
    <title>Allow anonymous SPA users to access secure resources</title>
    <link href="https://www.ajeetyelandur.com/2019/12/Allow-anonymous-SPA-users-to-access-secure-resources/"/>
    <id>https://www.ajeetyelandur.com/2019/12/Allow-anonymous-SPA-users-to-access-secure-resources/</id>
    <published>2019-12-08T12:00:14.000Z</published>
    <updated>2019-12-08T12:34:21.379Z</updated>
    
    <content type="html"><![CDATA[<p>I don’t know how many of you have faced this dilemma where your SPA has to access protected resources outside its domain before the user has logged in? Let’s say, you need to display products to all users, whether signed-in or not. You have a Products API which is protected using OAuth2 Client Credentials flow. For security reasons you don’t want to publish this API with anonymous access, but still allow anonymous users to benefit from it. The client would be configured to use OAuth2 Implicit/Hybrid Flow.<br>Below is a standard flow of Client Credentials.</p><figure class="half-width"><img src="/images/201912/oauth2_cc.jpg" alt="OAuth2 Client Credentials Flow" title="Client Credentials Sequence diagram"></figure><p>The SPA will have access token only when the user has logged in to the Authorisation server. The client can access the  protected API using the access token which has the required scope. We are not speaking of token management here, but client secret management.</p><p>Now when a user is still anonymous, we still need to provide them with data from our API. Secret management on client side is not a viable option. The only place client secret can be safely stored is with a trusted client which runs on the server side.<br>There is an active doc by IETF which guides you on using OAuth with browser based apps <a href="https://tools.ietf.org/html/draft-ietf-oauth-browser-based-apps-04" target="_blank" rel="noopener">here</a>. Based on their recommendation at <a href="https://tools.ietf.org/html/draft-ietf-oauth-browser-based-apps-04#section-6.2" target="_blank" rel="noopener">6.2</a> we can move the authentication and token management to the ASP.NET Core app which shares the domain with the SPA. The token/session management would be done by Cookies with HttpOnly and Lax or Strict SameSite mode. Check out this <a href="https://devblogs.microsoft.com/aspnet/upcoming-samesite-cookie-changes-in-asp-net-and-asp-net-core" target="_blank" rel="noopener">blog</a> for more details on SameSite Cookie.</p><p>This way we are moving all the authentication to the server and a machine to machine communication takes place through which a token is requested on behalf of the clients.<br>The <a href="https://samnewman.io/patterns/architectural/bff/" target="_blank" rel="noopener">BFF</a> (Backend for front end) architecture is more common with Microservices and sometime also referred to as <a href="https://microservices.io/patterns/apigateway.html" target="_blank" rel="noopener">API Gateway</a>. Personally, in this scenario I would lean more towards calling this as a BFF pattern since this nomenclature makes the intent more clearer that we are introducing this API specifically for a front-end, namely SPA.</p><p>Let us see what goes in to implement such an API.<br>In the same ASP.NET Core site which serves the static content you can setup session management and forwarding the requests to the backend API along with attaching a valid access token.<br>In Startup.cs<br><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><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">const</span> <span class="keyword">string</span> Authority_TokenEndpoint = <span class="string">"http://localhost:62000/connect/token"</span>;</span><br><span class="line"><span class="keyword">private</span> <span class="keyword">const</span> <span class="keyword">string</span> token_cookie_name = <span class="string">"code.token"</span>;</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.Configure&lt;CookiePolicyOptions&gt;(options =&gt;</span><br><span class="line">    &#123;</span><br><span class="line">        options.HttpOnly = Microsoft.AspNetCore.CookiePolicy.HttpOnlyPolicy.Always;</span><br><span class="line">        options.MinimumSameSitePolicy = SameSiteMode.Strict;</span><br><span class="line">    &#125;);</span><br><span class="line">    services.AddHttpClient();</span><br><span class="line">    services.AddProxy();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p><p>You might have noticed  line AddProxy(). This is from <a href="https://github.com/damianh/ProxyKit" target="_blank" rel="noopener">ProxyKit</a>. A light-weight, code-first HTTP reverse proxy. In this case it deals with the mundane task of forwarding requests to the back-end API with ease and style. It is very powerfull and you can do a lot more with it.<br>Let is see how we use it next.<br><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><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></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">Configure</span>(<span class="params">IApplicationBuilder app, IHostingEnvironment env</span>)</span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">app.UseCookiePolicy();</span><br><span class="line"><span class="keyword">string</span> tokenForCookie = <span class="string">""</span>;</span><br><span class="line">app.Use(<span class="keyword">async</span> (context, next) =&gt;</span><br><span class="line">&#123;</span><br><span class="line"><span class="comment">// get access token</span></span><br><span class="line"><span class="keyword">var</span> factory = app.ApplicationServices.GetRequiredService&lt;IHttpClientFactory&gt;();</span><br><span class="line"><span class="keyword">var</span> client = factory.CreateClient();</span><br><span class="line"><span class="keyword">var</span> tokenResponse = <span class="keyword">await</span> client.RequestClientCredentialsTokenAsync(</span><br><span class="line">            <span class="keyword">new</span> ClientCredentialsTokenRequest</span><br><span class="line">&#123;</span><br><span class="line">Address = Authority_TokenEndpoint,</span><br><span class="line"></span><br><span class="line">ClientId = <span class="string">"securebff"</span>,</span><br><span class="line">ClientSecret = <span class="string">"secret"</span>,</span><br><span class="line">Scope = <span class="string">"externalapi"</span></span><br><span class="line">&#125;);</span><br><span class="line"><span class="comment">// check if we have a valid response</span></span><br><span class="line">tokenForCookie = tokenResponse.AccessToken;</span><br><span class="line"><span class="keyword">var</span> expiresin = DateTime.Now.AddSeconds(tokenResponse.ExpiresIn);</span><br><span class="line"><span class="comment">// save to cookie</span></span><br><span class="line">CookieOptions options = <span class="keyword">new</span> CookieOptions</span><br><span class="line">&#123;</span><br><span class="line">IsEssential = <span class="literal">true</span>,</span><br><span class="line">HttpOnly = <span class="literal">true</span>,</span><br><span class="line">SameSite = SameSiteMode.Strict,</span><br><span class="line">Secure = env.IsDevelopment() ? <span class="literal">false</span> : <span class="literal">true</span>,</span><br><span class="line">Expires = expiresin</span><br><span class="line">&#125;;</span><br><span class="line">context.Response.Cookies.Append(token_cookie_name, tokenForCookie, options);</span><br><span class="line"><span class="keyword">await</span> next();</span><br><span class="line">&#125;);</span><br><span class="line">app.Map(<span class="string">"/external"</span>, api =&gt;</span><br><span class="line">&#123;</span><br><span class="line">api.RunProxy(<span class="keyword">async</span> context =&gt;</span><br><span class="line">&#123;</span><br><span class="line"><span class="keyword">var</span> forwardContext = context.ForwardTo(<span class="string">"http://localhost:5000/api/test"</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> token = <span class="keyword">string</span>.IsNullOrEmpty(tokenForCookie) </span><br><span class="line">            ? context.Request.Cookies[token_cookie_name] </span><br><span class="line">            : tokenForCookie;</span><br><span class="line"></span><br><span class="line">forwardContext.UpstreamRequest.SetBearerToken(token);</span><br><span class="line">forwardContext.AddXForwardedHeaders();</span><br><span class="line"><span class="comment">// add retry on 401 or other conditions</span></span><br><span class="line"><span class="keyword">var</span> response = <span class="keyword">await</span> forwardContext.Send();</span><br><span class="line"><span class="keyword">return</span> response;</span><br><span class="line">&#125;);</span><br><span class="line">&#125;);</span><br><span class="line">app.UseStaticFiles();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p><p>That’s it! As we receive a request, it creates a new token. Here I am using <code>IdentityModel.Client</code> to retrieve an access token from the STS end-point. It creates a cookie with the provided options and saves the token. If the request is for an external API protected by the access token, then the map would attach the current access token and forward the request to the external API and return the response.<br>Of course I have omitted checks like cookie existence, token expiration and skipping token retrieval for every requests for brevity. Also the STS and external API are not shown here, but there is nothing different about them here.</p><p>For completeness here is the new flow.</p><figure class="half-width"><img src="/images/201912/oauth2_cc_bff.jpg" alt="OAuth2 Client Credentials Flow with BFF" title="Client Credentials BFF Sequence diagram"></figure><p>Some parting notes to consider. The activation of BFF component need not be that long when the token is retrieved from the cookie for subsequent requests. The SameSite cookie helps in stopping CSRF attacks. I am not sure if this completely shields you in XSS attacks. You would be adding additional server round-trips. It’s for you to decide if this choice suits your architecture.</p>]]></content>
    
    <summary type="html">
    
      
      
        &lt;p&gt;I don’t know how many of you have faced this dilemma where your SPA has to access protected resources outside its domain before the user 
      
    
    </summary>
    
    
      <category term="Security" scheme="https://www.ajeetyelandur.com/tags/Security/"/>
    
      <category term="Architecture" scheme="https://www.ajeetyelandur.com/tags/Architecture/"/>
    
      <category term="OAuth2" scheme="https://www.ajeetyelandur.com/tags/OAuth2/"/>
    
      <category term="DotNet Core" scheme="https://www.ajeetyelandur.com/tags/DotNet-Core/"/>
    
  </entry>
  
  <entry>
    <title>Entity Framework Core Owned Types explained</title>
    <link href="https://www.ajeetyelandur.com/2018/05/EF-Core-Owned-Types-explained/"/>
    <id>https://www.ajeetyelandur.com/2018/05/EF-Core-Owned-Types-explained/</id>
    <published>2018-05-04T03:40:00.000Z</published>
    <updated>2019-06-27T09:12:14.817Z</updated>
    
    <content type="html"><![CDATA[<p>Owned entity was made available from EF Core 2.0 onwards. The same .NET type can be shared among different entities. Owned entities would not have a key or identity property of their own, but would always be a navigational property of another entity. In DDD we could see this as a value/complex type. For those coming from EF 6, you may see a similarity with complex types in your model. But the way it works and behaves in EF Core is different. There are some gotchas you need to watch out for. We’ll explore these in detail here.</p><p>Let us work with a model shown below<br><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><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">Student</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">int</span> Id &#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">string</span> Name &#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> Address Home &#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">Address</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">string</span> Street &#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">string</span> City &#123; <span class="keyword">get</span>; <span class="keyword">set</span>; &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p><p>Here <code>Student</code> owns <code>Address</code> which is the owned type and does not have its own identity property.  <code>Address</code> becomes a navigation property on <code>Student</code> and would always have an one-to-one relationship (at least for now).</p><p>The <code>DbContext</code> would be defined like this:<br><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><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">StudentContext</span> : <span class="title">DbContext</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">public</span> DbSet&lt;Student&gt; Students &#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">ModelBuilder modelBuilder</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        modelBuilder.Entity&lt;Student&gt;()</span><br><span class="line">            .OwnsOne(s =&gt; s.Home);</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">OnConfiguring</span>(<span class="params">DbContextOptionsBuilder optionsBuilder</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        optionsBuilder.UseSqlServer(<span class="string">"Server=(localdb)\\mssqllocaldb;Database=StudentDb; Trusted_Connection=True;App=StudentContext"</span>);</span><br><span class="line">        optionsBuilder.EnableSensitiveDataLogging();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p><p>An owned type cannot have a <code>DbSet&lt;&gt;</code> and <code>OnModelCreating</code> you can specify the Home property as Owned Entity of <code>Student</code>.</p><p>Home would be mapped to the same table as <code>Student</code>.</p><p>Let us fire up this model and see it working.</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><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="keyword">using</span> Microsoft.EntityFrameworkCore.Infrastructure;</span><br><span class="line"><span class="keyword">using</span> Microsoft.Extensions.Logging;</span><br><span class="line"></span><br><span class="line"><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">static</span> <span class="keyword">void</span> <span class="title">Main</span>(<span class="params"><span class="keyword">string</span>[] args</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        <span class="keyword">var</span> _context = <span class="keyword">new</span> StudentContext();</span><br><span class="line">        _context.GetService&lt;ILoggerFactory&gt;().AddConsole();</span><br><span class="line">        _context.Database.EnsureDeleted();</span><br><span class="line">        _context.Database.EnsureCreated();</span><br><span class="line"></span><br><span class="line">        InsertStudent(_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">static</span> <span class="keyword">void</span> <span class="title">InsertStudent</span>(<span class="params">StudentContext context</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        <span class="keyword">var</span> student = <span class="keyword">new</span> Student</span><br><span class="line">        &#123;</span><br><span class="line">            Name = <span class="string">"Student_1"</span>,</span><br><span class="line">            Home = <span class="keyword">new</span> Address</span><br><span class="line">            &#123;</span><br><span class="line">                Street = <span class="string">"Circular Quay"</span>,</span><br><span class="line">                City = <span class="string">"Sydney"</span></span><br><span class="line">            &#125;</span><br><span class="line">        &#125;;</span><br><span class="line">        context.Students.Add(student);</span><br><span class="line">        context.SaveChanges();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>I have added Microsoft.EntityFrameworkCore.SqlServer and Microsoft.Extensions.Logging.Console packages.<br>From the console logs we see that we have Students table created and a row inserted.<br><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></pre></td><td class="code"><pre><span class="line"><span class="keyword">CREATE</span> <span class="keyword">TABLE</span> [Students] (</span><br><span class="line">    [<span class="keyword">Id</span>] <span class="built_in">int</span> <span class="keyword">NOT</span> <span class="literal">NULL</span> <span class="keyword">IDENTITY</span>,</span><br><span class="line">    [<span class="keyword">Name</span>] <span class="keyword">nvarchar</span>(<span class="keyword">max</span>) <span class="literal">NULL</span>,</span><br><span class="line">    [Home_City] <span class="keyword">nvarchar</span>(<span class="keyword">max</span>) <span class="literal">NULL</span>,</span><br><span class="line">    [Home_Street] <span class="keyword">nvarchar</span>(<span class="keyword">max</span>) <span class="literal">NULL</span>,</span><br><span class="line">    <span class="keyword">CONSTRAINT</span> [PK_Students] PRIMARY <span class="keyword">KEY</span> ([<span class="keyword">Id</span>])</span><br><span class="line">);</span><br></pre></td></tr></table></figure></p><p>To query, just get the students and the owned entity is also included.<br><figure class="highlight csharp"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> students = _context.Students.ToList();</span><br></pre></td></tr></table></figure></p><p>We can also store <code>Address</code> in another table, which we can’t do with complex types in EF6. Simply call <code>.ToTable()</code> and provide a different name.<br><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></pre></td><td class="code"><pre><span class="line">modelBuilder.Entity&lt;Student&gt;()</span><br><span class="line">    .OwnsOne(s =&gt; s.Home)</span><br><span class="line">    .ToTable(<span class="string">"HomeAddress"</span>);</span><br></pre></td></tr></table></figure></p><p>Now when you run the app, you would see 2 tables being created. Note the identity column for the HomeAddress table. It is referencing Students table’s identity.<br><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></pre></td><td class="code"><pre><span class="line"><span class="keyword">CREATE</span> <span class="keyword">TABLE</span> [Students] (</span><br><span class="line">    [<span class="keyword">Id</span>] <span class="built_in">int</span> <span class="keyword">NOT</span> <span class="literal">NULL</span> <span class="keyword">IDENTITY</span>,</span><br><span class="line">    [<span class="keyword">Name</span>] <span class="keyword">nvarchar</span>(<span class="keyword">max</span>) <span class="literal">NULL</span>,</span><br><span class="line">    <span class="keyword">CONSTRAINT</span> [PK_Students] PRIMARY <span class="keyword">KEY</span> ([<span class="keyword">Id</span>])</span><br><span class="line">);</span><br><span class="line"><span class="keyword">CREATE</span> <span class="keyword">TABLE</span> [HomeAddress] (</span><br><span class="line">    [StudentId] <span class="built_in">int</span> <span class="keyword">NOT</span> <span class="literal">NULL</span>,</span><br><span class="line">    [City] <span class="keyword">nvarchar</span>(<span class="keyword">max</span>) <span class="literal">NULL</span>,</span><br><span class="line">    [Street] <span class="keyword">nvarchar</span>(<span class="keyword">max</span>) <span class="literal">NULL</span>,</span><br><span class="line">    <span class="keyword">CONSTRAINT</span> [PK_HomeAddress] PRIMARY <span class="keyword">KEY</span> ([StudentId]),</span><br><span class="line">    <span class="keyword">CONSTRAINT</span> [FK_HomeAddress_Students_StudentId] <span class="keyword">FOREIGN</span> <span class="keyword">KEY</span> ([StudentId]) <span class="keyword">REFERENCES</span> [Students] ([<span class="keyword">Id</span>]) <span class="keyword">ON</span> <span class="keyword">DELETE</span> <span class="keyword">CASCADE</span></span><br><span class="line">);</span><br></pre></td></tr></table></figure></p><p>You can ignore properties which you do not want EF tracking.<br><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><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">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="keyword">public</span> <span class="keyword">string</span> Street &#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">string</span> City &#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">string</span> State &#123; <span class="keyword">get</span>; <span class="keyword">set</span>; &#125; <span class="comment">// ignore this</span></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">OnModelCreating</span>(<span class="params">ModelBuilder modelBuilder</span>)</span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    modelBuilder.Entity&lt;Student&gt;()</span><br><span class="line">        .OwnsOne(s =&gt; s.Home, (h) =&gt;</span><br><span class="line">        &#123;</span><br><span class="line">            h.Ignore(a =&gt; a.State);</span><br><span class="line">            h.ToTable(<span class="string">"HomeAddress"</span>);</span><br><span class="line">        &#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p><p>There are certain elements to keep in mind especially with change tracking. With EF core do not assume the same code of EF6 would give you similar behaviour. This is especially true with Change Tracking. In my view these changes are welcome and makes tracking more intuitive and easy to navigate.</p><p>When you use <code>Add</code>, <code>Attach</code>, <code>Update</code> or <code>Remove</code> on either <code>DbSet&lt;&gt;</code> or through <code>DbContext</code>, it effects all reachable entities. Here is what it would look like:<br><figure class="highlight csharp"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">context.Students.Add(student);</span><br></pre></td></tr></table></figure></p><p>This would also mark <code>Address</code> in a <code>Added</code> state.<br>But if you do not want to track all the entities in the graph:<br><figure class="highlight csharp"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">context.Entry(student).State = EntityState.Added;</span><br></pre></td></tr></table></figure></p><p>When you do this only the student is marked for insert and address is not. So how do you only change the state of address?<br><figure class="highlight csharp"><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> address = _context.Entry(student).Reference(s =&gt; s.Home).TargetEntry;</span><br><span class="line">address.State = EntityState.Unchanged;</span><br></pre></td></tr></table></figure></p><p>When you mark an entity in the graph for update, all the properties are marked for update. In a disconnected (n-tier) scenario, you would need to track changes on your entity externally and let EF know about the changes. You need to have the original state of the entity and do some processing to know which properties were changed. Or you could go back to the database, get the entity and compare it’s state.<br><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></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> entry = _context.Attach(student);</span><br><span class="line"><span class="keyword">var</span> dbValues = entry.GetDatabaseValues(); <span class="comment">// gets only the student</span></span><br><span class="line">entry.OriginalValues.SetValues(dbValues);</span><br><span class="line">_context.SaveChanges();</span><br></pre></td></tr></table></figure></p><p>This would only update those columns which had any changes on them. But it would only affect the student object and not the address. The address would still be in an <code>Unchanged</code> state. The above <code>entry.GetDatabaseValues()</code> would fetch only student values and not address. For you to track changes on address, you would need to explicitly check on its entity.<br><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></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> entry = _context.Attach(student);</span><br><span class="line"><span class="keyword">var</span> adEntry = _context.Entry(student.Home);</span><br><span class="line">adEntry.OriginalValues.SetValues(adEntry.GetDatabaseValues()); <span class="comment">// gets home address</span></span><br><span class="line">entry.OriginalValues.SetValues(entry.GetDatabaseValues()); <span class="comment">// gets student</span></span><br><span class="line">_context.SaveChanges();</span><br></pre></td></tr></table></figure></p><p>Now on <code>SaveChanges()</code>, it would issue update on <code>Address</code> too if it found any changes.</p>]]></content>
    
    <summary type="html">
    
      
      
        &lt;p&gt;Owned entity was made available from EF Core 2.0 onwards. The same .NET type can be shared among different entities. Owned entities would
      
    
    </summary>
    
    
      <category term="Entity Framework Core" scheme="https://www.ajeetyelandur.com/tags/Entity-Framework-Core/"/>
    
  </entry>
  
  <entry>
    <title>Windows 10 Fall Creators update crashes App Pool</title>
    <link href="https://www.ajeetyelandur.com/2017/10/Windows-10-Fall-Creators-update-crashes-App-Pool/"/>
    <id>https://www.ajeetyelandur.com/2017/10/Windows-10-Fall-Creators-update-crashes-App-Pool/</id>
    <published>2017-10-19T04:37:20.000Z</published>
    <updated>2017-12-20T10:38:57.734Z</updated>
    
    <content type="html"><![CDATA[<p>Windows 10 Fall Creators update was not yet available on my PC, so I manually pulled the update. The upgrade seems to have run fine except that when I tried starting one of my development services hosted on IIS, it did not. Instead I saw <strong>Service Unavailable</strong> HTTP Error 503. I checked the application pool assigned to this web site and it had stopped.  </p><p>Under windows event log I saw this<br>IIS-W3SVC-WP(2307)  </p><blockquote><p>The worker process for application pool &lt;<em>Pool Name</em>&gt; encountered an error ‘Cannot read configuration file’ trying to read configuration data from file ‘\\?\&lt;EMPTY&gt;’, line number ‘0’.  The data field contains the error code.</p></blockquote><p>I knew for sure that the update had caused this issue as I was working on this particular web site just before the restart prompted me to close down my work.</p><p>I started looking at the user account under which I was running the app pool. It checked out fine. Next I just went and cleared off all the files under the Inetpub\temp folder. After restarting the services the web site came up without fuss this time. </p><p>I got curious since I had no idea what had caused the issue in the first place and started searching for support articles and came across this <a href="https://support.microsoft.com/en-us/help/4050891/error-http-503-and-was-event-5189-from-web-applications-on-windows-10" target="_blank" rel="noopener">Web applications return HTTP Error 503 and WAS event 5189 on Windows 10 Version 1709 (Fall Creators Update)</a></p><p>This explained why I was facing the issue though the error message and the event logged was different. You also require to stop W3SVC service which the article missed(?) without which some files cannot be deleted and Remove-Item fails.</p><p><strong>Solution</strong><br>Stop “Windows Process Activation Service” and “W3SVC” service and clean out (delete) all the files under C:\Inetpub\temp\AppPools*. Start your services and the sites should be back to work.</p>]]></content>
    
    <summary type="html">
    
      
      
        &lt;p&gt;Windows 10 Fall Creators update was not yet available on my PC, so I manually pulled the update. The upgrade seems to have run fine excep
      
    
    </summary>
    
    
      <category term="Windows" scheme="https://www.ajeetyelandur.com/tags/Windows/"/>
    
      <category term="Troubleshoot" scheme="https://www.ajeetyelandur.com/tags/Troubleshoot/"/>
    
  </entry>
  
  <entry>
    <title>WCF - One-way or the other</title>
    <link href="https://www.ajeetyelandur.com/2017/09/WCF-One-way-or-the-other/"/>
    <id>https://www.ajeetyelandur.com/2017/09/WCF-One-way-or-the-other/</id>
    <published>2017-09-27T09:51:05.000Z</published>
    <updated>2017-09-27T10:46:42.681Z</updated>
    
    <content type="html"><![CDATA[<figure class="half-width left"><img src="/images/201709/wcf_oneway.png" alt="WCF One-way" title="WCF One-way"></figure><p>I have always found WCF to be a great technology for many use cases. Before I ruffle anyone’s feathers out there, I love what Web API is capable of and if I am looking at providing HTTP services or anything which is targeted over internet, I would blindly choose Web API.<br>I am also eagerly waiting to see WCF service framework becoming a part of .NET Core. We already have the <a href="https://github.com/dotnet/wcf" target="_blank" rel="noopener">WCF client libraries</a> available for the .NET Core version.<br>Having cleared that up, let me get back to one such use case for WCF, making a fire and forget call or one-way. This is useful when the client truly does not bother about the result or when it needs to kick off a process on the server and does not want to wait for it to finish, usually long running.<br>WCF’s comes with great variety, power and flexibility, but to truly harness it, one needs to have a deep understanding of its internals. You can use it out of the box without much mucking around, but sometimes it’s behaviour may not be obvious.</p><p>A quick recap on WCF one-way pattern.<br>The default behaviour of a service is request-reply pattern and to make it one-way you simply set the <code>OperationContract</code> as IsOneWay.</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></pre></td><td class="code"><pre><span class="line">[<span class="meta">ServiceContract</span>]</span><br><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title">IOneWayService</span></span><br><span class="line">&#123;</span><br><span class="line">[<span class="meta">OperationContract(IsOneWay = true)</span>]</span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">Process</span>(<span class="params"><span class="keyword">int</span> seed</span>)</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>A few things to keep in mind when decorating an Operation as one-way.</p><ul><li>The method has to return void</li><li>You cannot return Faults to the client.  That means you cannot decorate the operation with <code>FaultContract(typeof(Exception))</code> attribute.</li></ul><p>Even if you unintentionally did the above on an one-way operation, the service would throw an error when attempting to start it.</p><p>Your service implementation is going to be nothing different here and so would the hosting part of it. So I won’t be delving in to it. You can simulate some load in it by doing a <code>Thread.Sleep</code>. So, would one get fire and forget operation form your client’s? <em>It depends</em>.<br>In fact it depends on quite a few things. First let us see what we can expect with our current implementation. Let me show you my client proxy first.</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></pre></td><td class="code"><pre><span class="line">public class OneWayProxy : ClientBase&lt;IOneWayService&gt;, IOneWayService</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">Process</span>(<span class="params"><span class="keyword">int</span> seed</span>)</span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">Channel.Process(seed);</span><br><span class="line">&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>I like to hand-code my proxy / client for the service. I’ll probably keep that for another post. I also implement my clients different to what I have shown here, but this too is better than the freebie client you get from Visual Studio.</p><p>Let us look at the code calling our client.</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></pre></td><td class="code"><pre><span class="line">OneWayProxy proxy = <span class="keyword">new</span> OneWayProxy();</span><br><span class="line">proxy.Process(<span class="number">5</span>);</span><br><span class="line"><span class="comment">//proxy.Process(10);</span></span><br><span class="line">proxy.Close();</span><br></pre></td></tr></table></figure><p>The input parameter is just to make the service look important.</p><p>Here is what we see from running this implementation.</p><ol><li>The call to the proxy would be asynchronous (at the client). You can uncomment the next call and verify that. They would not block.</li><li>Closing the channel might block. If the binding used is NetTcpBinding, by default it supports transport-level sessions. Which means the channel is kept open until the server completes processing all the client’s calls. If you use transport without a session, like basicHttpBinding, then the closing of channel would not block.</li><li>The calls are dispatched synchronously on the service. Meaning, your next call would only get processed after completing the previous.</li></ol><p>So what we learn is using One-way throws up a few surprises. It is fire &amp; forget only for the operation calls. When you are having long running processes, you might not always want to wait for the operations to complete to close the channel. And Yes! You should always close the channel so that they are returned back to the servers pool.</p><p>Since most uses of WCF within the firewall would use or prefer TCP protocol over HTTP for speed and security and I would like to close my channel after each call is made,but not have it blocked, the above implementation would not be the most useful.</p><p>So what are our options here?<br>To close the proxy before the operation finishes -</p><ul><li><p>We can use a session less transport, such as BasicHttpBinding or turn on Reliable session on NetTcpBinding. TCP binding provides reliability at transport level, but you get message level reliable session by enabling explicitly at the binding. But this comes at a cost overhead since a lot more messages are exchanged between the client and server to ensure this. This would also not give the best performance due to its chatty nature. <code>&lt;reliableSession enabled=&quot;true&quot; /&gt;</code></p></li><li><p>You can mark the NetTcpBinding by turning off the session support. This is done by marking the binding as ‘oneWay’. This requires you to create a custom binding which turns off session support on NetTcpBinding. This would not block the channel from closing. In the below example we have adding tcpTransport support.</p><figure class="highlight xml"><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="tag">&lt;<span class="name">bindings</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">customBinding</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">binding</span> <span class="attr">name</span>=<span class="string">"onewayBinding"</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">oneWay</span> /&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">tcpTransport</span> /&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">binding</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">customBinding</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">bindings</span>&gt;</span></span><br></pre></td></tr></table></figure></li></ul><p>Remember to use the same binding at the client also.</p><p>By default all calls from a client would be processed synchronously. If more than one call were made from a client, they would be queued up on the server. The proxy would also be blocked from closing until all the processing is completed.</p><p>To enable concurrent processing of messages at the service-</p><p>With the above custom binding, it will also ensure that messages are processed concurrently. Which means each request would be processed on a different thread. Or you could again use basicHttpBinding.<br>However if you are using NetTcpBinding or session shaped binding, you should mark your service concurrency mode as Multiple.</p>]]></content>
    
    <summary type="html">
    
      
      
        &lt;figure class=&quot;half-width left&quot;&gt;&lt;img src=&quot;/images/201709/wcf_oneway.png&quot; alt=&quot;WCF One-way&quot; title=&quot;WCF One-way&quot;&gt;&lt;/figure&gt;

&lt;p&gt;I have always f
      
    
    </summary>
    
    
      <category term="WCF" scheme="https://www.ajeetyelandur.com/tags/WCF/"/>
    
  </entry>
  
  <entry>
    <title>Migration: Legacy application and trigger happy</title>
    <link href="https://www.ajeetyelandur.com/2017/06/migration-legacy-app-and-trigger-happy/"/>
    <id>https://www.ajeetyelandur.com/2017/06/migration-legacy-app-and-trigger-happy/</id>
    <published>2017-06-27T07:15:14.000Z</published>
    <updated>2017-09-27T12:08:24.305Z</updated>
    
    <content type="html"><![CDATA[<p>Many of my major projects of my career have been in application migration involving rewrite using a new technology. I can think of only one instance where it was a big bang approach, where we built a new system and in one go replaced the other system. It wasn’t as simple as it sounded, but we could justify this approach and it worked well.<br>However every other time, we have built the new system invariably adding new features while keeping the old system running and accessible.<br>There have been many different approaches to this strategy. While in some cases, we would force the users to switch to the new application when available while disabling features from the old. Other times we would keep the old app running in parallel while making continuous releases on the new application. We have even had to maintain and service the old application to keep the business happy and sometimes to make the application gel with the new features being introduced in the newer application, especially when database changes were involed.</p><p>I’ll go through one such case where we had to rewrite a critical application while keeping access to the old system. We discovered that a lot of business functionality was kept in database triggers. There were many apps and I guess at that point someone decided to use triggers since they then needn’t touch any of the apps to add new features. You can read my take on business in database <a href="2016/05/bl-in-database-or-application/">here</a>.</p><p>We had decided to use DDD approach and this meant consolidating all those business rules in the trigger in their respective domains. The database being a common layer for both the applications, called for some strategy here.</p><p>The triggers couldn’t simply be disabled nor could we have them trigger when the new applications interacted with those underlying tables.</p><p>We need to restrict those triggers to only the old applications. The triggers will fire, no stopping that. But, we’ll stop the triggers body from continuing execution of the SQL. There are couple of ways of doing this.</p><ol><li><p>Using App Name</p><p>This is the least impact way of determining if the trigger needs to continue execution or return. Providing an app name in the connection string <code>;app=YourApplicationName</code>, would make it available in your SQL session. I also make it a practice to include this as it helps in profiling your database more easily. In your SQL (Trigger) you can now check</p><figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">if (APP_NAME() = 'YourApplicationName') RETURN;</span><br></pre></td></tr></table></figure></li><li><p>Using a column to track the transaction source</p><p>Depending on your situation, this might be intrusive or acceptable. If this is a new column, you might want it to have a default value so that older applications can use that. You should set a specific value from your new applications for each transaction it does with these specific tables. Check for these values in the trigger and exit from executions. Of course the trigger would execute completely for transactions from your older applications. With this column you can also gain some insight in to who is transacting with which app. Be sure to check correctly in <em>inserted</em> or <em>deleted</em> special table depending on the operation that activates the trigger.</p></li></ol><p>In both the above methods, there would be no change in the legacy applications.</p><p>BTW, many of the triggers were good candidates for domain events.</p><p>I have used both approaches and they have worked well for me. If there are other ways of doing this, let me know in your comments.</p>]]></content>
    
    <summary type="html">
    
      
      
        &lt;p&gt;Many of my major projects of my career have been in application migration involving rewrite using a new technology. I can think of only o
      
    
    </summary>
    
    
      <category term="Database" scheme="https://www.ajeetyelandur.com/tags/Database/"/>
    
      <category term="Migration" scheme="https://www.ajeetyelandur.com/tags/Migration/"/>
    
  </entry>
  
  <entry>
    <title>Practical Patterns: Control with Builder</title>
    <link href="https://www.ajeetyelandur.com/2017/06/Practical-Patterns-Control-with-Builder/"/>
    <id>https://www.ajeetyelandur.com/2017/06/Practical-Patterns-Control-with-Builder/</id>
    <published>2017-06-12T06:53:59.000Z</published>
    <updated>2017-06-13T09:49:45.627Z</updated>
    
    <content type="html"><![CDATA[<figure class="half-width left"><img src="/images/201706/lego_builder.png" alt="Builder-Director" title="Builder-Director"></figure><p>There are many situations where one needs to construct a complex object before consuming it. You might need to pass many arguments, set configurations and many other mandatory properties before the instance is ready for use. Passing parameters through constructors is a sure way of ensuring that your objects are always in a proper state when created. But for complex objects having everything through constructors can be a bit cumbersome and restrictive too in some cases.</p><p>I will not be taking you through building the standard builder pattern, but one which implements a fluent interface to build a product. It would not just be chaining of methods, but will also ensure that domain rules are met for the product.</p><p>A quick review of the main features of the builder pattern itself before we start addressing its quirks and the alternate approach.</p><p><em>A builder always returns a concrete product unlike factory or abstract factory which return abstract products.</em></p><p><em>A builder encapsulates the construction of an object (product). You would use one when the process of constructing  an object is complex. The builder only defines the steps required to construct the object.</em></p><p><em>It does not enforce any order in which they should be called. The director has to know this and constructs the object through the builder.</em></p><p><em>While the builder is being built, it is in a mutable state.</em></p><p>Let us consider <code>Account</code> as our product which requires to be built.</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></pre></td><td class="code"><pre><span class="line"><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="keyword">int</span> Number &#123; <span class="keyword">get</span>; <span class="keyword">internal</span> <span class="keyword">set</span>; &#125;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">string</span> Type &#123; <span class="keyword">get</span>; <span class="keyword">internal</span> <span class="keyword">set</span>; &#125;</span><br><span class="line">    <span class="keyword">public</span> IContact PrimaryContact &#123; <span class="keyword">get</span>; <span class="keyword">internal</span> <span class="keyword">set</span>; &#125;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">string</span> HomeBranch &#123; <span class="keyword">get</span>; <span class="keyword">internal</span> <span class="keyword">set</span>; &#125;</span><br><span class="line">    <span class="comment">// Optional</span></span><br><span class="line">    <span class="keyword">public</span> IEnumerable&lt;IContact&gt; OtherContacts &#123; <span class="keyword">get</span>; <span class="keyword">internal</span> <span class="keyword">set</span>; &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>We have <code>IContact</code> just to spice up this product.<br><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></pre></td><td class="code"><pre><span class="line"><span class="keyword">interface</span> <span class="title">IContact</span></span><br><span class="line">&#123;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p><p>Let us also define a concrete for this interface</p><p>Our typical builder interface would look something like this</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></pre></td><td class="code"><pre><span class="line"><span class="keyword">interface</span> <span class="title">IAccountBuilder</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">SetNumber</span>(<span class="params"><span class="keyword">int</span> number</span>)</span>;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">SetType</span>(<span class="params"><span class="keyword">string</span> type</span>)</span>;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">AssignHomeBranch</span>(<span class="params"><span class="keyword">string</span> branchName</span>)</span>;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">RecordPrimaryContact</span>(<span class="params">IContact primary</span>)</span>;</span><br><span class="line">    <span class="function">Account <span class="title">Build</span>(<span class="params"></span>)</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>Most of the examples of the Builder out there would guide you to build a Director next, which takes in a Builder and returns the product. The director should now the order in which to call the methods in the builder. Most of the Directors do not accept any input from the user except the Builder itself. But if we need to accept inputs from the user (or program) to create our Product, the Builder would need to accept the inputs (as in our example) and the Director would also need to take in the inputs so that it could pass it over to the builder.</p><p>Instead we can have a Builder something like this<br><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><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></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title">AccountBuilder</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">private</span> Account _account = <span class="literal">null</span>;</span><br><span class="line">    <span class="keyword">private</span> List&lt;IContact&gt; Contacts &#123;<span class="keyword">get</span>; <span class="keyword">set</span>;&#125; = <span class="keyword">new</span> List&lt;IContact&gt;();</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> AccountBuilder <span class="title">Create</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        _account = <span class="keyword">new</span> Account();</span><br><span class="line">        _account.OtherContacts = Contacts;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">this</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> AccountBuilder <span class="title">As</span>(<span class="params"><span class="keyword">string</span> type</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        _account.Type = type;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">this</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> AccountBuilder <span class="title">With</span>(<span class="params"><span class="keyword">int</span> number</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        _account.Number = number;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">this</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> AccountBuilder <span class="title">In</span>(<span class="params"><span class="keyword">string</span> branch</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        _account.HomeBranch = branch;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">this</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> AccountBuilder <span class="title">HavingAddress</span>(<span class="params">IContact contact</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        _account.PrimaryContact = contact;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">this</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> AccountBuilder <span class="title">AddingOtherAddress</span>(<span class="params">IContact contact</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        Contacts.Add(contact);</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">this</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> Account <span class="title">Build</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> _account;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p><p>We can now create an Account instance like this<br><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></pre></td><td class="code"><pre><span class="line">AccountBuilder _builder = <span class="keyword">new</span> AccountBuilder();</span><br><span class="line"><span class="keyword">var</span> account = _builder.Create()</span><br><span class="line">                .As(<span class="string">"Saving"</span>)</span><br><span class="line">                .With(<span class="number">123</span>)</span><br><span class="line">                .HavingAddress(<span class="keyword">new</span> Address(<span class="string">"Sydney"</span>))</span><br><span class="line">                .In(<span class="string">"Sydney"</span>)</span><br><span class="line">                .Build();</span><br></pre></td></tr></table></figure></p><p>The above Builder uses chaining of methods which constructs an <code>Account</code> class. Each method returns the same copy of its instance, allowing chaining of methods. Through this we can assign properties of the Account class. Finally, calling the <code>Build()</code> returns us the completed(hopefully!) Account class.</p><p>Even though the new builder is much easier to use, it comes with a lot of pitfalls. In order to use this interface, the developer would need to know the implementation details of each method. We cannot enforce assigning of mandatory properties. Knowing which are optional is also not intuitive. The client can also repeat assigning certain properties.</p><p>Let us try to remove some of the ways to fail by introducing certain guards. How can we ensure we always start with Create(), which allows for the instance of Account to be initialised.<br>We’ll make the constructor of <code>AccountBuilder</code> private and make the <code>Create()</code> a static method. The clients can now access <code>AccountBuilder</code> only through <code>Create()</code>.</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></pre></td><td class="code"><pre><span class="line"><span class="comment">// In AccountBuilder</span></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="title">AccountBuilder</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> _account = <span class="keyword">new</span> Account();</span><br><span class="line">    _account.OtherContacts = Contacts; </span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> AccountBuilder <span class="title">Create</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> AccountBuilder();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>Now our clients would use the builder like this<br><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></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> account = AccountBuilder.Create()</span><br><span class="line">                .As(<span class="string">"Saving"</span>)</span><br><span class="line">                .With(<span class="number">123</span>)</span><br><span class="line">                .HavingAddress(<span class="keyword">new</span> Address(<span class="string">"Sydney"</span>))</span><br><span class="line">                .In(<span class="string">"Sydney"</span>)</span><br><span class="line">                .Build();</span><br></pre></td></tr></table></figure></p><p>Now the only saving grace is that we can at least ensure the client always gets an <code>Account</code> instance, even if they may not be completely constructed. I would still be hesitant to ship this to developers. What we want is to enforce an order of construction and guide them until all the rules have been met before the <code>Account</code> product can be returned.</p><p>For this we can look at <strong>I</strong> of the SOLID principles. Through Interface Segregation Principle, I’ll show how we can have a water tight builder.<br>We shall isolate each method in a separate interface. While at this, we’ll also determine what should be the next possible call(s) from this method. This can be done by returning the next permissible interface.<br>Let us see this in code to make it more clear.</p><p>Based on our methods we’ll define the following interfaces.<br><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><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">interface</span> <span class="title">IAccountType</span></span><br><span class="line">&#123;</span><br><span class="line"><span class="function">IAccountNumber <span class="title">As</span>(<span class="params"><span class="keyword">string</span> type</span>)</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">interface</span> <span class="title">IAccountNumber</span></span><br><span class="line">&#123;</span><br><span class="line"><span class="function">IPrimaryContact <span class="title">With</span>(<span class="params"><span class="keyword">int</span> number</span>)</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">interface</span> <span class="title">IPrimaryContact</span></span><br><span class="line">&#123;</span><br><span class="line"><span class="function">IOtherContact <span class="title">HavingAddress</span>(<span class="params">IContact contact</span>)</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">interface</span> <span class="title">IOtherContact</span></span><br><span class="line">&#123;</span><br><span class="line"><span class="function">IOtherContact <span class="title">AddingOtherAddress</span>(<span class="params">IContact contact</span>)</span>;</span><br><span class="line"><span class="function">IHomeBranch <span class="title">NoMoreAddress</span>(<span class="params"></span>)</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">interface</span> <span class="title">IHomeBranch</span></span><br><span class="line">&#123;</span><br><span class="line"><span class="function">IAccountBuilder <span class="title">In</span>(<span class="params"><span class="keyword">string</span> branch</span>)</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">interface</span> <span class="title">IAccountBuilder</span></span><br><span class="line">&#123;</span><br><span class="line"><span class="function">Account <span class="title">Build</span>(<span class="params"></span>)</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p><p>Each interface returns only the next available interface. This allows the user to progress only through the steps which we have defined. We can also allow the user to skip optional parameters (check <code>IOtherContact</code>). Only when the client reaches <code>IAccountBuilder</code> will they be able to access <code>Build()</code> which finally returns <code>Account</code> instance.</p><p>The account builder will now look like this. It will implement all of the above interfaces.</p><figure class="highlight cpp"><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></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">AccountBuilder</span> :</span> IAccountBuilder, IAccountNumber, IAccountType, </span><br><span class="line">IPrimaryContact, IHomeBranch, IOtherContact</span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">private</span> Account _account = null;</span><br><span class="line">    <span class="keyword">private</span> List&lt;IContact&gt; Contacts &#123;get; <span class="built_in">set</span>;&#125; = </span><br><span class="line">            <span class="keyword">new</span> List&lt;IContact&gt;();</span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="title">AccountBuilder</span><span class="params">()</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        var _account = <span class="keyword">new</span> Account();</span><br><span class="line">        _account.OtherContacts = Contacts; </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> IAccountType <span class="title">Create</span><span class="params">()</span> </span>=&gt; <span class="keyword">new</span> AccountBuilder();</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> IAccountNumber <span class="title">As</span><span class="params">(<span class="built_in">string</span> type)</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        _account.Type = type;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">this</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> IPrimaryContact <span class="title">With</span><span class="params">(<span class="keyword">int</span> number)</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        _account.Number = number;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">this</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> IOtherContact <span class="title">HavingAddress</span><span class="params">(IContact contact)</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        _account.PrimaryContact = contact;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">this</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> IOtherContact <span class="title">AddingOtherAddress</span><span class="params">(IContact contact)</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        Contacts.Add(contact);</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">this</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> IHomeBranch <span class="title">NoMoreAddress</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">this</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> IAccountBuilder <span class="title">In</span><span class="params">(<span class="built_in">string</span> branch)</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        _account.HomeBranch = branch;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">this</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> Account <span class="title">Build</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> _account;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>And we use it similar to before<br><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></pre></td><td class="code"><pre><span class="line">account = AccountBuilder.Create()</span><br><span class="line">.As(<span class="string">"Saving"</span>)</span><br><span class="line">.With(<span class="number">123</span>)</span><br><span class="line">.HavingAddress(<span class="keyword">new</span> Address(<span class="string">"Sydney"</span>))</span><br><span class="line">.NoMoreAddress()</span><br><span class="line">.In(<span class="string">"Sydney 2000"</span>)</span><br><span class="line">.Build();</span><br></pre></td></tr></table></figure></p><p>With optional address<br><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></pre></td><td class="code"><pre><span class="line">account = AccountBuilder.Create()</span><br><span class="line">.As(<span class="string">"Saving"</span>)</span><br><span class="line">.With(<span class="number">123</span>)</span><br><span class="line">.HavingAddress(<span class="keyword">new</span> Address(<span class="string">"Sydney"</span>))</span><br><span class="line">.AddingOtherAddress(<span class="keyword">new</span> Address(<span class="string">"Katoomba"</span>))</span><br><span class="line">.NoMoreAddress()</span><br><span class="line">.In(<span class="string">"Sydney"</span>)</span><br><span class="line">            .Build();</span><br></pre></td></tr></table></figure></p><p>Doesn’t look much different, but the client cannot progress to the next method unless they go through the previous.<br>Depending on how you see this, this class is not immutable. If this is something you desire, then do not return the same instance of <code>AccountBuilder</code>, but a new one each time. You would need to maintain the state internally of <code>AccountBuilder</code>. Also create the <code>Account</code> only in the <code>Build()</code> method.</p><figure class="highlight cpp"><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></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">AccountBuilder</span> :</span> IAccountBuilder, IAccountNumber, IAccountType,</span><br><span class="line">IPrimaryContact, IHomeBranch, IOtherContact</span><br><span class="line">&#123;</span><br><span class="line">    <span class="comment">// Maintain state</span></span><br><span class="line">    <span class="keyword">private</span> List&lt;IContact&gt; Contacts &#123; get; <span class="built_in">set</span>; &#125; </span><br><span class="line">        = <span class="keyword">new</span> List&lt;IContact&gt;();</span><br><span class="line">    <span class="keyword">private</span> <span class="built_in">string</span> Type &#123; get; <span class="built_in">set</span>; &#125;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> Number &#123; get; <span class="built_in">set</span>; &#125;</span><br><span class="line">    <span class="comment">// protect instantiation</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="title">AccountBuilder</span><span class="params">()</span></span></span><br><span class="line"><span class="function">    </span>&#123;&#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> IAccountType <span class="title">Create</span><span class="params">()</span> </span>=&gt; <span class="keyword">new</span> AccountBuilder();</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> IAccountNumber <span class="title">As</span><span class="params">(<span class="built_in">string</span> type)</span> </span>=&gt; <span class="keyword">new</span> AccountBuilder()</span><br><span class="line">    &#123;</span><br><span class="line">        Type = type</span><br><span class="line">    &#125;;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> IPrimaryContact <span class="title">With</span><span class="params">(<span class="keyword">int</span> number)</span> </span>=&gt; <span class="keyword">new</span> AccountBuilder()</span><br><span class="line">    &#123;</span><br><span class="line">        Type = <span class="keyword">this</span>.Type,</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> Account <span class="title">Build</span><span class="params">()</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        var account = <span class="keyword">new</span> Account();</span><br><span class="line">        account.Type = Type;</span><br><span class="line">        account.Number = Number;</span><br><span class="line">        <span class="keyword">return</span> account;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/// rest of the implementation left out for brevity</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>I have left rest of the methods out in the above example, but you should be able to get an idea out of it. I now internally maintain state of the user’s inputs in the <code>AccountBuilder</code>‘s instance. When the <code>Build()</code> is called, I transfer all the values to the <code>Account</code> instance. BTW, I have used C# 6’s feature of expression-bodied functions.</p><p>I find builders very useful, especially when my domain is complex and need to control how the instance is created. With fluent interfacing and enforcing domain rules, it becomes easy for developers to create instances of your product. I find implementation of Builder this way more expressive and with more control.</p>]]></content>
    
    <summary type="html">
    
      
      
        &lt;figure class=&quot;half-width left&quot;&gt;&lt;img src=&quot;/images/201706/lego_builder.png&quot; alt=&quot;Builder-Director&quot; title=&quot;Builder-Director&quot;&gt;&lt;/figure&gt;

&lt;p&gt;The
      
    
    </summary>
    
    
      <category term="DotNet" scheme="https://www.ajeetyelandur.com/tags/DotNet/"/>
    
      <category term="Design Patterns" scheme="https://www.ajeetyelandur.com/tags/Design-Patterns/"/>
    
  </entry>
  
  <entry>
    <title>Practical Patterns: Refactoring with CoR Pattern</title>
    <link href="https://www.ajeetyelandur.com/2017/02/Practical-Patterns-Refactoring-with-CoR/"/>
    <id>https://www.ajeetyelandur.com/2017/02/Practical-Patterns-Refactoring-with-CoR/</id>
    <published>2017-02-03T06:15:03.000Z</published>
    <updated>2017-06-13T09:49:45.638Z</updated>
    
    <content type="html"><![CDATA[<p>This is a 3rd post in the series of Design Patterns. Since I would be refactoring an existing solution it would help to refer to my previous posts to understand the sample code base. You may begin with <a href="/2016/05/Practical-Patterns-Refactoring-with-Bridge">Bridge</a> and move to <a href="/2016/05/Practical-Patterns-Refactoring-with-Decorator">Decorator</a> pattern to see how the application has evolved.</p><p>Using a single <code>if else</code> or a small <code>switch case</code> has never been difficult. But if the options or decisions to make continues to grow, then you would soon end up with an unruly code base. You would very quickly lose loose coupling and with violation of Single Reponsibility Principle, there would be a huge risk of breaking existing code or introducing defects with newer requirements.</p><p>Chain of Responsibility (CoR) is very popular frameworks which employ it to process events or requests. One can write a single atomic unit of process and then chain them together to form a complex processing pipelines. <a href="http://owin.org/" target="_blank" rel="noopener">OWIN</a> is one such specification through which you can implement complex frameworks by chaining individual OWIN components together.</p><p>CoR provides a chance for more than one object to process the request. Every object in the chain can process the request or once the request has been processed by a suitable handler, it can return. The sender or the client needs to only know the initial handler or the base class to launch the request. </p><p>There is a special case which requires to be handled in CoR. Since each handler is chained like nodes in a linked list, the end of chain condition requires to be handled. We’ll review the options shortly.</p><p>Let us work with adding a new requirement to the existing application. A client requires to go through an approval process for Corporate accounts. Depending on the amount’s value a manager or director can approve the <em>WithDrawal</em>. Let us see how the solution looks without implementing it through the pattern. Let us pick up from where we left from our <a href="/2016/05/Practical-Patterns-Refactoring-with-Decorator">Decorator</a> implementation.<br>Introduce a new <code>Employee</code> class which would provide us with a possible approver. The <code>Approve</code> method would determine if this employee can approve or not.</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><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">class</span> <span class="title">Employee</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Employee</span>(<span class="params"><span class="keyword">string</span> name, <span class="keyword">decimal</span> approvalLimit</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        Name = name;</span><br><span class="line">        ApprovalLimit = approvalLimit;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">string</span> Name &#123; <span class="keyword">get</span>; &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">decimal</span> ApprovalLimit &#123; <span class="keyword">get</span>; &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">bool</span> <span class="title">Approve</span>(<span class="params"><span class="keyword">decimal</span> amount</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        <span class="keyword">if</span>(amount &lt; ApprovalLimit)</span><br><span class="line">        &#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 class="keyword">return</span> <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>In the <code>Withdraw</code> method, we now check through the list of approvers to determine if we can continue with the withdrawal.</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><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></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title">Corporate</span> : <span class="title">ITransaction</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">decimal</span> _balance = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">decimal</span> _overdraft = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">const</span> <span class="keyword">decimal</span> overdraft_factor = <span class="number">0.1</span>m;</span><br><span class="line">    <span class="comment">// list of approvers</span></span><br><span class="line">    List&lt;Employee&gt; approvers;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Corporate</span>(<span class="params"><span class="keyword">decimal</span> balance</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        _balance = balance;</span><br><span class="line">        Overdraft = _balance;</span><br><span class="line">        Console.WriteLine(<span class="string">"Opened corporate account with balance &#123;0&#125;"</span>, balance);</span><br><span class="line">        Console.WriteLine(<span class="string">"Overdraft stands at &#123;0&#125;"</span>, _overdraft);</span><br><span class="line"></span><br><span class="line">        approvers = <span class="keyword">new</span> List&lt;Employee&gt;</span><br><span class="line">        &#123;</span><br><span class="line">            <span class="keyword">new</span> Employee(<span class="string">"Micky Manager"</span>, <span class="number">1000</span>),</span><br><span class="line">            <span class="keyword">new</span> Employee(<span class="string">"Donald Director"</span>, <span class="number">5000</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="comment">// Omitted Deposit for brevity</span></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">Withdraw</span>(<span class="params"><span class="keyword">decimal</span> amount</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        <span class="keyword">bool</span> amountProcessed = <span class="literal">false</span>;</span><br><span class="line">        <span class="keyword">foreach</span> (Employee approver <span class="keyword">in</span> approvers)</span><br><span class="line">        &#123;</span><br><span class="line">            amountProcessed = approver.Approve(amount);</span><br><span class="line">            <span class="keyword">if</span> (amountProcessed)</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span>(!amountProcessed)</span><br><span class="line">        &#123;</span><br><span class="line">            Console.WriteLine(<span class="string">"Amount &#123;0&#125; did not get approved"</span>, amount);</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (amount &lt; Overdraft)</span><br><span class="line">        &#123;</span><br><span class="line">            _balance -= amount;</span><br><span class="line">            Overdraft = _balance;</span><br><span class="line">            Console.WriteLine(<span class="string">"Widthdrawn: &#123;0&#125; | New balance: &#123;1&#125; | Overdraft: &#123;2&#125;"</span>, amount, _balance, Overdraft);</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        Console.WriteLine(<span class="string">"Could not withdraw. Current overdraft limit &#123;0&#125;"</span>, Overdraft);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>At this point there is no change in the client application.</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></pre></td><td class="code"><pre><span class="line">IAccount account = <span class="keyword">new</span> CreditAccount(<span class="string">"C2102"</span>, AccountType.Corporate);</span><br><span class="line">account.Deposit(<span class="number">1000</span>);</span><br><span class="line">account.Withdraw(<span class="number">1000</span>);</span><br></pre></td></tr></table></figure><p>In the <code>Withdraw</code> method we now iterate through the list of approvers. Why is this a cause of concern? This means that the algorithm for knowing how the approval process works is known to the caller. In this simple case it is iterating through a list of employees. It goes from one approver to the next until someone in the list approves or the list ends. CoR takes all these reponsibilities away from the caller, while also reducing coupling and granting more flexibility.<br>To move this to CoR implementation, we introduce a handler. The handler takes the responsibility of the action as well as promoting or delegating to the next handler if the current instance is unable to process.</p><p>Though it is not imperative to have an interface (I normally have just an abstract class), in this instance we would go with 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></pre></td><td class="code"><pre><span class="line"><span class="keyword">interface</span> <span class="title">IWithdrawHandler</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="function"><span class="keyword">bool</span> <span class="title">Approve</span>(<span class="params"><span class="keyword">decimal</span> amount</span>)</span>;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">SetNext</span>(<span class="params">IWithdrawHandler next</span>)</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>Implementing the interface we can get a common handler.</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><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">class</span> <span class="title">WithdrawHandler</span> : <span class="title">IWithdrawHandler</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">readonly</span> Employee _approver;</span><br><span class="line">    <span class="keyword">private</span> IWithdrawHandler _next;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">WithdrawHandler</span>(<span class="params">Employee approver</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        _approver = approver;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">bool</span> <span class="title">Approve</span>(<span class="params"><span class="keyword">decimal</span> amount</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        <span class="keyword">if</span> (_approver.Approve(amount))</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">        <span class="keyword">else</span></span><br><span class="line">            <span class="keyword">return</span> _next.Approve(amount);</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">SetNext</span>(<span class="params">IWithdrawHandler next</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        _next = next;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>The <code>Corporate</code> class can take in instance of <code>IWithdrawHandler</code> in its constructor.<br>In <code>AccountBase</code> where we were creating the instance of <code>Corporate</code> class.<br><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><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></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title">Corporate</span> : <span class="title">ITransaction</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">decimal</span> _balance = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">decimal</span> _overdraft = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">const</span> <span class="keyword">decimal</span> overdraft_factor = <span class="number">0.1</span>m;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">readonly</span> IWithdrawHandler _handler;</span><br><span class="line">    <span class="comment">//List&lt;Employee&gt; approvers;</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Corporate</span>(<span class="params"><span class="keyword">decimal</span> balance, IWithdrawHandler handler</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        _balance = balance;</span><br><span class="line">        Overdraft = _balance;</span><br><span class="line">        Console.WriteLine(<span class="string">"Opened corporate account with balance &#123;0&#125;"</span>, balance);</span><br><span class="line">        Console.WriteLine(<span class="string">"Overdraft stands at &#123;0&#125;"</span>, _overdraft);</span><br><span class="line">        _handler = handler;</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">Withdraw</span>(<span class="params"><span class="keyword">decimal</span> amount</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        <span class="keyword">bool</span> amountProcessed = _handler.Approve(amount);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span>(!amountProcessed)</span><br><span class="line">        &#123;</span><br><span class="line">            Console.WriteLine(<span class="string">"No approvers for amount &#123;0&#125;"</span>, amount);</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (amount &lt; Overdraft)</span><br><span class="line">        &#123;</span><br><span class="line">            _balance -= amount;</span><br><span class="line">            Overdraft = _balance;</span><br><span class="line">            Console.WriteLine(<span class="string">"Widthdrawn: &#123;0&#125; | New balance: &#123;1&#125; | Overdraft: &#123;2&#125;"</span>, amount, _balance, Overdraft);</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        Console.WriteLine(<span class="string">"Could not withdraw. Current overdraft limit &#123;0&#125;"</span>, Overdraft);</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">abstract</span> <span class="keyword">class</span> <span class="title">AccountBase</span> : <span class="title">IAccount</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">protected</span> ITransaction transactionImp;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">AccountBase</span>(<span class="params"><span class="keyword">string</span> name, AccountType type</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        Name = name;</span><br><span class="line">        <span class="keyword">switch</span> (type)</span><br><span class="line">        &#123;</span><br><span class="line">            <span class="keyword">case</span> AccountType.Personal:</span><br><span class="line">                transactionImp = <span class="keyword">new</span> AuditTransactionDecorator(<span class="keyword">new</span> Personal(<span class="number">1000</span>));</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">case</span> AccountType.Corporate:</span><br><span class="line">                IWithdrawHandler micky = <span class="keyword">new</span> WithdrawHandler(<span class="keyword">new</span> Employee(<span class="string">"Micky Manager"</span>, <span class="number">500</span>));</span><br><span class="line">                IWithdrawHandler donald = <span class="keyword">new</span> WithdrawHandler(<span class="keyword">new</span> Employee(<span class="string">"Donald Director"</span>, <span class="number">1000</span>));</span><br><span class="line">                IWithdrawHandler scrooge = <span class="keyword">new</span> WithdrawHandler(<span class="keyword">new</span> Employee(<span class="string">"Scrooge Owner"</span>, <span class="number">1500</span>));</span><br><span class="line">                micky.SetNext(donald);</span><br><span class="line">                donald.SetNext(scrooge);</span><br><span class="line">                transactionImp = <span class="keyword">new</span> AuditTransactionDecorator(</span><br><span class="line">                    <span class="keyword">new</span> NotifyTransactionDecorator(</span><br><span class="line">                        <span class="keyword">new</span> Corporate(<span class="number">5000</span>, micky)));</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">default</span>:</span><br><span class="line">                <span class="keyword">throw</span> <span class="keyword">new</span> NotImplementedException(<span class="string">"Unknown account type"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//...</span></span><br><span class="line">    <span class="comment">//...</span></span><br><span class="line">    <span class="comment">//...</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p><p>There still is no change in the calling application, but only change is how the instance of Corporate is being created. When this is handled by DI or a factory, the change would be even less intrusive. One requirement of CoR is the handling of “end of chain” condition. What happens when we reach the last handler (scrooge here) and is unable to approve? In this case <code>NullReferenceException</code> is thrown. This might be an acceptable behaviour, though you might want to throw a custom exception. The client in this case should be prepared to take a corrective action. Another way is to have the last handler special such that it knows not to try and promote to next handler, but always returns. Or you could have a special handler which is meant to handler ‘end of chain’ event. This is akin to a Null Object where it has a default implementation.</p>]]></content>
    
    <summary type="html">
    
      
      
        &lt;p&gt;This is a 3rd post in the series of Design Patterns. Since I would be refactoring an existing solution it would help to refer to my previ
      
    
    </summary>
    
    
      <category term="DotNet" scheme="https://www.ajeetyelandur.com/tags/DotNet/"/>
    
      <category term="Design Patterns" scheme="https://www.ajeetyelandur.com/tags/Design-Patterns/"/>
    
      <category term="Refactoring" scheme="https://www.ajeetyelandur.com/tags/Refactoring/"/>
    
  </entry>
  
  <entry>
    <title>Entity Framework mapping private members with Search</title>
    <link href="https://www.ajeetyelandur.com/2016/08/EF-mapping-private-members-with-Search/"/>
    <id>https://www.ajeetyelandur.com/2016/08/EF-mapping-private-members-with-Search/</id>
    <published>2016-08-31T06:45:50.000Z</published>
    <updated>2016-09-01T11:31:29.028Z</updated>
    
    <content type="html"><![CDATA[<p>In one of my project’s, I am in the process of implementing a complex domain by embracing DDD. I am using Entity Framework and working on a legacy database.</p><p>EF is good enough to provide us with sufficient mapping powers to use the data model as our business model. Also I would want to keep things simple and direct by using the same model for both domain as well as EF. However, this brings up a few challenges.</p><p>If you need a fully encapsulated domain, you would probably want to expose your collections as <code>IEnumerable&lt;T&gt;</code>. But, you cannot have <code>IEnumerable&lt;T&gt;</code> for your collection and map to EF. It requires the collection to be of type <code>ICollection&lt;T&gt;</code>. But this would allow direct access to manipulate the collection through its Add, Remove methods. Your domain is not completely encapsulated. You can get around this limitation and use <code>IEnumerable&lt;T&gt;</code> in your model so that it is protected by your domain rules, but you would have to load the collection manually through your repository or factory in to the domain model. You would need to track the changes yourself and let EF know at the time of persisting by attaching each object from the collection back to EF and set with the relevant <code>EntityState</code>.  This is needed since you could not have mapped an association in EF as your <code>ICollection&lt;T&gt;</code> backing member was private.</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><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></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">Student</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">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="keyword">private</span> List&lt;Course&gt; _courses;</span><br><span class="line">    <span class="keyword">public</span> IEnumerable&lt;Course&gt; Courses &#123; <span class="keyword">get</span> &#123; <span class="keyword">return</span> _courses; &#125; &#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">AssignCourses</span>(<span class="params">IEnumerable&lt;Course&gt; courses</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        _courses = <span class="keyword">new</span> List&lt;Course&gt;(courses);</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">Student</span>(<span class="params"><span class="keyword">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 class="function"><span class="keyword">private</span> <span class="title">Student</span>(<span class="params"></span>)</span> &#123; &#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">StudentRepository</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> Student <span class="title">Get</span>(<span class="params"><span class="keyword">string</span> name</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        <span class="keyword">var</span> student = context.Students.FirstOrDefault(c =&gt; c.Name == name);</span><br><span class="line">        <span class="keyword">var</span> courses = context.Courses.Where(c =&gt; c.Name == name).AsEnumerable();</span><br><span class="line">        student.AssignCourses(courses);</span><br><span class="line">        <span class="keyword">return</span> student;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>Another approach would be for you to map your private properties or members. This is a bit more involved than the previous method, but you can take advantage of EF while loading objects. In this article, <a href="https://blog.oneunicorn.com/2012/03/26/code-first-data-annotations-on-non-public-properties/" target="_blank" rel="noopener">mapping to non-public member</a> shows one way how this can be achieved. As the article explains, this would not be a pure POCO since it contains knowledge of configuration for persistence. But I like this approach as it is simple and non-intrusive to the actual behaviour of the POCO itself.</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><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></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">partial</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="keyword">int</span> Id &#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="keyword">public</span> <span class="keyword">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="keyword">private</span> <span class="keyword">string</span> Code &#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">partial</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="keyword">class</span> <span class="title">EFStorageExpression</span></span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">readonly</span> Expression&lt;Func&lt;Account, <span class="keyword">string</span>&gt;&gt;</span><br><span class="line">            CodeAccessor = a =&gt; a.Code;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>You can then map it as follows under <code>EntityTypeConfiguration&lt;Account&gt;</code><br><figure class="highlight csharp"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Property(Account.EFStorageExpression.CodeAccessor)</span><br></pre></td></tr></table></figure></p><p>The reason I stated this as complicated was that, sometimes it does not end with us just being able to map the entity and load it. We would also need to query using the private properties. If a private field is holding a collection, then there might be more reasons to filter on them. You would still be able to Include them to eager load them. You would then need to go through the Expression which you have exposed.</p><p>Let us see how we can query the for <code>Account</code>.<br><figure class="highlight csharp"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> account = context.Accounts.Where(a =&gt; a.Id == id).FirstOrDefault();</span><br></pre></td></tr></table></figure></p><p>This would infact load the value for the property <code>Code</code>. But what if you need to filter on <code>Code</code>? All we have is the <code>Expression&lt;Func&lt;Account, string&gt;&gt;</code> pointing to Code property, but we require an <code>Expression&lt;Func&lt;Account, bool&gt;&gt;</code> which should be passed as the Where clause. For this we’ll need to build an Expression which represent our filter.</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="keyword">static</span> Expression&lt;Func&lt;Account, <span class="keyword">bool</span>&gt;&gt; SearchCode(<span class="keyword">string</span> code)</span><br><span class="line">&#123;</span><br><span class="line">    ParameterExpression param = Expression.Parameter(<span class="keyword">typeof</span>(Account));</span><br><span class="line">    <span class="keyword">var</span> codeExp = Expression.Constant(code);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">var</span> invokedExpr = Expression.Invoke(Account.EFStorageExpression.CodeAccessor,</span><br><span class="line">            param);</span><br><span class="line">    <span class="keyword">var</span> searchCodeExp = Expression.Equal(invokedExpr, codeExp);</span><br><span class="line">    <span class="comment">// a =&gt; a.Code == code</span></span><br><span class="line">    <span class="keyword">return</span> Expression.Lambda&lt;Func&lt;Account, <span class="keyword">bool</span>&gt;&gt;(searchCodeExp, param);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>Using the above, our search on Code can be done like this.<br><figure class="highlight csharp"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> account = context.Accounts.Where(SearchCode(<span class="string">"A001"</span>)).FirstOrDefault();</span><br></pre></td></tr></table></figure></p><p>But during runtime, this fails miserably throwing an exception </p><blockquote><p>Message=The LINQ expression node type ‘Invoke’ is not supported in LINQ to Entities.</p></blockquote><p>The problem is LINQ to Entities does not support Invocation of expressions. This works fine with LINQ to Objects and LINQ to SQL, but not with EF. You would need to use an <a href="https://msdn.microsoft.com/en-us/library/system.linq.expressions.expressionvisitor.aspx" target="_blank" rel="noopener"><code>ExpressionVisitor</code></a> to rewrite the tree.<br>Or use <a href="http://www.albahari.com/nutshell/linqkit.aspx" target="_blank" rel="noopener">LinqKit</a> as I do here. This can be downloaded from Nuget. With this you can use your Expressions with EF.</p><p>The same query above after LinqKit looks as below.<br><figure class="highlight csharp"><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> account = context.Accounts.AsExpandable().</span><br><span class="line">    Where(SearchCode(<span class="string">"A000001"</span>)).FirstOrDefault();</span><br></pre></td></tr></table></figure></p><p>The only addition was <code>AsExpandable()</code> extension before calling your custom expression. Everything works like a charm.</p><p>You can now hide your data and also make use of EF without adding much gunk to your model. </p>]]></content>
    
    <summary type="html">
    
      
      
        &lt;p&gt;In one of my project’s, I am in the process of implementing a complex domain by embracing DDD. I am using Entity Framework and working on
      
    
    </summary>
    
    
      <category term="Entity Framework" scheme="https://www.ajeetyelandur.com/tags/Entity-Framework/"/>
    
  </entry>
  
  <entry>
    <title>Thinking on your feet</title>
    <link href="https://www.ajeetyelandur.com/2016/08/Thinking-on-your-feet/"/>
    <id>https://www.ajeetyelandur.com/2016/08/Thinking-on-your-feet/</id>
    <published>2016-08-16T09:51:39.000Z</published>
    <updated>2016-08-18T09:22:12.865Z</updated>
    
    <content type="html"><![CDATA[<p>I have been away from my blog past few weeks. Most of my weekends have been very busy. But I want to keep the momentum going in contributing towards my blog, so decided to write a product review instead. It addresses an integral part of our code, the posture we take while keying away our creations.<br>I am talking about standing desks if any one of you were wondering. Couple of years ago I dismissed it as a fad. But then heaps of research started surfacing indicating the benefits of standing. Let me rephrase it, indicating the horrors of sitting for long durations.</p><p> This intrigued me. But before jumping and investing in a standing desk, I had to test it out first. Will I like standing and working? These desks don’t come cheap. Would I be really using it and find it comfortable? I knew it would be very difficult to judge any immediate health benefits by using the desk. I am not sure how this can be determined after continued use also. But what I needed to know was how comfortable would it be in using it.</p><p> I scoured the internet and came across a few hacks and Ikea hacks. I even came up with a design to build a frame using PVC pipes to support a laptop and a keyboard, when placed on a table. All required new material purchases, time and effort. Then it hit upon me to simply use cardboard boxes already lying around which were sturdy enough to support a laptop and also high enough to provide ergonomic viewing of the screen. I used shorter box to place my external keyboard and mouse on. This way my forearm was comfortable and parallel to the floor. With this setup I was able to  very comfortably work standing on my laptop without any strain or discomfort. I could easily stand and work for 2 hours at a stretch. And all for zilch. This is what I would call a good POC.</p><p>I had a similar setup at office and tried out standing and working for more than a month. It was much easier at work since I would use my desktop while sitting and switch over to laptop while standing. I just had to clear the boxes whenever I felt like reclaiming my desk space.</p><figure class="half-width"><img src="/images/201608/DIY_standing_desk.jpg" alt="My DIY desk @ home" title="Cardboard box standing desk"></figure><p>Conclusion. Standing and working rocks. I absolutely loved it. One thing I observe is that each time I switch to standing mode, it gives me a fresh boost of energy and focus. It definitely gives you a psychological advantage. </p><p>Now for those who plan to research further, there are basically 2 categories of standing desks. One which sits on top of your existing desk. This involves least rearrangement of your existing furniture and you could get to use your existing cubicle desk or table. The other variety is where the entire desk moves up or down with the help of a motor. These type of desks are more expensive, but also offer you greater flexibility and more usable space.</p><p>When I was ready for a more serious desk, thanks to my company, I settled down with a brand new <a href="http://au.varidesk.com/cubicle-standing-desk-cube-corner-48" target="_blank" rel="noopener">VERIDESK PRO</a>.</p><figure class="half-width"><img src="/images/201608/vpro_standing_desk.jpg" alt="VERIDESK PRO @ Work" title="VERIDESK PRO at Work"></figure><p>It is very convenient to transform it from sitting to standing and vise versa. You can easily pull up the desk using the hand slots and lock it at any height. It does use up some desk space and you might have to rearrange your desk items to suit the new furniture.</p><p>I also love using multiple monitors while working. This desk accommodates two large ones very easily. You also can keep few small items while using it in standing mode.</p><p>Taking it down to sit is even more easier. But I have to warn you! Always ensure there is nothing under the lower platform. It is going to crush it. Be it cables, pen or ear phones. Yes, during the first lowering excersice I crushed my favourite ear phones. Sigh! Now I always look underneath to ensure nothing is going to get crushed. I also stop at the lowest possible level and pull out the keyboard and mouse cables out of the way before lowering it all the way down. You need to push down until it clicks to lock in.</p><p>Motorised desks obviously won’t have this drawback of having to clear or rearrange your desk. Whether down or up, it is the same.</p><p>Whichever standing desk you choose, here the end is more important than the means.</p><figure class="half-width left"><img src="/images/201608/desk_bridge.jpg" alt="Command Bridge" title="Command Bridge"></figure>]]></content>
    
    <summary type="html">
    
      
      
        &lt;p&gt;I have been away from my blog past few weeks. Most of my weekends have been very busy. But I want to keep the momentum going in contribut
      
    
    </summary>
    
    
      <category term="General" scheme="https://www.ajeetyelandur.com/tags/General/"/>
    
      <category term="Review" scheme="https://www.ajeetyelandur.com/tags/Review/"/>
    
  </entry>
  
  <entry>
    <title>Events Part 3 On steroids using TPL Dataflow</title>
    <link href="https://www.ajeetyelandur.com/2016/07/Events-Part-3-with-dataflow/"/>
    <id>https://www.ajeetyelandur.com/2016/07/Events-Part-3-with-dataflow/</id>
    <published>2016-07-31T00:20:49.000Z</published>
    <updated>2016-08-18T09:45:30.295Z</updated>
    
    <content type="html"><![CDATA[<figure class="half-width left"><img src="/images/201607/event_dataflow.png" alt="Events" title="Events"></figure><p>For last couple of days I have been exploring <a href="https://msdn.microsoft.com/en-us/library/hh228603.aspx" target="_blank" rel="noopener">TPL Dataflow</a> in seeing how it can reduce complexity of parallel processing by alleviating callbacks and synchronizations such as locks and sharing data. And I am loving it. I am still exploring this library and the resources and documentations on this seem a bit scarce as of now. I feel there are not enough developers using it as they are not aware or the design pattern is unfamiliar.</p><h4 id="How-can-we-use-Dataflow-to-handle-events"><a href="#How-can-we-use-Dataflow-to-handle-events" class="headerlink" title="How can we use Dataflow to handle events?"></a>How can we use Dataflow to handle events?</h4><p>There was a particular feature which caught my attention since my last 2 articles were based on events, I set out to implement a solution to handle events by using Dataflow. For those of you who are exploring DDD, I recommend taking a look at <a href="http://udidahan.com/2009/06/14/domain-events-salvation/" target="_blank" rel="noopener">Domain Events</a> which helps you keep the domain completely encapsulated. I like the idea here of exposing events as an object instead of a delegate. The immediate benefit I see is that the domain class no longer needs to hold a reference to the handler and the handlers need not explicitly unsubscribe from the events. These were few of the drawback which I had stated earlier by using delegate based <code>event</code> and this addresses them nicely.</p><p>TPL Dataflow is built on top of Task Parallel Library and so with it brings all the familiar support for tasks and asynchronous programming. It is not distributed with the .NET framework and needs to be installed through NuGet. Look for Microsoft.Tpl.Dataflow and you should have System.Threading.Tasks.Dataflow.dll when installed.</p><h4 id="Quick-Intro"><a href="#Quick-Intro" class="headerlink" title="Quick Intro"></a>Quick Intro</h4><p>To get started, Dataflow provides us blocks with pipes through which data can be processed or just flow. A block can either receive (<a href="https://msdn.microsoft.com/en-us/library/mt604405.aspx" target="_blank" rel="noopener"><code>ITargetBlock&lt;T&gt;</code></a>) or offer data (<a href="https://msdn.microsoft.com/en-us/library/mt604404.aspx" target="_blank" rel="noopener"><code>ISourceBlock&lt;T&gt;</code></a>) or do both when combined. The data can be processed by the block or simply transferred. You can push data to a block (<a href="https://msdn.microsoft.com/en-us/library/mt604569.aspx" target="_blank" rel="noopener"><code>Post(input)</code></a>) and get output from it (<a href="https://msdn.microsoft.com/en-us/library/mt604551.aspx" target="_blank" rel="noopener"><code>Receive</code></a>). You can connect two or more blocks together by linking them together (<a href="https://msdn.microsoft.com/en-us/library/mt604558.aspx" target="_blank" rel="noopener"><code>LinkTo(ITargetBlock)</code></a>). That’s where the analogy of pipes comes in. Once you have linked the blocks and send data to the top most block, you need not worry about moving data. The linking would take care of propagating data from one block to another. You can instruct a block to stop accepting input anytime.<br>There are different blocks readily made available and one could create custom blocks too. You can find more information from Microsoft’s <a href="https://www.microsoft.com/en-us/download/details.aspx?id=14782" target="_blank" rel="noopener">Introduction to TPL Dataflow</a>.</p><p>In this article I’ll hit the ground running with Dataflow by using it to handle my domain events. I would be building this on top of my earlier simple domain example used <a href="2016/07/Events-part-1">here</a> and <a href="2016/07/Events-Part-2">here</a>. I would be borrowing the idea of domain event here and represent it explicitly through an instance.</p><p>Domain Event Interface<br><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></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title">IDomainEvent</span></span><br><span class="line">&#123;</span><br><span class="line">    DateTime EventOccurred &#123; <span class="keyword">get</span>; &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p><p>Define my event for product added.<br><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><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">ProductAddedEvent</span> : <span class="title">IDomainEvent</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">public</span> DateTime EventOccurred</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">get</span>; <span class="keyword">private</span> <span class="keyword">set</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> Product Product &#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">ProductAddedEvent</span>(<span class="params">Product product</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        EventOccurred = DateTime.Now;</span><br><span class="line">        Product = product;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p><p>The event would now be raised by the domain object <code>Product</code><br><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">public</span> <span class="title">Product</span>(<span class="params">IBroadcaster mediator</span>)</span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    _mediator = mediator;</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">Add</span>(<span class="params"><span class="keyword">string</span> name, <span class="keyword">int</span> quantity</span>)</span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    Name = name;</span><br><span class="line">    Quantity = quantity;</span><br><span class="line">    _mediator.Post(<span class="keyword">new</span> ProductAddedEvent(<span class="keyword">this</span>));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p><p>As you can see, the domain no longer raises an <code>event</code>, but sends the change in state through an object instance of <code>ProductAddedEvent</code>. Also there are no static calls here to raise the event, but through an injected instance of <code>IBroadcaster</code>.</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></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title">IBroadcaster</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">void</span> Post&lt;T&gt;(T args) <span class="keyword">where</span> T : IDomainEvent;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>All those interested in subscribing to any type of <code>IDomainEvent</code> would do through a concrete instance of <code>ISubscriber</code>.<br><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></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title">ISubscriber</span></span><br><span class="line">&#123;</span><br><span class="line">    IDisposable Subscribe&lt;T&gt;(Action&lt;T&gt; action)</span><br><span class="line">        <span class="keyword">where</span> T : IDomainEvent;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">UnSubscribe</span>(<span class="params">IDisposable obj</span>)</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p><p>Ok. So how do we link all this up and where does Dataflow fit in? Under Dataflow we have a <a href="https://msdn.microsoft.com/en-us/library/mt604434.aspx" target="_blank" rel="noopener"><code>BroadcastBlock&lt;T&gt;</code></a> concrete implementation. Its sole mission is to send a copy of every message published to all linked targets. Optionally you can even issue a cloning function <code>Func&lt;T,T&gt;</code> on how that copy would be offered to the targets.</p><p>We implement both the interfaces here to manage subscription and posting of messages.</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><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></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">EventMediator</span> : <span class="title">ISubscriber</span>, <span class="title">IBroadcaster</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">readonly</span> BroadcastBlock&lt;IDomainEvent&gt; broadcast =</span><br><span class="line">        <span class="keyword">new</span> BroadcastBlock&lt;IDomainEvent&gt;(args =&gt; args);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> Post&lt;T&gt;(T args)</span><br><span class="line">        <span class="keyword">where</span> T : IDomainEvent</span><br><span class="line">    &#123;</span><br><span class="line">        broadcast.Post(args);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> IDisposable Subscribe&lt;T&gt;(Action&lt;T&gt; action)</span><br><span class="line">        <span class="keyword">where</span> T : IDomainEvent</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">var</span> handler = <span class="keyword">new</span> ActionBlock&lt;IDomainEvent&gt;(</span><br><span class="line">            args =&gt; action((T)args));</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> broadcast.LinkTo(handler,</span><br><span class="line">            e =&gt; e.GetType() == <span class="keyword">typeof</span>(T));</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">UnSubscribe</span>(<span class="params">IDisposable obj</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        obj.Dispose();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>Event handlers can subscribe to the events they are interested in. The message would be passed only to those handlers which satisfy the filter condition.<br>Another beauty is anytime a handler can unlink by calling <code>UnSubscribe</code> which just disposes off the <code>IDisposable</code> object returned by the <code>LinkTo</code> call. This would internally unlink and stop sending future messages to that handler.</p><p>That’s it. Now we write the handler and subscribe.</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><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="keyword">class</span> <span class="title">CheckStock</span> : <span class="title">IDisposable</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">private</span> IDisposable _subscription;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">CheckStock</span>(<span class="params">ISubscriber subscriber</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        _subscription = subscriber.Subscribe&lt;ProductAddedEvent&gt;</span><br><span class="line">            (m =&gt; Handler(m));</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">Handler</span>(<span class="params">ProductAddedEvent args</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        Console.WriteLine(<span class="string">"Received by CheckStock,</span></span><br><span class="line"><span class="string">            event at &#123;0&#125;"</span>, args.EventOccurred);</span><br><span class="line">        Console.WriteLine(<span class="string">"Checking stock for &#123;0&#125; "</span>,</span><br><span class="line">            args.Product.Name);</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">Dispose</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        _subscription.Dispose();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>Stitching them up together below we can see them in action.</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><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">var</span> mediator = <span class="keyword">new</span> EventMediator();</span><br><span class="line"><span class="comment">// subscribers</span></span><br><span class="line"><span class="keyword">var</span> stockChecker = <span class="keyword">new</span> CheckStock(mediator);</span><br><span class="line"><span class="keyword">var</span> notify = <span class="keyword">new</span> SendNotification(mediator);</span><br><span class="line"></span><br><span class="line"><span class="comment">// add an inline handler</span></span><br><span class="line"><span class="keyword">var</span> adHoc = mediator.Subscribe&lt;ProductAddedEvent&gt;(</span><br><span class="line">    (m) =&gt; </span><br><span class="line">    &#123; Console.WriteLine(<span class="string">"This is an inline process for &#123;0&#125;"</span>,</span><br><span class="line">    m.Product.Name); &#125;);</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> product = <span class="keyword">new</span> Product(mediator);</span><br><span class="line">product.Add(<span class="string">"Cutting edge"</span>, <span class="number">10</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">//notify.Dispose();</span></span><br><span class="line"><span class="comment">// Unsubscribe one of them</span></span><br><span class="line">mediator.UnSubscribe(adHoc);</span><br><span class="line">product = <span class="keyword">new</span> Product(mediator);</span><br><span class="line">product.Add(<span class="string">"Bleeding edge"</span>, <span class="number">10</span>);</span><br></pre></td></tr></table></figure><p>What we now have is completely unit testable and injectable. Those adhering to DDD would have a fully encapsulated domain. Since the <code>Subscribe</code> takes in an <code>Action&lt;T&gt;</code>, send any action which you can assert when the event is raised.</p><p>If there are many events in a domain, we can define new type implementing <code>IDomainEvent</code></p><figure class="highlight csharp"><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">ProductDeletedEvent</span> : <span class="title">IDomainEvent</span></span><br></pre></td></tr></table></figure><p>Assign a handler for the new event and subscribe</p><figure class="highlight csharp"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">mediator.Subscribe&lt;ProductDeletedEvent&gt;(m =&gt; Handler(m));</span><br></pre></td></tr></table></figure><p>The above handlers would run as concurrent operations. You can send message to as many handlers as required while still being able to maintain throughput. Dataflow allows you to throttle the processing or buffer your messages. Like we have multiple consumers registered with <code>EventMediator</code>, we can have multiple producers sending data through the same instance of <code>EventMediator</code>.</p>]]></content>
    
    <summary type="html">
    
      
      
        &lt;figure class=&quot;half-width left&quot;&gt;&lt;img src=&quot;/images/201607/event_dataflow.png&quot; alt=&quot;Events&quot; title=&quot;Events&quot;&gt;&lt;/figure&gt;

&lt;p&gt;For last couple of da
      
    
    </summary>
    
    
      <category term="DotNet" scheme="https://www.ajeetyelandur.com/tags/DotNet/"/>
    
      <category term="Events" scheme="https://www.ajeetyelandur.com/tags/Events/"/>
    
      <category term="TPL Dataflow" scheme="https://www.ajeetyelandur.com/tags/TPL-Dataflow/"/>
    
  </entry>
  
  <entry>
    <title>Events Part 2 - Asynchronously call handlers</title>
    <link href="https://www.ajeetyelandur.com/2016/07/Events-Part-2/"/>
    <id>https://www.ajeetyelandur.com/2016/07/Events-Part-2/</id>
    <published>2016-07-12T01:19:02.000Z</published>
    <updated>2016-07-26T11:19:06.478Z</updated>
    
    <content type="html"><![CDATA[<figure class="half-width left"><img src="/images/201607/event_many.png" alt="Events" title="Events"></figure><p>In the <a href="/2016/07/Events-part-1/" title="previous post">previous post</a> we saw how to make use of events to extend functionality. We also saw that the execution of the handlers were blocking in nature. The execution was synchronous. There might be a real benefit if the handlers were executed asynchronously without blocking the main thread. Please note that I stressed on might. You have to choose carefully if your operations requires parallelism, because this will complicate your application and would take more resources without any benefit in return. If you foresee many handlers listening to an event, this might give you the desired throughput by offloading them to background threads. If you are making the call from a UI thread, it would also be beneficial to free up the UI thread.<br>Since the events are handled by delegates we can leverage asynchronous methods calls. You can find more information of calling methods asynchronously <a href="https://msdn.microsoft.com/en-us/library/2e08f6yc.aspx" target="_blank" rel="noopener">here</a> as of this writing.</p><p>There are a few things we have to consider and be cautious while dealing with events asynchronously. Events return void by default. When you use the generic delegates (<code>EventHandler</code> / <code>EventHandler&lt;EventArgs&gt;</code>) they always return void. If you use custom delegates which return value with your events, it can become awkward to deal with them when they have multiple handlers attached to them. I am not saying it is not possible, just difficult. You should be able to correlate each handlers return value, if not you would end up only with the value from the last handler’s result. Then again if you require return value from your events, then you might nned to use something other than events.</p><p>The only thing the subject needs to wait for is until all the handlers complete executing. If the thread (main or foreground) from which the event handlers were invoked exits before the handlers return, which would be running on the background thread, then they would be abruptly terminated. You would also only know if there were any exceptions in any of the handlers when you call the <code>EndInvoke</code> of the delegate.</p><p>Asynchronous Programming Pattern (APM) is now obsolete in favour of Task-based Asynchronous Pattern (TAP) and so is Event-Based Asynchronous Pattern (EAP). Calling of Begin<em> method, dealing with <code>IAsynResult</code> and calling of End</em> was not easy to implement and  for a client consuming it, the very least, cumbersome.</p><p>We can now use <a href="https://msdn.microsoft.com/en-us/library/system.threading.tasks.taskfactory.fromasync.aspx" target="_blank" rel="noopener"><code>Task.Factory.FromAsync</code></a> which makes it easy to deal with APM calls by returning a <code>Task</code>. One of its overloads takes the Begin/End pair and while taking any additional arguments that gets passed to these methods. If you find the overloads lacking, then you can provide one of your own wrapper using <code>TaskCompletionSource</code> internally similar to <code>FromAsync</code>.</p><p>For those projects which cannot yet take advantage of TAP, I recommend using callback method when the call completes as described in <a href="https://msdn.microsoft.com/en-us/library/2e08f6yc.aspx" target="_blank" rel="noopener">MSDN</a>. Through this one can handle multiple handlers since the callback would provide you with a unique <code>IAsyncResult</code> so that you don’t need to keep track of it. It provides the most flexibility and least blocking.</p><p>Ok, heading back to implement our asynchronous event handlers, we’ll see that there are not much changes that need to be done to the <a href="/2016/07/Events-part-1/" title="synchronous implementation">synchronous implementation</a>. We would be receiving a <code>Task</code> for each Add. Add method signature would now be look as below</p><figure class="highlight csharp"><table><tr><td class="gutter"><pre><span class="line">1</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">AddAsync</span>(<span class="params"><span class="keyword">string</span> name, <span class="keyword">int</span> quantity</span>)</span></span><br></pre></td></tr></table></figure><p>Notice we are returning a <code>Task</code> and also marked it as <code>async</code>. Also changed the method name to reflect this as per the conventions.<br>One for all, all for one. If one method is async in a chain of calls, then it is best to have all the methods up the order as async-await.</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><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></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">ProductAsyncTask</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">event</span> EventHandler&lt;ProductAsyncTaskEventArgs&gt; Saved;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// simulate data store</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">readonly</span> IDictionary&lt;<span class="keyword">string</span>, ProductAsyncTask&gt; _productRepository;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">ProductAsyncTask</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        _productRepository = <span class="keyword">new</span> Dictionary&lt;<span class="keyword">string</span>, ProductAsyncTask&gt;();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">string</span> Name &#123; <span class="keyword">get</span>; <span class="keyword">set</span>; &#125;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">int</span> Quantity &#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">async</span> Task <span class="title">AddAsync</span>(<span class="params"><span class="keyword">string</span> name, <span class="keyword">int</span> quantity</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        <span class="keyword">if</span> (_productRepository.ContainsKey(name))</span><br><span class="line">        &#123;</span><br><span class="line">            _productRepository[name].Quantity = quantity;</span><br><span class="line">            Console.WriteLine(<span class="string">"Thread# &#123;2&#125;: &#123;0&#125; quantity updated to &#123;1&#125;"</span>,</span><br><span class="line">                name, quantity, Thread.CurrentThread.ManagedThreadId);</span><br><span class="line">            <span class="comment">// return a completed task</span></span><br><span class="line">            <span class="keyword">await</span> Task.CompletedTask;</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">var</span> p = <span class="keyword">new</span> ProductAsyncTask() &#123; Name = name, Quantity = quantity &#125;;</span><br><span class="line">        _productRepository.Add(name, p);</span><br><span class="line">        Console.WriteLine(<span class="string">"Thread# &#123;1&#125;: New Product added - &#123;0&#125; "</span>,</span><br><span class="line">            name, Thread.CurrentThread.ManagedThreadId);</span><br><span class="line">        <span class="comment">// wait without blocking the thread</span></span><br><span class="line">        <span class="keyword">await</span> OnSaved(p);</span><br><span class="line">        Console.WriteLine(<span class="string">"Thread# &#123;1&#125;: Completed add for &#123;0&#125;"</span>,</span><br><span class="line">            name, Thread.CurrentThread.ManagedThreadId);</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">async</span> <span class="keyword">virtual</span> Task <span class="title">OnSaved</span>(<span class="params">ProductAsyncTask p</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        <span class="keyword">var</span> multiDels = Saved <span class="keyword">as</span> EventHandler&lt;ProductAsyncTaskEventArgs&gt;;</span><br><span class="line">        <span class="keyword">if</span> (multiDels == <span class="literal">null</span>)</span><br><span class="line">        &#123;</span><br><span class="line">            <span class="keyword">await</span> Task.CompletedTask;</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// list of event subscribers</span></span><br><span class="line">        Delegate[] delList = multiDels.GetInvocationList();</span><br><span class="line">        Task[] tasks = <span class="keyword">new</span> Task[delList.Length];</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; delList.Length; i++)</span><br><span class="line">        &#123;</span><br><span class="line">            EventHandler&lt;ProductAsyncTaskEventArgs&gt; e = </span><br><span class="line">                delList[i] <span class="keyword">as</span> EventHandler&lt;ProductAsyncTaskEventArgs&gt;;</span><br><span class="line">            Task t = Task.Factory.FromAsync(</span><br><span class="line">                e.BeginInvoke, e.EndInvoke, <span class="keyword">this</span>,</span><br><span class="line">                <span class="keyword">new</span> ProductAsyncTaskEventArgs(p), <span class="literal">null</span>);</span><br><span class="line">            tasks[i] = t;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">await</span> Task.WhenAll(tasks);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>Nothing much has changed inside the <code>AddSync</code> method. We are now awaiting on task or returning a completed task if there is nothing to continue for.<br>Inside <code>OnSaved</code> we see a little bit more action. We are now getting a list of delegates from the <code>MulticastDelegate</code> and use <code>Task.Factory.FromAsync</code> to create a <code>Task</code> for async call of each delegate. If we would have created a <code>Task</code> using <code>Task.Factory.StartNew</code> or <code>Task.Run</code> and made an Invoke of each delegate, the final outcome would be the same. But, this would have blocked each thread on the thread pool until completion since the task would run synchronously. In FromSync, the EndInvoke call would signal the completion and the thread would not be blocked.</p><p>The client application<br><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><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">var</span> productTask = <span class="keyword">new</span> ProductAsyncTask();</span><br><span class="line">productTask.Saved += handler1.SendMail;</span><br><span class="line">productTask.Saved += handler2.DoCall;</span><br><span class="line">productTask.Saved += handler3.Audit;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> t1 = productTask.AddAsync(<span class="string">"Cadbury classic"</span>, <span class="number">10</span>);</span><br><span class="line"><span class="keyword">var</span> t2 = productTask.AddAsync(<span class="string">"Lindt Dark 80%"</span>, <span class="number">10</span>);</span><br><span class="line"><span class="keyword">var</span> t3 = productTask.AddAsync(<span class="string">"Mars"</span>, <span class="number">10</span>);</span><br><span class="line"><span class="keyword">var</span> t4 = productTask.AddAsync(<span class="string">"Cadbury classic"</span>, <span class="number">10</span>);</span><br><span class="line">Console.WriteLine(<span class="string">"Doing some other work here..."</span>);</span><br><span class="line"><span class="keyword">try</span></span><br><span class="line">&#123;</span><br><span class="line">    Task.WaitAll(t1, t2, t3, t4);</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">catch</span> (AggregateException ae)</span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">foreach</span> (<span class="keyword">var</span> e <span class="keyword">in</span> ae.InnerExceptions)</span><br><span class="line">    &#123;</span><br><span class="line">        Console.WriteLine(e.Message);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// unregister</span></span><br><span class="line">productTask.Saved -= handler1.SendMail;</span><br><span class="line">productTask.Saved -= handler2.DoCall;</span><br><span class="line">productTask.Saved -= handler3.Audit;</span><br></pre></td></tr></table></figure></p><p>I have not including any error handling, but since we have a Task returned, we can follow its exception handling pattern. You can have a continuation task on fault or catch the exceptions closest to its source. Also if the subject is long lived, remember to un-register the handlers.</p><p>So we have seen how we can relatively easily make our event handlers run asynchronously using TAP.</p>]]></content>
    
    <summary type="html">
    
      
      
        &lt;figure class=&quot;half-width left&quot;&gt;&lt;img src=&quot;/images/201607/event_many.png&quot; alt=&quot;Events&quot; title=&quot;Events&quot;&gt;&lt;/figure&gt;

&lt;p&gt;In the &lt;a href=&quot;/2016/07/
      
    
    </summary>
    
    
      <category term="DotNet" scheme="https://www.ajeetyelandur.com/tags/DotNet/"/>
    
      <category term="Events" scheme="https://www.ajeetyelandur.com/tags/Events/"/>
    
      <category term="Asynchronous" scheme="https://www.ajeetyelandur.com/tags/Asynchronous/"/>
    
      <category term="Threads" scheme="https://www.ajeetyelandur.com/tags/Threads/"/>
    
  </entry>
  
  <entry>
    <title>Events Part 1 - Food for thought</title>
    <link href="https://www.ajeetyelandur.com/2016/07/Events-part-1/"/>
    <id>https://www.ajeetyelandur.com/2016/07/Events-part-1/</id>
    <published>2016-07-07T06:24:42.000Z</published>
    <updated>2016-07-26T11:19:06.480Z</updated>
    
    <content type="html"><![CDATA[<figure class="half-width left"><img src="/images/201607/event_done.png" alt="Events" title="Events"></figure><p>Event - a notification of a an occurrence or incidence, in programming terms, <em>almost</em> always in the past. Events are not always intuitive or easy to follow since they jump out of the natural control flow.<br>If we consider approaches to extend functionality without uglifying your class immediate thought goes to Dependency Injection. Whether it is a service or a Decorator, they now become the dependencies of your class, albeit through Inversion of Control. I am not saying this is bad, but raising events do not get a fair consideration.</p><p>Yet in so many cases they present as a great choice to extend functionality by reacting to them and even pass data out through to consuming clients. Yes, they can serve as a great vehicle to send data out. If you consider a method which returns void, but raises an event, then even though returning void is able to communicate or send out data through events. Neat.</p><p>Here I would be discussing on how to leverage events and improve code instead of delving into semantics of events and delegates in the DotNet framework. I intend this post to serves as a food for thought on using events to decouple behaviour.<br>Events enable loose coupling and promote separation of concerns. You can delegate (no pun intended) all external processing to the event handlers such as logging, notifications or calls to other services. The event could have multiple subscribers to it. It is a good way to update a subject’s dependents. As you can see, events need not be restricted to UI programming, but are also equally suitable for business components.<br>Let is consider a product domain. I’ll keep the domain logic simple and mundane so that we can focus on events and its usage. We wish to raise an event for each new product that gets added. The handlers(subscribers) who are interested in this event can then react to this.</p><p>Product(Subject)<br><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><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></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">ProductSync</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">event</span> EventHandler&lt;ProductSyncEventArgs&gt; Saved;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// simulate data store</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">readonly</span> IDictionary&lt;<span class="keyword">string</span>, ProductSync&gt; _productRepository;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">ProductSync</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        _productRepository = <span class="keyword">new</span> Dictionary&lt;<span class="keyword">string</span>, ProductSync&gt;();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">string</span> Name &#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">int</span> Quantity &#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">void</span> <span class="title">Add</span>(<span class="params"><span class="keyword">string</span> name, <span class="keyword">int</span> quantity</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        <span class="keyword">if</span> (_productRepository.ContainsKey(name))</span><br><span class="line">        &#123;</span><br><span class="line">            _productRepository[name].Quantity = quantity;</span><br><span class="line">            Console.WriteLine(<span class="string">"Thread# &#123;2&#125;: &#123;0&#125; quantity updated to &#123;1&#125;"</span>,</span><br><span class="line">                name, quantity, Thread.CurrentThread.ManagedThreadId);</span><br><span class="line">            <span class="comment">// no event will be raised here</span></span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">var</span> p = <span class="keyword">new</span> ProductSync() &#123; Name = name, Quantity = quantity &#125;;</span><br><span class="line">        _productRepository.Add(name, p);</span><br><span class="line">        Console.WriteLine(<span class="string">"Thread# &#123;1&#125;: New Product added - &#123;0&#125; "</span>,</span><br><span class="line">            name, Thread.CurrentThread.ManagedThreadId);</span><br><span class="line">        OnSaved(p); <span class="comment">// event raised</span></span><br><span class="line">        Console.WriteLine(<span class="string">"Thread# &#123;1&#125;: Completed add for &#123;0&#125;"</span>,</span><br><span class="line">            name, Thread.CurrentThread.ManagedThreadId);</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">virtual</span> <span class="keyword">void</span> <span class="title">OnSaved</span>(<span class="params">ProductSync p</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        <span class="comment">// check if we have any handlers listening</span></span><br><span class="line">        <span class="comment">// and call them. Below is a short hand to do that.</span></span><br><span class="line">        (Saved <span class="keyword">as</span> EventHandler&lt;ProductSyncEventArgs&gt;)?.Invoke(<span class="keyword">this</span>, <span class="keyword">new</span> ProductSyncEventArgs(p));</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">ProductSyncEventArgs</span> : <span class="title">EventArgs</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">ProductSyncEventArgs</span>(<span class="params">ProductSync product</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        Product = product;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">public</span> ProductSync Product &#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><p>I have deliberately appended Sync to the name. This is to highlight that event handlers subscribing to an event are invoked synchronously. The execution path does jump from one method to another, but the calls are blocking. I have included the thread id to show where the publishers and the subscribers are executing. This is important so that we do not have any misleading assumptions since the execution flow passes to the handlers. We also have a class <code>ProductSyncEventArgs</code> which inherits from <code>EventArgs</code>. This is a standard approach to pass arguments through events within DotNet.</p><p>Let us create a few subscribers or event handlers which need to do some work when event is raised.</p><p>Handlers (Subscribers)<br><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><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></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">NotifyHandler</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">readonly</span> ConsoleWriter cw;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">NotifyHandler</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        cw = <span class="keyword">new</span> ConsoleWriter();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">SendMail</span>(<span class="params"><span class="keyword">object</span> source, ProductSyncEventArgs e</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        Thread.Sleep(<span class="number">1000</span>);</span><br><span class="line">        cw.Write(<span class="string">"Thread# &#123;1&#125;: Sending email for product &#123;0&#125;"</span>,</span><br><span class="line">            ConsoleColor.Red, e.Product.Name,</span><br><span class="line">            Thread.CurrentThread.ManagedThreadId.ToString());</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">ExternalCallHandler</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">readonly</span> ConsoleWriter cw;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">ExternalCallHandler</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        cw = <span class="keyword">new</span> ConsoleWriter();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">DoCall</span>(<span class="params"><span class="keyword">object</span> source, ProductSyncEventArgs e</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        Thread.Sleep(<span class="number">1000</span>);</span><br><span class="line">        cw.Write(<span class="string">"Thread# &#123;1&#125;: New note added for &#123;0&#125;"</span>,</span><br><span class="line">            ConsoleColor.Green, e.Product.Name,</span><br><span class="line">            Thread.CurrentThread.ManagedThreadId.ToString());</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">QuantityAuditHandler</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">readonly</span> ConsoleWriter cw;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">QuantityAuditHandler</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        cw = <span class="keyword">new</span> ConsoleWriter();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">Audit</span>(<span class="params"><span class="keyword">object</span> source, ProductSyncEventArgs e</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        Thread.Sleep(<span class="number">1000</span>);</span><br><span class="line">        cw.Write(<span class="string">"Thread# &#123;2&#125;: Auditing for &#123;1&#125;. Quantity: &#123;0&#125;"</span>,                </span><br><span class="line">            ConsoleColor.Yellow, e.Product.Quantity.ToString(), e.Product.Name,        </span><br><span class="line">            Thread.CurrentThread.ManagedThreadId.ToString());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//helper to colour code console outputs</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">ConsoleWriter</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">Write</span>(<span class="params"><span class="keyword">string</span> message, ConsoleColor colour, <span class="keyword">params</span> <span class="keyword">string</span>[] args</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        Console.ForegroundColor = colour;</span><br><span class="line">        Console.WriteLine(message, args);</span><br><span class="line">        Console.ResetColor();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p><p>The implementations are self-explanatory. I have added <code>Thread.Sleep</code> to simulate a load and helper class to output colour coded text to indicate some behaviour.</p><p>Application (Client)<br><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><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></pre></td><td class="code"><pre><span class="line"><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">static</span> <span class="keyword">void</span> <span class="title">Main</span>(<span class="params"><span class="keyword">string</span>[] args</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        <span class="keyword">var</span> handler1 = <span class="keyword">new</span> NotifyHandler();</span><br><span class="line">        <span class="keyword">var</span> handler2 = <span class="keyword">new</span> ExternalCallHandler();</span><br><span class="line">        <span class="keyword">var</span> handler3 = <span class="keyword">new</span> QuantityAuditHandler();</span><br><span class="line"></span><br><span class="line">        <span class="keyword">var</span> product = <span class="keyword">new</span> ProductSync();</span><br><span class="line">        <span class="comment">// registering handlers</span></span><br><span class="line">        product.Saved += handler1.SendMail;</span><br><span class="line">        product.Saved += handler2.DoCall;</span><br><span class="line">        product.Saved += handler3.Audit;</span><br><span class="line"></span><br><span class="line">        product.Add(<span class="string">"Cadbury classic"</span>, <span class="number">10</span>);</span><br><span class="line">        product.Add(<span class="string">"Lindt Dark 80%"</span>, <span class="number">10</span>);</span><br><span class="line">        product.Add(<span class="string">"Mars"</span>, <span class="number">10</span>);</span><br><span class="line">        product.Add(<span class="string">"Cadbury classic"</span>, <span class="number">10</span>);</span><br><span class="line">        <span class="comment">// unregistering handlers</span></span><br><span class="line">        product.Saved -= handler1.SendMail;</span><br><span class="line">        product.Saved -= handler2.DoCall;</span><br><span class="line">        product.Saved -= handler3.Audit;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure></p><p>When you run the program you get the below output. It clearly shows the synchronous execution and how the Add call is blocked until all the handlers have not returned.<br><img src="/images/201607/Output_sync.png" alt="Program output" title="Sync output"></p><p>When a product is now added there can be other actions executed without having to inject external dependencies to the Product class. I would however like to point out there are a few draw backs in implementing events this way. Astute readers would have already realised that what we have seen is DotNet’s inbuilt implementation of Observer pattern and most of these drawbacks are inherit to Observer pattern.</p><ul><li>Multiple subscribers and publishers make it difficult to maintain and understand code.</li><li>Subscriber and publishers need to know each other. This tight coupling will not allow each to vary independently.</li><li>The publisher holds strong references of each observer. This might create memory leaks when the subscriber does not de-register themselves.</li></ul><p>Here I would not go into addressing each of these issues, but these could be solved using Mediator pattern or Event Aggregate pattern. Again a warning, both these patterns at first glance might seem interchangeable or have the same intent, but they are not. Mediator helps in communicating between unrelated objects, which require co-ordinations. It is not mandatory to use <code>Event</code> type with in Mediator. You would see behaviour inside  Mediator. Event Aggregators as the name suggests deal only in maintaining subscriptions and publishing of events. Once again it need not be done using <code>Event</code> type. You can also manage the references of subscribers to avoid memory leaks. Of course all this would mean more work upfront.<br>Well, like I had mentioned, this post was supposed to be a food for thought and use of events in modelling business logic.<br>In a continuing post I’ll explore how we can call the event handlers asynchronously.</p><p>Do let me know your thoughts through comments on how you have used events in your business layers?</p>]]></content>
    
    <summary type="html">
    
      
      
        &lt;figure class=&quot;half-width left&quot;&gt;&lt;img src=&quot;/images/201607/event_done.png&quot; alt=&quot;Events&quot; title=&quot;Events&quot;&gt;&lt;/figure&gt;

&lt;p&gt;Event - a notification of
      
    
    </summary>
    
    
      <category term="DotNet" scheme="https://www.ajeetyelandur.com/tags/DotNet/"/>
    
      <category term="Events" scheme="https://www.ajeetyelandur.com/tags/Events/"/>
    
      <category term="Design Patterns" scheme="https://www.ajeetyelandur.com/tags/Design-Patterns/"/>
    
  </entry>
  
  <entry>
    <title>Entity Framework stumps SQL performance by defaulting to Unicode</title>
    <link href="https://www.ajeetyelandur.com/2016/06/EF-stumps-SQL-performance-through-Unicode/"/>
    <id>https://www.ajeetyelandur.com/2016/06/EF-stumps-SQL-performance-through-Unicode/</id>
    <published>2016-06-22T06:11:10.000Z</published>
    <updated>2016-07-26T11:19:06.477Z</updated>
    
    <content type="html"><![CDATA[<p>The other day I was working on building a POC which involved a legacy database. I decided to use code first’s fluent API  to map out the configuration since the database was pretty complex and I wanted to control how EF sees it.</p><p>I always have SQL profiler open when programming EF just to make sure EF is doing the right thing. With EF6 onwards you could also use <code>context.Database.Log</code> to review what EF does underneath.</p><p>When I ran my application, I noticed a very visible lag in performance. The table I was working on was very large, but the query was returning only one row, so the impact really stood out.  But I knew that the query would not take that long to execute otherwise. I looked at the query in the profiler and at first glance it looked normal. The query was as simple as it could be. I copied it and ran it under query analyser. The query once again took perceivably longer time to finish. This told me it was not EF alone responsible. Looked at the execution plan, it did not look normal. There was an index scan instead of seek and a lot of parallelism thrown in. Then I took a closer look at the query plan and voila the reason for the slow performance became obvious.</p><p>Entity Framework defaults to Unicode. This is very easy to overlook and under certain EF strategies and configurations it can really hit your SQL performance. Note, this has nothing to do with EF itself, but how SQL server prepares and executes the query provided by EF.</p><p>Let me illustrate with an example.<br>Below is my sample database. Product with many sales.<br><img src="/images/201606/EF_Product_table.png" alt="Database diagram" title="Database Diagram"></p><p>Below is how the mapping is defined.<br><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><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></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="keyword">public</span> <span class="keyword">int</span> Id &#123; <span class="keyword">get</span>; <span class="keyword">set</span>; &#125;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">string</span> Name &#123; <span class="keyword">get</span>; <span class="keyword">set</span>; &#125;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">virtual</span> ICollection&lt;Sale&gt; Sales &#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">Sale</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">int</span> Id &#123; <span class="keyword">get</span>; <span class="keyword">set</span>; &#125;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">int</span> ProdId &#123; <span class="keyword">get</span>; <span class="keyword">set</span>; &#125;</span><br><span class="line">    <span class="keyword">public</span> DateTime SaleDate &#123; <span class="keyword">get</span>; <span class="keyword">set</span>; &#125;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">virtual</span> Product Product &#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">ProductContext</span> : <span class="title">DbContext</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">ProductContext</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function">        : <span class="title">base</span>(<span class="params"><span class="string">"TestDb"</span></span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        Database.SetInitializer&lt;ProductContext&gt;(<span class="literal">null</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> DbSet&lt;Product&gt; Products &#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> DbSet&lt;Sale&gt; Sales &#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.Entity&lt;Product&gt;().HasKey(p =&gt; p.Id)</span><br><span class="line">            .Property(p =&gt; p.Id)</span><br><span class="line">            .HasColumnName(<span class="string">"ProdId"</span>)</span><br><span class="line">            .HasDatabaseGeneratedOption(System.ComponentModel.DataAnnotations</span><br><span class="line">                .Schema.DatabaseGeneratedOption.Identity);</span><br><span class="line"></span><br><span class="line">        modelBuilder.Entity&lt;Product&gt;()</span><br><span class="line">            .HasMany(s =&gt; s.Sales)</span><br><span class="line">            .WithOptional();</span><br><span class="line"></span><br><span class="line">        modelBuilder.Entity&lt;Sale&gt;().HasKey(s =&gt; s.Id)</span><br><span class="line">            .Property(s =&gt; s.Id)</span><br><span class="line">            .HasColumnName(<span class="string">"SaleId"</span>)</span><br><span class="line">            .HasDatabaseGeneratedOption(System.ComponentModel.DataAnnotations</span><br><span class="line">                .Schema.DatabaseGeneratedOption.Identity);</span><br><span class="line"></span><br><span class="line">        modelBuilder.Entity&lt;Sale&gt;()</span><br><span class="line">            .Property(s =&gt; s.ProdId)</span><br><span class="line">            .HasColumnName(<span class="string">"ProdId"</span>);</span><br><span class="line"></span><br><span class="line">        modelBuilder.Entity&lt;Sale&gt;()</span><br><span class="line">            .HasRequired(p =&gt; p.Product)</span><br><span class="line">            .WithMany(s =&gt; s.Sales)</span><br><span class="line">            .HasForeignKey(s =&gt; s.ProdId);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p><p>Below is how EF has interpreted the mapping.<br><img src="/images/201606/EF_Product_model.png" alt="EF model" title="EF Model"></p><p>Let us query for product by name.<br><figure class="highlight csharp"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> prods = prodContext.Products.Where(p =&gt; p.Name == <span class="string">"p3"</span>).ToList();</span><br></pre></td></tr></table></figure></p><p>EF generates the below query.<br><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></pre></td><td class="code"><pre><span class="line"><span class="keyword">SELECT</span> [Extent1].[ProdId] <span class="keyword">AS</span> [ProdId], [Extent1].[<span class="keyword">Name</span>] <span class="keyword">AS</span> [<span class="keyword">Name</span>]</span><br><span class="line"><span class="keyword">FROM</span> [dbo].[Products] <span class="keyword">AS</span> [Extent1]</span><br><span class="line"><span class="keyword">WHERE</span> N<span class="string">'p3'</span> = [Extent1].[<span class="keyword">Name</span>]</span><br></pre></td></tr></table></figure></p><p>Pay attention to the Unicode conversion against the search value(<strong>N</strong>‘p3’). Below is the query plan.<br><img src="/images/201606/EF_query_plan.png" alt="Query plan" title="Query plan"></p><p>Notice how SQL is converting each row to Unicode before the search. This is what is killing your queries performance.<br>The fix is simple. Just let EF know that the column you are mapping to is not Unicode or is VARCHAR. This will allow EF to issue queries without the conversion.<br>Add mapping details for the <code>Name</code> property instead of mapping through convention. Specify either <em>Not</em> Unicode or the column type.<br><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></pre></td><td class="code"><pre><span class="line">modelBuilder.Entity&lt;Product&gt;()</span><br><span class="line">    .Property(p =&gt; p.Name)</span><br><span class="line">    .IsUnicode(<span class="literal">false</span>);</span><br><span class="line">    <span class="comment">//.HasColumnType("varchar");</span></span><br></pre></td></tr></table></figure></p><p>If you approach using model first or code first without an existing database, you would not get into this problem since EF would create the database for you. This is also true if you reverse engineer your database to get your edmx generated. The tool would include the correct datatypes while mapping.</p><p>Now this should help me remember and hopefully help others too from stumbling.</p>]]></content>
    
    <summary type="html">
    
      
      
        &lt;p&gt;The other day I was working on building a POC which involved a legacy database. I decided to use code first’s fluent API  to map out the 
      
    
    </summary>
    
    
      <category term="Entity Framework" scheme="https://www.ajeetyelandur.com/tags/Entity-Framework/"/>
    
  </entry>
  
  <entry>
    <title>Dependency Injection of Custom Claim Authorisation Manager</title>
    <link href="https://www.ajeetyelandur.com/2016/06/DI-Claim-Authorisation/"/>
    <id>https://www.ajeetyelandur.com/2016/06/DI-Claim-Authorisation/</id>
    <published>2016-06-08T08:30:18.000Z</published>
    <updated>2016-07-26T11:19:06.476Z</updated>
    
    <content type="html"><![CDATA[<figure class="half-width left"><img src="/images/201606/ClaimsIcon.png" alt="Claims" title="Claims"></figure><p>Authorisation is one of the most intertwined aspect in an application. We find it the most difficult part to isolate its implementations from rest of the logic. We can overcome partly syntactically through declarative sugar, but for more complex evaluations we might have to go inline. But the application still needs to continue checking the validity of the user.</p><p>The best thing that happened in security since .NET version 4.5 is that Claims became the base for all identity based security and with it we also saw ways through which we could externalise the authorisation logic (and also building of claims). A claim is statement or declaration made about oneself or others. When a user tries to claim access to any resource, the authorisation process assess if they trust the issuer of the claim and evaluates the claim.</p><p>In claim based authorisation the applications need not authenticate individuals and find out about the user. It is presented with claims by the user and the application just uses it to determine if they indeed have the right claim to continue. Now the application is undisturbed (decoupled) by the ever changing roles of a user or whether it has to accommodate any changed roles. As long as the user presents it with the right claims they get access.</p><p>Using claims not just simplifies authorisation, but you can use it to add other important facts about the user. During authentication, we could query multiple systems or specific sources which the application is more interested in and build the claim for the user. These could be email addresses, roles, position, mode of transport, dietary preferences anything which makes sense and need to share that information with applications. You can already see if used correctly how it would make authorisation and personalisation mush more easier in applications.</p><p>Enough with the introductions already! Windows Identity Foundation has now been merged with .NET Framework and we have access to default implementations of <code>ClaimsAuthorizationManager</code>. We can override this programmatically by using <code>IdentityConfiguration</code> or through application configuration file.</p><p>Through configuration:<br><figure class="highlight xml"><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="tag">&lt;<span class="name">system.identityModel</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">identityConfiguration</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">claimsAuthorizationManager</span> <span class="attr">type</span>=<span class="string">"CustomAuthorisationManager"</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">identityConfiguration</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">system.identityModel</span>&gt;</span></span><br></pre></td></tr></table></figure></p><p>One limitation which it presents is that the custom type reference which we provide through configuration must have a 0 argument constructor. Which means we cannot specify any dependencies through the constructor.</p><p>This can however be overcome through code. We can register for the event <code>FederationConfigurationCreated</code> and when the <code>FederationConfiguration</code> is initialised, this event is raised where we can then modify the configuration to assign our own <code>ClaimsAuthorizationManager</code>.</p><p>Through code:<br><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><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></pre></td><td class="code"><pre><span class="line"><span class="keyword">namespace</span> <span class="title">ClaimsAwareApp</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">class</span> <span class="title">App</span></span><br><span class="line">    &#123;</span><br><span class="line">        <span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">Main</span>(<span class="params"><span class="keyword">string</span>[] args</span>)</span></span><br><span class="line"><span class="function"></span>        &#123;</span><br><span class="line">            FederatedAuthentication.FederationConfigurationCreated += </span><br><span class="line">                FederatedAuthentication_FederationConfigurationCreated;</span><br><span class="line"></span><br><span class="line">            <span class="comment">//declarative</span></span><br><span class="line">            DoAction();</span><br><span class="line"></span><br><span class="line">            <span class="comment">// inline</span></span><br><span class="line">            <span class="keyword">var</span> cuthmgr = FederatedAuthentication.FederationConfiguration</span><br><span class="line">                            .IdentityConfiguration.ClaimsAuthorizationManager;</span><br><span class="line">            <span class="keyword">var</span> authContext = </span><br><span class="line">            <span class="keyword">new</span> AuthorizationContext(ClaimsPrincipal.Current, <span class="string">"SomeResource"</span>, <span class="string">"Execute"</span>);</span><br><span class="line">            <span class="keyword">if</span> (cuthmgr.CheckAccess(authContext))</span><br><span class="line">                Console.WriteLine(<span class="string">"DoAction"</span>);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        [<span class="meta">ClaimsPrincipalPermission(</span></span><br><span class="line"><span class="meta">            SecurityAction.Demand,</span></span><br><span class="line"><span class="meta">            Operation = <span class="meta-string">"Execute"</span>,</span></span><br><span class="line"><span class="meta">            Resource = <span class="meta-string">"SomeResource"</span>)</span>]</span><br><span class="line">        <span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">DoAction</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function"></span>        &#123;</span><br><span class="line"></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">static</span> <span class="keyword">void</span> <span class="title">FederatedAuthentication_FederationConfigurationCreated</span>(<span class="params"><span class="keyword">object</span> sender,</span></span></span><br><span class="line"><span class="function"><span class="params">                            FederationConfigurationCreatedEventArgs e</span>)</span></span><br><span class="line"><span class="function"></span>        &#123;</span><br><span class="line">            DependencyFactory factory = <span class="keyword">new</span> DependencyFactory();</span><br><span class="line">            e.FederationConfiguration.IdentityConfiguration.ClaimsAuthorizationManager = </span><br><span class="line">                                        <span class="keyword">new</span> CustomClaimAuthorisation(factory);</span><br><span class="line">            <span class="comment">//e.FederationConfiguration.IdentityConfiguration.ClaimsAuthenticationManager</span></span><br><span class="line">            <span class="comment">//                          = new ClaimsAuthenticationManager();</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">class</span> <span class="title">CustomClaimAuthorisation</span> : <span class="title">ClaimsAuthorizationManager</span></span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">private</span> <span class="keyword">readonly</span> DependencyFactory factory;</span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="title">CustomClaimAuthorisation</span>(<span class="params">DependencyFactory factory</span>)</span></span><br><span class="line"><span class="function"></span>        &#123;</span><br><span class="line">            <span class="keyword">this</span>.factory = factory;</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="keyword">bool</span> <span class="title">CheckAccess</span>(<span class="params">AuthorizationContext context</span>)</span></span><br><span class="line"><span class="function"></span>        &#123;</span><br><span class="line">            <span class="comment">// Get instance from factory</span></span><br><span class="line">            <span class="keyword">using</span> (<span class="keyword">var</span> store = factory.GetStore())</span><br><span class="line">            &#123;</span><br><span class="line">                <span class="comment">// Do your authorisation</span></span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">base</span>.CheckAccess(context);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">class</span> <span class="title">DependencyFactory</span></span><br><span class="line">    &#123;</span><br><span class="line">        <span class="function"><span class="keyword">public</span> MyStore <span class="title">GetStore</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> MyStore();</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">class</span> <span class="title">MyStore</span> : <span class="title">IDisposable</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">Dispose</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function"></span>        &#123;</span><br><span class="line">            <span class="comment">// clean up</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><h6 id="Few-points-to-note"><a href="#Few-points-to-note" class="headerlink" title="Few points to note!"></a>Few points to note!</h6><p>You need to have system.identityModel in your configSections of your configuration file.<br><figure class="highlight xml"><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="tag">&lt;<span class="name">configuration</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">configSections</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">section</span> <span class="attr">name</span>=<span class="string">"system.identityModel"</span></span></span><br><span class="line"><span class="tag">             <span class="attr">type</span>=<span class="string">"System.IdentityModel.Configuration.SystemIdentityModelSection,</span></span></span><br><span class="line"><span class="tag"><span class="string">                    System.IdentityModel, Version=4.0.0.0,</span></span></span><br><span class="line"><span class="tag"><span class="string">                    Culture=neutral, PublicKeyToken=B77A5C561934E089"</span> /&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">configSections</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">configuration</span>&gt;</span></span><br></pre></td></tr></table></figure></p><p>Without the above entry you would run into the below exception.</p><blockquote><p>Message=ID7027: Could not load the identity configuration because no &lt;system.identityModel&gt; configuration section was found.</p></blockquote><p>I think this config section is mandatory to get access to instance of <code>FederationConfiguration</code>. I anyway have not found a work around for this.</p><p>Also note that <code>FederationConfiguration</code> is created as a singleton and you would always get the same instance of <code>ClaimsAuthorizationManager</code> or <code>ClaimsAuthenticationManager</code>. So take care how you manage the lifetime of the objects which you inject inside of these instances. If you need to dispose them after each call, I recommend inject Factory instance instead of the actual concrete instance. This way you can dispose of the concretes and have the factory provide you with a new instance on each call to CheckAccess in the case of authorisation.</p><p>Of course for a web application, one should register the <code>FederationConfigurationCreated</code> event under global.asax App start.</p>]]></content>
    
    <summary type="html">
    
      
      
        &lt;figure class=&quot;half-width left&quot;&gt;&lt;img src=&quot;/images/201606/ClaimsIcon.png&quot; alt=&quot;Claims&quot; title=&quot;Claims&quot;&gt;&lt;/figure&gt;

&lt;p&gt;Authorisation is one of t
      
    
    </summary>
    
    
      <category term="DotNet" scheme="https://www.ajeetyelandur.com/tags/DotNet/"/>
    
      <category term="Security" scheme="https://www.ajeetyelandur.com/tags/Security/"/>
    
      <category term="Claims" scheme="https://www.ajeetyelandur.com/tags/Claims/"/>
    
  </entry>
  
  <entry>
    <title>Practical Patterns: Refactoring with Decorator Design Pattern</title>
    <link href="https://www.ajeetyelandur.com/2016/05/Practical-Patterns-Refactoring-with-Decorator/"/>
    <id>https://www.ajeetyelandur.com/2016/05/Practical-Patterns-Refactoring-with-Decorator/</id>
    <published>2016-05-28T03:22:05.000Z</published>
    <updated>2016-07-26T11:19:06.482Z</updated>
    
    <content type="html"><![CDATA[<p>This post is the second in the series of Design Patterns. You may refer to the earlier article here <a href="/2016/05/Practical-Patterns-Refactoring-with-Bridge/" title="Practical Patterns: Refactoring with Bridge Design Pattern">Practical Patterns: Refactoring with Bridge Design Pattern</a></p><p>One cannot always start by applying design patterns with a new or greenfield project. Majority of the times we are working on existing or brownfield projects. We should be able to identify how the requirement can be retrofit into an existing code while retaining/enhancing maintainability and not adding any technical debts.<br>Earlier we had observed how through Bridge design pattern we were able to structurally separate the classes so they could be extended independently. Bridge pattern is applied at the class level.<br>Decorator design pattern is applied to an object and not to a class. Once again this is done through composition rather than inheritance.</p><p>Let us continue with the code from the <a href="/2016/05/Practical-Patterns-Refactoring-with-Bridge/" title="previous article">previous article</a> in seeing how we can manage new requirements through Decorator pattern.<br>We’ll naturally come across a few new requirements which I am going to conjure up. Firstly, the business requires each transaction to get audited. They also require notification to be sent for certain transactions. If we look at the requirements, we need to add behaviour to the existing implementations. They need to happen when a transaction is taking place.</p><p>Any class which needs to provide a transaction needs to implement <code>ITransaction</code> interface. This is implemented by <code>Personal</code> and <code>Corporate</code> classes. The auditing needs to be done when there is a deposit or withdrawal. We could introduce a base class which implements auditing. This class can be inherited by those who implement <code>ITransaction</code>. But, we would be exhausting the only inheritance allowed on these classes since the language supports only single inheritance. Even if we go ahead with this option, it would affect all the instances of the original class. What about the other requirement? How can we apply notifications to be sent from only certain instances? If and when we decide to remove notifications, how do we efficiently do it? We cannot selectively alter the behaviour of the objects during runtime through sub-classing. Also handling both the requirements in a base class would violate the <a href="https://en.wikipedia.org/wiki/Single_responsibility_principle" target="_blank" rel="noopener">Single Responsibility Principle(SRP)</a>.</p><p>Decorator pattern helps you in applying SRP while also selectively allowing us to add behaviour to objects and in any combination.<br>As many examples showcase, it is not always required or necessary to have an abstract class to implement decorator. But in many cases they might be convenient to have and we’ll see why. But for now we can do without one and have just the concrete decorators. All we need is to implement the interface which we wish to extend and also have a reference of the interfaces object internally. The decorators which we implement can be stacked in any order to add behaviour and repeated too.<img src="/images/201605/Decorator.png" alt="Decorator Pattern"></p><p>The new changes are highlighted in blue.</p><p><code>AuditTransactionDecorator</code> implements the first requirement of audting.<br><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><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">class</span> <span class="title">AuditTransactionDecorator</span> : <span class="title">ITransaction</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">readonly</span> ITransaction transaction;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">AuditTransactionDecorator</span>(<span class="params">ITransaction transaction</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        <span class="keyword">this</span>.transaction = transaction;</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">Deposit</span>(<span class="params"><span class="keyword">decimal</span> amount</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        Console.WriteLine(<span class="string">"Auditing amount BEFORE deposit transaction &#123;0&#125;"</span>, amount);</span><br><span class="line">        <span class="keyword">this</span>.transaction.Deposit(amount);</span><br><span class="line">        Console.WriteLine(<span class="string">"Auditing amount AFTER deposit transaction &#123;0&#125;"</span>, amount);</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">decimal</span> <span class="title">GetBalance</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">this</span>.transaction.GetBalance();</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">Withdraw</span>(<span class="params"><span class="keyword">decimal</span> amount</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        Console.WriteLine(<span class="string">"Auditing amount BEFORE withdraw transaction &#123;0&#125;"</span>, amount);</span><br><span class="line">        <span class="keyword">this</span>.transaction.Withdraw(amount);</span><br><span class="line">        Console.WriteLine(<span class="string">"Auditing amount AFTER withdraw transaction &#123;0&#125;"</span>, amount);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p><p><code>NotifyTransactionDecorator</code> implements the next requirement of notifying.<br><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><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></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title">NotifyTransactionDecorator</span> : <span class="title">ITransaction</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">readonly</span> ITransaction transaction;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">NotifyTransactionDecorator</span>(<span class="params">ITransaction transaction</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        <span class="keyword">this</span>.transaction = transaction;</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">Deposit</span>(<span class="params"><span class="keyword">decimal</span> amount</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        <span class="keyword">this</span>.transaction.Deposit(amount);</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">decimal</span> <span class="title">GetBalance</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">this</span>.transaction.GetBalance();</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">Withdraw</span>(<span class="params"><span class="keyword">decimal</span> amount</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        <span class="keyword">this</span>.transaction.Withdraw(amount);</span><br><span class="line">        <span class="keyword">if</span> (amount &gt; <span class="number">100</span>)</span><br><span class="line">        &#123;</span><br><span class="line">            Console.WriteLine(<span class="string">"NOTIFY: The amount withdrawn has exceeded $100. The amount was &#123;0&#125;"</span>,</span><br><span class="line">             amount);</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><p>As you may notice, we are able to implement the new requirements in isolation and not having to modify the existing code.<br>In our <code>AccountBase</code> where we are creating the instance of type <code>ITransaction</code>, we can now decorate them with the new objects.<br><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><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></pre></td><td class="code"><pre><span class="line"><span class="keyword">abstract</span> <span class="keyword">class</span> <span class="title">AccountBase</span> : <span class="title">IAccount</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">protected</span> ITransaction transactionImp;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">AccountBase</span>(<span class="params"><span class="keyword">string</span> name, AccountType type</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        Name = name;</span><br><span class="line">        <span class="keyword">switch</span> (type)</span><br><span class="line">        &#123;</span><br><span class="line">            <span class="keyword">case</span> AccountType.Personal:</span><br><span class="line">                transactionImp = <span class="keyword">new</span> AuditTransactionDecorator(</span><br><span class="line">                                    <span class="keyword">new</span> Personal(<span class="number">1000</span>));</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">case</span> AccountType.Corporate:</span><br><span class="line">                transactionImp = <span class="keyword">new</span> NotifyTransactionDecorator(</span><br><span class="line">                                    <span class="keyword">new</span> Corporate(<span class="number">5000</span>));</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">default</span>:</span><br><span class="line">                <span class="keyword">throw</span> <span class="keyword">new</span> NotImplementedException(<span class="string">"Unknown account type"</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">abstract</span> <span class="keyword">void</span> <span class="title">Deposit</span>(<span class="params"><span class="keyword">decimal</span> amount</span>)</span>;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">abstract</span> <span class="keyword">void</span> <span class="title">Withdraw</span>(<span class="params"><span class="keyword">decimal</span> amount</span>)</span>;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">abstract</span> <span class="keyword">decimal</span> Balance &#123; <span class="keyword">get</span>; &#125;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">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><p>In line 10 and 14 we inject the original instance into the decorators. The decorators would now call the injected instances method along with its own. We could also stack the decorators together.<br><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></pre></td><td class="code"><pre><span class="line">transactionImp = <span class="keyword">new</span> AuditTransactionDecorator(</span><br><span class="line">                    <span class="keyword">new</span> NotifyTransactionDecorator(</span><br><span class="line">                        <span class="keyword">new</span> Corporate(<span class="number">5000</span>)));</span><br></pre></td></tr></table></figure></p><p>So when do we need an abstract class for decorators? Let’s take a look at our requirements again. For auditing requirement, we needed to decorate only the <em>Deposit</em> and <em>Withdraw</em> methods. For <em>GetBalance</em> we just had to forward the call to the internal reference of the interface’s concrete instance. For the notification, we just needed to add behaviour to the <em>Withdraw</em> method. Each requirement had a different set of methods being decorated. If we had to create multiple decorator classes targeting same methods, then a base class would have helped since it would provide a default implementation to methods which need to only forward the calls and allow us to implement only the targeted methods. This would also serve as a document indicating that classes derived from this base are decorators.<br>For example:<br><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><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">abstract</span> <span class="keyword">class</span> <span class="title">TransactionDecoratorBase</span> : <span class="title">ITransaction</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">internal</span> ITransaction transaction;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">abstract</span> <span class="keyword">void</span> <span class="title">Deposit</span>(<span class="params"><span class="keyword">decimal</span> amount</span>)</span>;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">abstract</span> <span class="keyword">void</span> <span class="title">Withdraw</span>(<span class="params"><span class="keyword">decimal</span> amount</span>)</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">decimal</span> <span class="title">GetBalance</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> transaction.GetBalance();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p><p>The implementation of auditing would look like this-<br><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><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">class</span> <span class="title">AuditTransactionDecorator</span> : <span class="title">TransactionDecoratorBase</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">AuditTransactionDecorator</span>(<span class="params">ITransaction transaction</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        <span class="keyword">this</span>.transaction = transaction;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">override</span> <span class="keyword">void</span> <span class="title">Deposit</span>(<span class="params"><span class="keyword">decimal</span> amount</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        Console.WriteLine(<span class="string">"Auditing amount BEFORE deposit transaction &#123;0&#125;"</span>, amount);</span><br><span class="line">        <span class="keyword">this</span>.transaction.Deposit(amount);</span><br><span class="line">        Console.WriteLine(<span class="string">"Auditing amount AFTER deposit transaction &#123;0&#125;"</span>, amount);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">override</span> <span class="keyword">void</span> <span class="title">Withdraw</span>(<span class="params"><span class="keyword">decimal</span> amount</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        Console.WriteLine(<span class="string">"Auditing amount BEFORE withdraw transaction &#123;0&#125;"</span>, amount);</span><br><span class="line">        <span class="keyword">this</span>.transaction.Withdraw(amount);</span><br><span class="line">        Console.WriteLine(<span class="string">"Auditing amount AFTER withdraw transaction &#123;0&#125;"</span>, amount);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p><p>Which takes us to the classic textbook diagram.<img src="/images/201605/DecoratorClassic.png" alt="Decorator pattern classic example"></p>]]></content>
    
    <summary type="html">
    
      
      
        &lt;p&gt;This post is the second in the series of Design Patterns. You may refer to the earlier article here &lt;a href=&quot;/2016/05/Practical-Patterns-
      
    
    </summary>
    
    
      <category term="DotNet" scheme="https://www.ajeetyelandur.com/tags/DotNet/"/>
    
      <category term="Design Patterns" scheme="https://www.ajeetyelandur.com/tags/Design-Patterns/"/>
    
      <category term="Refactoring" scheme="https://www.ajeetyelandur.com/tags/Refactoring/"/>
    
  </entry>
  
  <entry>
    <title>Practical Patterns: Refactoring with Bridge Design Pattern</title>
    <link href="https://www.ajeetyelandur.com/2016/05/Practical-Patterns-Refactoring-with-Bridge/"/>
    <id>https://www.ajeetyelandur.com/2016/05/Practical-Patterns-Refactoring-with-Bridge/</id>
    <published>2016-05-12T05:47:01.000Z</published>
    <updated>2016-06-02T12:56:00.200Z</updated>
    
    <content type="html"><![CDATA[<p>You would have heard this before - the only thing constant is change. In software how do we prepare ourselves for change? Can we afford to over engineer in anticipation of change or do we create a <a href="https://en.wikipedia.org/wiki/Big_ball_of_mud" target="_blank" rel="noopener">big ball of mud</a> as we continue to accommodate change?</p><p>Only in a perfect world would we be able to realise everything at one time and place. We need to be smart about how we design our software so that we can add/change features to it during its life. <strong>Y</strong>ou <strong>A</strong>ren’t <strong>G</strong>onna <strong>N</strong>eed <strong>I</strong>t (<a href="https://en.wikipedia.org/wiki/You_aren&#39;t_gonna_need_it" target="_blank" rel="noopener">YAGNI</a>) and SOLID would provide us with a good start so that refactoring need not be a pain. Refactoring is all in the mindset and often teams shy away from this practise.</p><p>In this start of my series, I’ll attempt to demonstrate on how we can use design patterns to refactor your existing code. Refactoring is a great approach even when you are working on a new piece of code and not just for modifying or enhancing existing software. It keeps your design light and simple.</p><p>Let us look at an overly simplified example of an account which facilitates in conducting a basic transaction. Let us also assume that this came in as your initial requirement and the client is implemented.<img src="/images/201605/Bridge1.png" alt="Initial solution"></p><p><code>IAccount</code> is the abstraction which the clients would use.<br><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></pre></td><td class="code"><pre><span class="line"><span class="keyword">interface</span> <span class="title">IAccount</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">Deposit</span>(<span class="params"><span class="keyword">decimal</span> amount</span>)</span>;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">Withdraw</span>(<span class="params"><span class="keyword">decimal</span> amount</span>)</span>;</span><br><span class="line">    <span class="keyword">decimal</span> Balance &#123; <span class="keyword">get</span>; &#125;</span><br><span class="line">    <span class="keyword">string</span> Name &#123; <span class="keyword">get</span>; &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p><p><code>SavingAccount</code> provides concrete implementation for <code>IAccount</code>.<br><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><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">class</span> <span class="title">SavingAccount</span> : <span class="title">IAccount</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">decimal</span> _balance = <span class="number">1000</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">SavingAccountLegacy</span>(<span class="params"><span class="keyword">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">        Console.WriteLine(<span class="string">"Opened personal account with balance &#123;0&#125;"</span>, _balance);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">Deposit</span>(<span class="params"><span class="keyword">decimal</span> amount</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        _balance += amount;</span><br><span class="line">        Console.WriteLine(<span class="string">"Deposited: &#123;0&#125; | New balance: &#123;1&#125;"</span>, amount, _balance);</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">Withdraw</span>(<span class="params"><span class="keyword">decimal</span> amount</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        <span class="keyword">if</span> (amount &lt; _balance)</span><br><span class="line">        &#123;</span><br><span class="line">            _balance -= amount;</span><br><span class="line">            Console.WriteLine(<span class="string">"Widthdrawn: &#123;0&#125; | New balance: &#123;1&#125;"</span>, amount, _balance);</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        Console.WriteLine(<span class="string">"Could not withdraw. Current balance is &#123;0&#125;"</span>, _balance);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">decimal</span> Balance</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">get</span> &#123; <span class="keyword">return</span> _balance; &#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">string</span> Name</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">get</span>;</span><br><span class="line">        <span class="keyword">private</span> <span class="keyword">set</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p><p>The client is tightly bound to <code>IAccount</code>.<br><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></pre></td><td class="code"><pre><span class="line"><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">static</span> <span class="keyword">void</span> <span class="title">Main</span>(<span class="params"><span class="keyword">string</span>[] args</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        IAccount account = <span class="keyword">new</span> SavingAccount(<span class="string">"A0001"</span>);</span><br><span class="line">        account.Withdraw(<span class="number">800</span>);</span><br><span class="line">        account.Deposit(<span class="number">100</span>);</span><br><span class="line">        account.Withdraw(<span class="number">400</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p><p>When you run the app you would see an output which indicates a set of transactions. These are from <code>SavingAccount</code> which portray some behaviour.<br><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></pre></td><td class="code"><pre><span class="line">/*</span><br><span class="line">Opened personal account with balance 1000</span><br><span class="line">Widthdrawn: 800 | New balance: 200</span><br><span class="line">Deposited: 100 | New balance: 300</span><br><span class="line">Could not withdraw. Current balance is 300</span><br><span class="line">*/</span><br></pre></td></tr></table></figure></p><p>Down the line the inevitable happens and we have new requirements. There is a need to handle processing of transactions depending on whether the accounts are - personal or corporate. When you start seeing changes, it is time to sit up and consider whether it is good time to refactor your code. You anyway have to handle the requirement and there is a cue that you might see more change coming this way. Refactor now than struggle later.</p><p>One could just derive again from the existing class and provide the 2 new types. The client code is already bound tightly to the abstraction <code>IAccount</code>. Suppose a credit account is required which varies from savings and also requires to have the two flavours(personal &amp; corporate) supported. As you meet new account types or variation thereof, there would be an explosion of classes due to inheritance. You could prevent this by having conditional checks in the existing classes for each account or transaction. But you would only make your code dirty and end up with technical debt. Here you should favour composition over inheritance while also retaining the abstraction.<br><img src="/images/201605/Bridge2.png" alt="Solution with inheritance" title="Bridge Pattern"></p><p>Introducing <a href="https://en.wikipedia.org/wiki/Bridge_pattern" target="_blank" rel="noopener">Bridge pattern</a> here would allow you to separate the abstraction from its implementation. Let us dive into refactoring this code while leveraging this pattern.</p><p>Like the Bridge pattern states let us introduce another level of abstraction for the implementations. Make note that this abstraction is not exposed or known to the client and we’ll shortly see why this is important. You would continue to inherit <code>IAccount</code> to provide different account types, but their implementations would be abstracted away through <code>ITransaction</code>.</p><p>The new refactored diagram.<img src="/images/201605/BridgeFull.png" alt="Refactored with Bridge Pattern" title="Bridge Pattern"></p><p>The client still goes through the earlier interface <code>IAccount</code> which ensures that none of the refactoring impacts the client. The implementers of <code>IAccount</code> would have a concrete instance of <code>ITransaction</code>. This should be not be exposed to the client or be assigned by the client. This way the client is never bound to <code>ITransaction</code> and we can port the client to any underlying concrete implementation without recompiling it. Only the bridge itself and its implementer needs to be compiled. You can now add new type <code>CreditAccount</code> (varying abstraction), but still use the same implementations. Since you have decoupled your abstraction (<code>IAccount</code>) from the implementation (<code>ITransaction</code>), both  can vary independently.</p><p>Abstraction for implementations.<br><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></pre></td><td class="code"><pre><span class="line"><span class="keyword">interface</span> <span class="title">ITransaction</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">Deposit</span>(<span class="params"><span class="keyword">decimal</span> amount</span>)</span>;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">Withdraw</span>(<span class="params"><span class="keyword">decimal</span> amount</span>)</span>;</span><br><span class="line">    <span class="function"><span class="keyword">decimal</span> <span class="title">GetBalance</span>(<span class="params"></span>)</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p><p><em>Note that this interface or base class can be different from the abstraction. They can provide a more finer interface.</em></p><p>Two flavours for an account implementation.<br><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><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></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title">Personal</span> : <span class="title">ITransaction</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">decimal</span> _balance = <span class="number">0</span>;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Personal</span>(<span class="params"><span class="keyword">decimal</span> balance</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        _balance = balance;</span><br><span class="line">        Console.WriteLine(<span class="string">"Opened personal account with balance &#123;0&#125;"</span>, balance);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">Deposit</span>(<span class="params"><span class="keyword">decimal</span> amount</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        _balance += amount;</span><br><span class="line">        Console.WriteLine(<span class="string">"Deposited: &#123;0&#125; | New balance: &#123;1&#125;"</span>, amount, _balance);</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">decimal</span> <span class="title">GetBalance</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> _balance;</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">Withdraw</span>(<span class="params"><span class="keyword">decimal</span> amount</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        <span class="keyword">if</span> (amount &lt; _balance)</span><br><span class="line">        &#123;</span><br><span class="line">            _balance -= amount;</span><br><span class="line">            Console.WriteLine(<span class="string">"Widthdrawn: &#123;0&#125; | New balance: &#123;1&#125;"</span>, amount, _balance);</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        Console.WriteLine(<span class="string">"Could not withdraw. Current balance is &#123;0&#125;"</span>, _balance);</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">class</span> <span class="title">Corporate</span> : <span class="title">ITransaction</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">decimal</span> _balance = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">decimal</span> _overdraft = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">const</span> <span class="keyword">decimal</span> overdraft_factor = <span class="number">0.1</span>m;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Corporate</span>(<span class="params"><span class="keyword">decimal</span> balance</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        _balance = balance;</span><br><span class="line">        Overdraft = _balance;</span><br><span class="line">        Console.WriteLine(<span class="string">"Opened corporate account with balance &#123;0&#125;"</span>, balance);</span><br><span class="line">        Console.WriteLine(<span class="string">"Overdraft stands at &#123;0&#125;"</span>, _overdraft);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">Deposit</span>(<span class="params"><span class="keyword">decimal</span> amount</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        _balance += amount;</span><br><span class="line">        Overdraft = _balance;</span><br><span class="line">        Console.WriteLine(<span class="string">"Deposited: &#123;0&#125; | New balance: &#123;1&#125; | Overdraft: &#123;2&#125;"</span>,</span><br><span class="line">            amount, _balance, Overdraft);</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">decimal</span> <span class="title">GetBalance</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> _balance;</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">Withdraw</span>(<span class="params"><span class="keyword">decimal</span> amount</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        <span class="keyword">if</span> (amount &lt; Overdraft)</span><br><span class="line">        &#123;</span><br><span class="line">            _balance -= amount;</span><br><span class="line">            Overdraft = _balance;</span><br><span class="line">            Console.WriteLine(<span class="string">"Widthdrawn: &#123;0&#125; | New balance: &#123;1&#125; | Overdraft: &#123;2&#125;"</span>,</span><br><span class="line">                amount, _balance, Overdraft);</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        Console.WriteLine(<span class="string">"Could not withdraw. Current overdraft limit &#123;0&#125;"</span>, Overdraft);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">decimal</span> Overdraft</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">get</span></span><br><span class="line">        &#123; <span class="keyword">return</span> _overdraft; &#125;</span><br><span class="line">        <span class="keyword">set</span></span><br><span class="line">        &#123;</span><br><span class="line">            _overdraft = Math.Abs(<span class="keyword">value</span>) + (Math.Abs(<span class="keyword">value</span>) * overdraft_factor);</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><p>Base class which selects the required implementer. This is not absolutely necessary, if we have setup a DI container, we could configure it to inject the concrete implementer directly in to the constructor of the abstraction. But the whole point is to not configure the concrete implementer by the client. Also one could have a factory method to return the required instance.<br><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><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></pre></td><td class="code"><pre><span class="line"><span class="keyword">abstract</span> <span class="keyword">class</span> <span class="title">AccountBase</span> : <span class="title">IAccount</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="comment">// this is protected and hidden from the client</span></span><br><span class="line">    <span class="keyword">protected</span> ITransaction transactionImp;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">AccountBase</span>(<span class="params"><span class="keyword">string</span> name, AccountType type</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        Name = name;</span><br><span class="line">        <span class="keyword">switch</span> (type)</span><br><span class="line">        &#123;</span><br><span class="line">            <span class="keyword">case</span> AccountType.Personal:</span><br><span class="line">                transactionImp = <span class="keyword">new</span> Personal(<span class="number">1000</span>);</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">case</span> AccountType.Corporate:</span><br><span class="line">                transactionImp = <span class="keyword">new</span> Corporate(<span class="number">5000</span>);</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">default</span>:</span><br><span class="line">                <span class="keyword">throw</span> <span class="keyword">new</span> NotImplementedException(<span class="string">"Unknown account type"</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">abstract</span> <span class="keyword">void</span> <span class="title">Deposit</span>(<span class="params"><span class="keyword">decimal</span> amount</span>)</span>;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">abstract</span> <span class="keyword">void</span> <span class="title">Withdraw</span>(<span class="params"><span class="keyword">decimal</span> amount</span>)</span>;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">abstract</span> <span class="keyword">decimal</span> Balance &#123; <span class="keyword">get</span>; &#125;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">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">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">enum</span> AccountType</span><br><span class="line">&#123;</span><br><span class="line">    Personal = <span class="number">0</span>,</span><br><span class="line">    Corporate</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p><p>Refactored SavingAccount<br><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><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">class</span> <span class="title">SavingAccount</span> : <span class="title">AccountBase</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">SavingAccount</span>(<span class="params"><span class="keyword">string</span> name, AccountType type</span>) : <span class="title">base</span>(<span class="params">name, type</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="keyword">override</span> <span class="keyword">void</span> <span class="title">Deposit</span>(<span class="params"><span class="keyword">decimal</span> amount</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        transactionImp.Deposit(amount);</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="keyword">void</span> <span class="title">Withdraw</span>(<span class="params"><span class="keyword">decimal</span> amount</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        transactionImp.Withdraw(amount);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">override</span> <span class="keyword">decimal</span> Balance</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">get</span> &#123; <span class="keyword">return</span> transactionImp.GetBalance(); &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p><p>Finally, the client. Note it still uses the same interface. The client has not changed. You would need a way to decide which implementation to choose.<br><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></pre></td><td class="code"><pre><span class="line"><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">static</span> <span class="keyword">void</span> <span class="title">Main</span>(<span class="params"><span class="keyword">string</span>[] args</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        IAccount account = <span class="keyword">new</span> SavingAccount(<span class="string">"A0001"</span>, AccountType.Personal);</span><br><span class="line">        account.Withdraw(<span class="number">800</span>);</span><br><span class="line">        account.Deposit(<span class="number">100</span>);</span><br><span class="line">        account.Withdraw(<span class="number">400</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p><p>Run the client and you see the same output which you had before refactoring.<br><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></pre></td><td class="code"><pre><span class="line">/*</span><br><span class="line">Opened personal account with balance 1000</span><br><span class="line">Widthdrawn: 800 | New balance: 200</span><br><span class="line">Deposited: 100 | New balance: 300</span><br><span class="line">Could not withdraw. Current balance is 300</span><br><span class="line">*/</span><br></pre></td></tr></table></figure></p><p>But when you have a new interface, you can continue to use the same implementations.<br><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><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">class</span> <span class="title">CreditAccount</span> : <span class="title">AccountBase</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">const</span> <span class="keyword">decimal</span> charge = <span class="number">0.03</span>m;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">CreditAccount</span>(<span class="params"><span class="keyword">string</span> name, AccountType type</span>) : <span class="title">base</span>(<span class="params">name, type</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="keyword">override</span> <span class="keyword">void</span> <span class="title">Deposit</span>(<span class="params"><span class="keyword">decimal</span> amount</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        transactionImp.Deposit(amount);</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="keyword">void</span> <span class="title">Withdraw</span>(<span class="params"><span class="keyword">decimal</span> amount</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        amount = amount + (amount * charge);</span><br><span class="line">        Console.WriteLine(<span class="string">"Credit withdraw surcharge levied: &#123;0&#125;"</span>, amount* charge);</span><br><span class="line">        transactionImp.Withdraw(amount);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">override</span> <span class="keyword">decimal</span> Balance</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">get</span> &#123; <span class="keyword">return</span> transactionImp.GetBalance(); &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p><p>The client which uses the interface <code>IAccount</code> never changes.<br><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><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">class</span> <span class="title">Program</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">Main</span>(<span class="params"><span class="keyword">string</span>[] args</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        IAccount account = <span class="keyword">new</span> SavingAccount(<span class="string">"A0001"</span>, AccountType.Corporate);</span><br><span class="line">        account.Withdraw(<span class="number">800</span>);</span><br><span class="line">        account.Deposit(<span class="number">100</span>);</span><br><span class="line">        account.Withdraw(<span class="number">400</span>);</span><br><span class="line"></span><br><span class="line">        Console.WriteLine(<span class="string">"-----------------------------"</span>);</span><br><span class="line">        account = <span class="keyword">new</span> CreditAccount(<span class="string">"C2102"</span>, AccountType.Personal);</span><br><span class="line">        account.Withdraw(<span class="number">1000</span>);</span><br><span class="line">        account.Deposit(<span class="number">1000</span>);</span><br><span class="line">        account.Withdraw(<span class="number">5000</span>);</span><br><span class="line">        account.Withdraw(<span class="number">200</span>);</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p><p>There is a lot of confusion between Bridge pattern and Strategy pattern. Both their implementations look similar, their UML representations look similar. You would have heard this before, but their intent is different. Now what the heck does that mean?<br>Strategy pattern provides a way to alter behaviour of the class(context) at runtime. The client decides which algorithm it needs to use based on some decision. The client uses the context which can take any instance of the strategy interface. The client is aware of both the context and the interface. The below client code blurs the distinction between Strategy and Bridge.<br><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="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">static</span> <span class="keyword">void</span> <span class="title">Main</span>(<span class="params"><span class="keyword">string</span>[] args</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        IAccount account = <span class="keyword">new</span> SavingAccount(<span class="string">"A0001"</span>);</span><br><span class="line">        <span class="comment">// client injects implementer instance to a property of type ITransaction.</span></span><br><span class="line">        account.Transaction = <span class="keyword">new</span> Personal(<span class="number">1000</span>);</span><br><span class="line">        </span><br><span class="line">        account.Withdraw(<span class="number">800</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p><p>In Bridge pattern, the client is only aware of the abstraction and not the implementation. That was the reason you saw the instance being created internally. This pattern is used to keep your code maintainable structurally. If the client was injecting an instance of implementer, then it would not be a Bridge pattern since the client is changing the behaviour. Also Bridge provides two separate lines of abstractions which allow us to change either on a tangent.</p><p>Next <a href="/2016/05/Practical-Patterns-Refactoring-with-Decorator/" title="Practical Patterns: Refactoring with Decorator Design Pattern">Practical Patterns: Refactoring with Decorator Design Pattern</a></p>]]></content>
    
    <summary type="html">
    
      
      
        &lt;p&gt;You would have heard this before - the only thing constant is change. In software how do we prepare ourselves for change? Can we afford t
      
    
    </summary>
    
    
      <category term="DotNet" scheme="https://www.ajeetyelandur.com/tags/DotNet/"/>
    
      <category term="Design Patterns" scheme="https://www.ajeetyelandur.com/tags/Design-Patterns/"/>
    
      <category term="Refactoring" scheme="https://www.ajeetyelandur.com/tags/Refactoring/"/>
    
  </entry>
  
  <entry>
    <title>Business Logic in database or application</title>
    <link href="https://www.ajeetyelandur.com/2016/05/bl-in-database-or-application/"/>
    <id>https://www.ajeetyelandur.com/2016/05/bl-in-database-or-application/</id>
    <published>2016-05-02T03:12:31.000Z</published>
    <updated>2016-06-02T11:35:14.319Z</updated>
    
    <content type="html"><![CDATA[<p>Many would agree that this has been an age old debate with programmers - where do we place the domain’s business logic? I have frequently been pulled into this discussion especially while dealing with legacy application in either enhancing or re-writing them. It has been less common to encounter such an debate with newer developments and  teams as I find very few programmers venture close to a complex database programming and rely on frameworks which abstract most of the database from them. SQL programming is now seen more like a handicraft skill.</p><p>I would like to base my discussion in the context of enterprise applications, which have a very long life and the only thing constant would be change. I should stress that there are no best practises here, the decisions would vary based on the circumstances and your judgement. In this article I’ll look into the question of placing business logic in a database or within an application’s code. I’ll highlight key points which one should consider and explore further while making this decision. This is mostly an architectural decision and there are no black and white answers here, no perfect solution and one fits all approach.</p><h3 id="What-is-Business-Logic-anyway"><a href="#What-is-Business-Logic-anyway" class="headerlink" title="What is Business Logic anyway?"></a>What is Business Logic anyway?</h3><p>To state in an overly simplified way - application logic generally applied to some data. These may be validations, logical decisions, transformations or processing data in to information. These may be as simple as a line of code or can span multiple steps which may require use of an orchestration. Sometimes they may also not involve any data storage. They are also referred as domain logic. Now you would want to have most of this in one place(ideally) and not scattered all over.</p><h3 id="Database-tier-for-your-business-logic"><a href="#Database-tier-for-your-business-logic" class="headerlink" title="Database tier for your business logic"></a>Database tier for your business logic</h3><figure class="quarter-width"><img src="/images/201605/db_layer_04.png" alt="Using database as business layer" title="Business in database"></figure><p>Database servers are very capable platforms and one can possibly run a very complex application entirely from a database. You can have your business logic written in stored procedures, views, functions and triggers in SQL. In fact during my early days I have written large multi-layered applications where a considerable amount of business logic was written within stored procedures. Multiple levels of processing would be achieved by using table variables or temp tables and pass the final result back to the calling code to be readily consumed. As you can see a lot of the business logic can be written in SQL.</p><h3 id="Application-tier-for-business-logic"><a href="#Application-tier-for-business-logic" class="headerlink" title="Application tier for business logic"></a>Application tier for business logic</h3><figure class="quarter-width"><img src="/images/201605/bl_layer_04.png" alt="Business layer outside of database" title="Business in application tier"></figure><p>This would generally be in your domain layer or a designated layer (business layer) in your app which <em>usually</em> coordinates between the storage layer and the application layers. For the benefit of this article I would not deviate by considering how to build this layer. For most of the cases it would be safe to assume the preferred approach would be employing of an OO language. The database would serve only as a data store.</p><h3 id="Performance"><a href="#Performance" class="headerlink" title="Performance"></a>Performance</h3><p>During my initial days in programming one of my reasons for using stored procedures for business logic was for performance and flexibility. The idea was keeping action close to data and you could modify the business many times without touching the application code. This would reduce a chatty interface and network load by sending smaller payloads. But as it turned out when applications and users grow, too much logic in a database turns out to be a processing bottleneck and maintenance nightmare. You lose out all the advantages you initially started out with when the application and requirements were small.<br>Application’s performance can be can still be high when business logic sits in your application tier while keeping it in a maintainable state. This can be truly appreciated in large applications. However one should still leverage what SQL is best at, at filtering data and set based operations. Database servers are generally singular in an enterprise and serve multiple users and applications. Scaling out a database is much harder than scaling out your application. Under heavy loads database object locks are the biggest contributors in degrading performance which can be alleviated by moving the processing outside of it. I have observed in databases where there are multiple triggers implementing business logic, especially on a single table, when moved outside vastly improved performance by increasing the number of transaction per second under heavy loads.<br>If cached query plans is the reason for sticking with stored procedures for business logic, then you can get the same results in SQL Server using <code>sp_executesql</code> from your data layer. Most of the ORM and micro-ORM internally promote query plan caching.<br>Minimise the trips to your database and reduce the number of data returned and the application tier should give a good performance and also make the maintenance easier. This would be more evident when your applications and database begin to grow. Most of the enterprise applications undergo a lot of churning, focusing on maintainability should be the primary goal.</p><h3 id="Maintainability"><a href="#Maintainability" class="headerlink" title="Maintainability"></a>Maintainability</h3><p>One of the biggest pit falls of having database as your business layer is in its maintainability. There may be arguments out there that if done right and if there is a formalised approach, programming in T-SQL would be as maintainable. SQL is designed to only query/modify the data in a database. T-SQL adds extension to this and gives it procedural language capability. But reuse and abstraction of an implementation is hardly supported.<br>Let’s consider that we have a business case implemented entirely inside a stored procedure. You would definitely be having parameters being passed in and result out from this stored procedure. It is safe to assume that many clients(applications) utilise this stored procedure. Out of blue there is a change request on one of the applications. If this involves changing any of the parameters of the stored procedure, it would break all the applications which are referring it. In an enterprise this is no cakewalk. Extensibility is lost and keeping it DRY(Don’t Repeat Yourself) is very difficult. When programmers are faced with such enhancements, the path of least resistance is to make a copy of the stored procedure while applying the required changes and use it within the concerning app so that rest of the relying apps are not broken.<br>Cyclomatic complexity and LoC (Lines of Code) is a good measure to indicate how maintainable the code is. In OO languages there are numerous design patterns which provide a ubiquitous language which can guide any new team member in refactoring a given code. A stored procedure or database trigger can run in to 100+ LoC easily and it is always a troublesome experience to maintain or troubleshoot even for the original author of that code in T-SQL. Refactoring is not intuitive when dealing with T-SQL.<br>On how many occasions does an organisation require a new team member to work on an existing application? In my opinion the barrier of entry for a new team member is comparatively less when the business logic is in its own layer in the application tier.</p><p>I am not familiar with any testing framework which we can use to unit test database logic implementations so I will refrain from commenting on testability of SQL code. But we have a mature market out there to test your application code.</p><h3 id="Reusability"><a href="#Reusability" class="headerlink" title="Reusability"></a>Reusability</h3><p>In any environment reusability improves code maintainability and brings down the overall cost of building an application. When we are faced with a new requirement which might be a slight modification of an existing code, it is all too tempting to copy and paste the code with slight modifications to meet the new requirement.<br>When you follow OOP, one of its principles is reusability. In fact even in procedural languages, reusability was desirable and could be achieved. With OOP you can target reuse at a very granular level, which is a class or at a coarse level even with growing complexity. Achieving this level of reusability is very difficult in SQL. I am not denying that it is not possible, but not easy. Even at a coarse level it is not that intuitive. Views are a good place to start, but they lack the support of parameters. Moving over to stored procedures, when attempts are made to provide functionality through a stored procedure by generalising it, you would generally see an explosion in the list of parameters in order to accommodate all the applications which intend to use this stored procedure since each may need a slightly different result. At a granular level one would get more mileage by using an inline UDF (User Defined Function) instead of a stored procedure. But be warned, it is not advisable to use scalar UDF due to their poor performance, especially when you include them in multi-row operations.<br>You can also implement business logic which is global and thereby automatically reused through constraints, triggers or unique filtered indexes. Consider constraints for enforcing data integrity if required and triggers only for requirements which are meant for simple auditing. The problem with triggers with implementing business rules is that they are the ninja in an application. They work in stealth. I have spent countless hours trying to figure out reason behind a certain mysterious behaviour only to find that a trigger was responsible for that.<br>I would leave you to explore deeper in each of the reusability options and take an informed decision.</p><h3 id="Integrity-referential-integrity"><a href="#Integrity-referential-integrity" class="headerlink" title="Integrity (referential integrity)"></a>Integrity (referential integrity)</h3><p>Referential integrity (RI) is part of business logic. Traditionally this has always been a part of database and more so because they support it very well. But as complexity of applications increased and more n-tier applications became common, you may realise that most of the integrity rules or validations would need to be repeated in many layers.<br>Let’s consider an example where we have a rich HTML app using REST services which in turn depends on a shared database. These REST services may also be used by other applications. The HTML app uses javascript which encapsulates business logic along with validations and pushes a JSON to the REST service. This JSON would be transformed in to another business object or domain object and all of the same logic or may be more would need to be applied again at this layer. This when persisted to the database would need to meet the RI checks placed here. Even though we strive for DRY, it is not always possible. We could have the validation restricted to one layer only, but that would only delay the result when data is incorrect or worse persist corrupt data. Each option presents with benefits and trade-offs and there are no set rules here. It depends on the needs and a developer might spread this responsibility across database and the domain object.<br>Applications which communicate to multiple databases and where a single database is not the only data store, RI checks have to be done in the business objects or your application layer. Once again ideally you would want to have your business logic in a tier which is commonly shared. Databases are often the best place for implementing RI. However placing rest of the business logic in here too might prove costly in maintenance and be a performance inhibitor when the complexity and size increases. </p><h3 id="Security"><a href="#Security" class="headerlink" title="Security"></a>Security</h3><p>Per se application security does not come under business logic, but it controls which part of business logic user has access to. It is an integral part of any application and business. When you have many applications in an organisation which are serviced by  a single central database, maintaining security (authorisation) at the database seems very tempting. After all we can centrally control what a user can access/execute irrespective of apps entering or leaving the ecosystem.<br>On database objects we can define security at a very granular level. To ease manageability, we can define DB roles and then assign them to DB objects. We can have very capable authorisation through databases. But they have drawbacks and bottlenecks which alone are worth considering to manage authorisation outside of database servers.<br>In order to utilise database authorisation we need to opt for impersonation using windows authentication. SQL authentication would not be the preferred choice in many organisations, but it poses the same problems while being less secure.<figure class="half-width"><img src="/images/201605/sql_ac.png" alt="Impersonating account" title="No connection pooling"></figure></p><p>But with impersonation each individual windows account needs to be mapped to the database server. With this one loses scalability due to no connection pooling, so limiting number of users simultaneously accessing the database. It is the client/application which handles connection pooling based on the connection string. When individual window users connect to the DB server, a pool is created per Windows Identity. When you use a service account or a process account to connect to the database, through effective use of connection pooling you can significantly enhance performance and scalability. You would of course have to pass user context with each call to the database to identify the user.<figure class="half-width"><img src="/images/201605/service_ac.png" alt="Service/trusted account" title="Connection pooling"></figure></p><p>In today’s growing need of interconnected applications and sharing of data, it is often necessary and prudent to know what a user is authorised to do early on. You could store authorisation/membership information of users in a database, which can be queried to build a security context of an user.<br>In today’s growing need of interconnected applications and sharing of data, it is often necessary and prudent to know what a user is authorised to do early on. You could store authorisation/membership information of users in a database, which can be queried to build a security context of an user.</p><h3 id="Conclusion"><a href="#Conclusion" class="headerlink" title="Conclusion"></a>Conclusion</h3><p>My personal preference is to contain business logic in the application tier. However I cannot stress enough on how unique each of your business and technical environments would be for one solution to fit all. From my experience in large enterprise applications, most of the times the data is scattered across different sources or across multiple RDBMS servers. Even if they happen to be concentrated in a single database, keeping logic in the database limits your choice on many fronts and depends also on the teams capabilities. Meanwhile it would be foolish to completely ignore the capabilities of SQL and limit to simple CRUD statements. Let your application tier drive your business logic but also utilise SQL capabilities to maximise performance.</p>]]></content>
    
    <summary type="html">
    
      
      
        &lt;p&gt;Many would agree that this has been an age old debate with programmers - where do we place the domain’s business logic? I have frequently
      
    
    </summary>
    
    
      <category term="Database" scheme="https://www.ajeetyelandur.com/tags/Database/"/>
    
      <category term="Architecture" scheme="https://www.ajeetyelandur.com/tags/Architecture/"/>
    
  </entry>
  
</feed>
