<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="4.3.4">Jekyll</generator><link href="/feed.xml" rel="self" type="application/atom+xml" /><link href="/" rel="alternate" type="text/html" /><updated>2026-11-14T18:19:10+00:00</updated><id>/feed.xml</id><title type="html">Async Thoughts</title><subtitle>A blog by Ashish Vegaraju exploring software development, architecture, and emerging technologies</subtitle><entry><title type="html">Measurement Is a Leadership Tool, Not an Engineering KPI</title><link href="/2026/01/01/measurement-leadership-tool/" rel="alternate" type="text/html" title="Measurement Is a Leadership Tool, Not an Engineering KPI" /><published>2026-01-01T00:00:00+00:00</published><updated>2026-01-01T00:00:00+00:00</updated><id>/2026/01/01/measurement-leadership-tool</id><content type="html" xml:base="/2026/01/01/measurement-leadership-tool/"><![CDATA[<p>This article came out of a very practical need.</p>

<p>As our organization started to scale, the management team wanted a clearer view into engineering velocity. The goal was not to apply pressure, but to understand how the engineering department was performing and whether there was any scope for further optimization.</p>

<p>The underlying intent was straightforward. If we are already delivering well, can we become even more effective? Can we continue to ship high-value features while reducing wasted effort, unnecessary delays, and invisible friction?</p>

<h2 id="why-metrics-entered-the-conversation">Why Metrics Entered the Conversation</h2>

<p>At that point, I was already tracking DORA metrics as part of my role as a technical leader. These were not newly introduced metrics, and they were not added in response to poor performance. In fact, across all four DORA signals, the engineering organization was in a healthy state.</p>

<p>Deployment frequency was strong, lead times were predictable, change failure rates were low, and recovery times were well within acceptable bounds. From a metrics perspective, the team was performing at a level I would consider elite for an organization of our size and complexity.</p>

<p>When the management team asked for visibility into engineering velocity, I consolidated these signals and presented them along with the necessary context. The objective was not to justify performance, but to provide a clear, honest view of how delivery actually worked in practice.</p>

<h2 id="what-became-clear-while-preparing-the-data">What Became Clear While Preparing the Data</h2>

<p>Preparing the data and walking through it carefully led to a deeper realization.</p>

<p>The metrics confirmed that the engineering system was healthy. At the same time, they highlighted patterns that could not be explained by engineering effort alone. Certain fluctuations, even within a strong baseline, reflected decisions made earlier in the lifecycle and outside the immediate control of individual teams.</p>

<p>This forced me to think more carefully about what these numbers really represented.</p>

<p>The metrics were accurate. The interpretation required more nuance.</p>

<h2 id="what-the-metrics-were-actually-reflecting">What the Metrics Were Actually Reflecting</h2>

<p>Over time, I started to see these metrics less as indicators of engineering performance and more as reflections of organizational behavior.</p>

<p>Deployment frequency correlated strongly with how quickly priorities were clarified and decisions were made. Lead time reflected coordination overhead, dependency management, and clarity of ownership more than technical difficulty. Change failure rate pointed to system boundaries and architectural choices rather than individual mistakes. MTTR was influenced heavily by preparedness, documentation, and trust during incidents.</p>

<p>These signals were not telling us whether engineers were working hard. They were showing us how effectively the organization enabled them to work.</p>

<h2 id="where-measurement-often-goes-wrong">Where Measurement Often Goes Wrong</h2>

<p>Measurement tends to fail when metrics are treated as scorecards rather than signals.</p>

<p>When numbers are used to judge teams instead of informing leadership decisions, they lose their value. When teams are measured on outcomes they do not fully control, trust erodes. And when metrics are reviewed without adjusting upstream decisions, they become passive reports instead of active tools.</p>

<p>Strong metrics do not eliminate leadership responsibility. They increase it.</p>

<h2 id="a-more-useful-way-to-think-about-measurement">A More Useful Way to Think About Measurement</h2>

<p>What worked well for us was treating metrics as a starting point for conversation rather than an endpoint.</p>

<p>Instead of asking why a number changed, we asked what conditions produced that change. Instead of focusing on individual teams, we looked at cross-team friction and decision latency. Instead of reacting to short-term variation, we examined long-term patterns.</p>

<p>This approach preserved psychological safety while still allowing us to improve an already strong system.</p>

<h2 id="why-i-am-writing-this">Why I Am Writing This</h2>

<p>I am writing these notes primarily for engineering leaders who are new to the responsibility of measuring engineering performance.</p>

<p>When you first encounter frameworks like DORA, it is easy to assume they are designed to tell you whether your teams are performing well or poorly. In reality, they are far more valuable when used to understand how leadership decisions shape delivery outcomes.</p>

<p>Coming from a context of healthy metrics, this distinction became especially clear to me.</p>

<h2 id="the-shift-that-matters">The Shift That Matters</h2>

<p>High-performing teams do not optimize metrics. They optimize clarity.</p>

<p>Metrics make the absence of clarity visible. They surface decision bottlenecks, structural friction, and hidden risk that would otherwise remain abstract.</p>

<p>If reviewing engineering metrics feels uncomfortable, it is often because they are highlighting decisions that need attention. That discomfort is not a sign of failure. It is a signal that leadership has an opportunity to improve an already strong system.</p>

<p>That, ultimately, is what measurement is for.</p>]]></content><author><name>avegaraju</name></author><category term="Engineering" /><category term="Leadership" /><category term="Metrics" /><category term="DORA" /><summary type="html"><![CDATA[DORA metrics reveal how effectively organizations enable teams to work, not just whether engineers are working hard. What I learned about measurement as a leadership tool.]]></summary></entry><entry><title type="html">Multi agent workflow</title><link href="/2025/09/03/multi-agent-workflow-coding/" rel="alternate" type="text/html" title="Multi agent workflow" /><published>2025-09-03T00:09:00+00:00</published><updated>2025-09-03T00:09:00+00:00</updated><id>/2025/09/03/multi-agent-workflow-coding</id><content type="html" xml:base="/2025/09/03/multi-agent-workflow-coding/"><![CDATA[<h1 id="how-i-started-using-multi-agent-workflow-for-better-code-development">How I Started Using Multi-Agent workflow for Better Code Development</h1>

<p>After working with various AI tools for coding, I found myself stuck in the same pattern. I would ask ChatGPT or Claude to help with a specific problem, get some code, and then move to the next issue. But when I tried to build complete features, especially complex ones, the AI would give me huge code blocks that were hard to test and debug.</p>

<p>Then I discovered something that changed my approach completely. Instead of using one AI for everything, I started working with a multi-agent workflow, i.e specialized AI agents with distinct roles that collaborate like a real development team. I’ve been applying this approach to my personal project which is a location-based web API built with ASP.NET Core and Hexagonal architecture.</p>

<h2 id="the-problem-with-single-ai-approach">The Problem with Single AI Approach</h2>

<p>Let me give you a real example from my current project. I was working on adding authentication using Google and Facebook OAuth providers. When I asked one AI to help with the authentication controller, it gave me a massive controller with login, registration, JWT token generation, user creation, and error handling all in one go.</p>

<p>The code looked impressive but had several issues:</p>

<ul>
  <li>No proper error handling for different OAuth scenarios</li>
  <li>Tests were missing for edge cases like invalid tokens</li>
  <li>Architecture decisions weren’t well thought out</li>
  <li>Too much code to debug if something went wrong</li>
</ul>

<p>This is when I realized that asking one AI to be architect, tester, and developer at the same time doesn’t work well for complex features.</p>

<h2 id="creating-a-multi-agent-workflow">Creating a Multi-Agent Workflow</h2>

<p>I decided to create three specialized agents, each with their own expertise:</p>

<p><strong>The Architect Agent</strong>: This agent focuses only on system design. When I ask about authentication, it thinks about JWT token structure, user repository patterns, OAuth flow security, and how different layers in my hexagonal architecture should interact.</p>

<p><strong>The Tester Agent</strong>: This agent is obsessed with finding problems. It creates test cases for happy paths, edge cases, error scenarios, and security vulnerabilities. It thinks about what could go wrong with OAuth tokens and how to test for it.</p>

<p><strong>The Coder Agent</strong>: This agent takes the architecture decisions and test requirements and implements clean, focused code. It follows TDD principles and makes small, testable changes.</p>

<h2 id="real-example-adding-user-creation-logic">Real Example: Adding User Creation Logic</h2>

<p>Let me show you how these agents worked together on a recent feature. I needed to add user creation logic that would either create a new user or return an existing one based on email.</p>

<h3 id="step-1-architecture-agent">Step 1: Architecture Agent</h3>

<p><strong>Me:</strong> <em>architect</em> “I need to implement user creation logic for my authentication flow. Users can sign up via Google or Facebook OAuth. How should I structure this?”</p>

<p><strong>Architect Agent Response:</strong>
“For user creation with OAuth providers, I would recommend this approach:</p>

<ol>
  <li>Create a UseCase class following your hexagonal architecture pattern</li>
  <li>The UseCase should check if user exists first, then create if needed</li>
  <li>Use the existing IUsersRepository interface for data operations</li>
  <li>Accept a UserUseCaseRequest with email, first name, last name, picture URL, and login provider</li>
  <li>Return just the user ID string to keep it simple</li>
</ol>

<p>Key components:</p>

<ul>
  <li>ICreateUserUseCase interface in Core layer</li>
  <li>CreateUserUseCase implementation in Core layer</li>
  <li>UserUseCaseRequest class for the input data</li>
  <li>IUsersRepository handles the database operations</li>
</ul>

<p>This keeps the business logic separate from OAuth token validation and follows your existing hexagonal architecture pattern.”</p>

<h3 id="step-2-tester-agent">Step 2: Tester Agent</h3>

<p><strong>Me:</strong> <em>tester</em> “Based on this architecture, create comprehensive test cases for the user creation use case.”</p>

<p><strong>Tester Agent Response:</strong>
“Here are the test scenarios for user creation:</p>

<p><strong>Happy Path Tests:</strong></p>

<ol>
  <li>New user creation should return new user ID</li>
  <li>Existing user lookup should return existing user ID</li>
</ol>

<p><strong>Edge Cases:</strong></p>

<ol>
  <li>User exists with same email but different provider</li>
  <li>Empty or null email should throw ArgumentException</li>
  <li>Database connection failures should bubble up properly</li>
</ol>

<p><strong>Integration Tests:</strong></p>

<ol>
  <li>Full OAuth flow with user creation</li>
  <li>Multiple rapid requests for same email (race conditions)</li>
</ol>

<p><strong>Specific Test Cases:</strong></p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">[</span><span class="n">Fact</span><span class="p">]</span>
<span class="k">public</span> <span class="k">async</span> <span class="n">Task</span> <span class="nf">ExecuteAsync_ShouldReturnExistingUserId_WhenUserAlreadyExists</span><span class="p">()</span>

<span class="p">[</span><span class="n">Fact</span><span class="p">]</span>
<span class="k">public</span> <span class="k">async</span> <span class="n">Task</span> <span class="nf">ExecuteAsync_ShouldCreateUserAndReturnUserId_WhenUserDoesNotExist</span><span class="p">()</span>

<span class="p">[</span><span class="n">Fact</span><span class="p">]</span>
<span class="k">public</span> <span class="k">async</span> <span class="n">Task</span> <span class="nf">ExecuteAsync_ShouldThrowException_WhenEmailIsNull</span><span class="p">()</span>
</code></pre></div></div>

<p>Each test should use AutoFixture for test data generation and Moq for repository mocking.”</p>

<h3 id="step-3-coder-agent-first-iteration">Step 3: Coder Agent (First Iteration)</h3>

<p><strong>Me:</strong> <em>coder</em> “Implement the user creation use case, but start small and testable.”</p>

<p><strong>Coder Agent Response:</strong>
“I’ll start with the minimal implementation:</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">interface</span> <span class="nc">ICreateUserUseCase</span>
<span class="p">{</span>
    <span class="n">Task</span><span class="p">&lt;</span><span class="kt">string</span><span class="p">&gt;</span> <span class="nf">ExecuteAsync</span><span class="p">(</span><span class="n">UserUseCaseRequest</span> <span class="n">request</span><span class="p">);</span>
<span class="p">}</span>

<span class="k">public</span> <span class="k">class</span> <span class="nc">CreateUserUseCase</span> <span class="p">:</span> <span class="n">ICreateUserUseCase</span>
<span class="p">{</span>
    <span class="k">private</span> <span class="k">readonly</span> <span class="n">IUsersRepository</span> <span class="n">_usersRepository</span><span class="p">;</span>

    <span class="k">public</span> <span class="nf">CreateUserUseCase</span><span class="p">(</span><span class="n">IUsersRepository</span> <span class="n">usersRepository</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="n">_usersRepository</span> <span class="p">=</span> <span class="n">usersRepository</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="k">public</span> <span class="k">async</span> <span class="n">Task</span><span class="p">&lt;</span><span class="kt">string</span><span class="p">&gt;</span> <span class="nf">ExecuteAsync</span><span class="p">(</span><span class="n">UserUseCaseRequest</span> <span class="n">request</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="c1">// Check if user already exists</span>
        <span class="kt">var</span> <span class="n">existingUserId</span> <span class="p">=</span> <span class="k">await</span> <span class="n">_usersRepository</span><span class="p">.</span><span class="nf">GetUserByEmailAsync</span><span class="p">(</span><span class="n">request</span><span class="p">.</span><span class="n">Email</span><span class="p">);</span>
        <span class="k">if</span> <span class="p">(</span><span class="n">existingUserId</span> <span class="p">!=</span> <span class="k">null</span><span class="p">)</span>
        <span class="p">{</span>
            <span class="k">return</span> <span class="n">existingUserId</span><span class="p">;</span>
        <span class="p">}</span>

        <span class="kt">var</span> <span class="n">userId</span> <span class="p">=</span> <span class="k">await</span> <span class="n">_usersRepository</span><span class="p">.</span><span class="nf">CreateUserAsync</span><span class="p">(</span><span class="n">request</span><span class="p">);</span>
        <span class="k">return</span> <span class="n">userId</span><span class="p">;</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>And the corresponding test:</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">[</span><span class="n">Fact</span><span class="p">]</span>
<span class="k">public</span> <span class="k">async</span> <span class="n">Task</span> <span class="nf">ExecuteAsync_ShouldReturnExistingUserId_WhenUserAlreadyExists</span><span class="p">()</span>
<span class="p">{</span>
    <span class="c1">// Arrange</span>
    <span class="kt">var</span> <span class="n">fixture</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">Fixture</span><span class="p">();</span>
    <span class="kt">var</span> <span class="n">request</span> <span class="p">=</span> <span class="n">fixture</span><span class="p">.</span><span class="n">Create</span><span class="p">&lt;</span><span class="n">UserUseCaseRequest</span><span class="p">&gt;();</span>
    <span class="kt">var</span> <span class="n">existingUserId</span> <span class="p">=</span> <span class="n">fixture</span><span class="p">.</span><span class="n">Create</span><span class="p">&lt;</span><span class="kt">string</span><span class="p">&gt;();</span>
    <span class="kt">var</span> <span class="n">repoMock</span> <span class="p">=</span> <span class="k">new</span> <span class="n">Mock</span><span class="p">&lt;</span><span class="n">IUsersRepository</span><span class="p">&gt;();</span>
    <span class="n">repoMock</span><span class="p">.</span><span class="nf">Setup</span><span class="p">(</span><span class="n">r</span> <span class="p">=&gt;</span> <span class="n">r</span><span class="p">.</span><span class="nf">GetUserByEmailAsync</span><span class="p">(</span><span class="n">request</span><span class="p">.</span><span class="n">Email</span><span class="p">)).</span><span class="nf">ReturnsAsync</span><span class="p">(</span><span class="n">existingUserId</span><span class="p">);</span>

    <span class="c1">// Act &amp; Assert</span>
    <span class="kt">var</span> <span class="n">result</span> <span class="p">=</span> <span class="k">await</span> <span class="n">useCase</span><span class="p">.</span><span class="nf">ExecuteAsync</span><span class="p">(</span><span class="n">request</span><span class="p">);</span>
    <span class="n">result</span><span class="p">.</span><span class="nf">Should</span><span class="p">().</span><span class="nf">Be</span><span class="p">(</span><span class="n">existingUserId</span><span class="p">);</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Next iteration: Add input validation and error handling.”</p>

<h3 id="step-4-testing-with-http-client">Step 4: Testing with HTTP Client</h3>

<p>After implementing the use case, I could test it through my AuthController using HTTP client:</p>

<div class="language-http highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="err">### Test Google OAuth signup
POST http://localhost:5282/api/auth/google-signup
Content-Type: application/json

{
  "idToken": "fake-google-token-for-testing",
  "email": "test@example.com",
  "firstName": "Test",
  "lastName": "User",
  "picture": "https://example.com/picture.jpg"
}

### Test Facebook OAuth signup
POST http://localhost:5282/api/auth/facebook-signup
Content-Type: application/json

{
  "accessToken": "fake-facebook-token",
  "email": "test@example.com"
}
</span></code></pre></div></div>

<h2 id="why-this-approach-works-better">Why This Approach Works Better</h2>

<p><strong>Better Architecture</strong>: The architect agent thinks about long-term implications that I might miss when coding quickly. It suggested using the existing hexagonal architecture pattern instead of putting everything in the controller.</p>

<p><strong>Comprehensive Testing</strong>: The tester agent finds edge cases I wouldn’t think of. It caught issues like race conditions with multiple rapid requests for the same email.</p>

<p><strong>Incremental Development</strong>: The coder agent makes small changes that are easy to test and debug. No more massive code dumps.</p>

<p><strong>Learning</strong>: Each agent’s approach teaches me something. I’ve become better at system design by seeing how the architect agent thinks through problems.</p>

<h2 id="setting-up-your-own-agents">Setting Up Your Own Agents</h2>

<p>You can set up a similar multi-agent workflow using any AI tool that supports custom instructions or configurations. The key idea in agentic development is giving each agent a specific role and making them stick to it.</p>

<p>For each agent, I created specific instructions:</p>

<ul>
  <li>Architect: Focus only on design decisions, don’t write implementation code</li>
  <li>Tester: Create specific test cases, think about edge cases and error scenarios</li>
  <li>Coder: Implement minimal code to pass tests, prefer small incremental changes</li>
</ul>

<h2 id="another-example-location-search-feature">Another Example: Location Search Feature</h2>

<p>Here’s how the agents helped with adding location search functionality to my API:</p>

<p><strong>Architect</strong>: Designed the use case pattern with ITomTomMapsClient port and SearchLocationUseCase implementation, following hexagonal architecture.</p>

<p><strong>Tester</strong>: Created tests for invalid queries, API failures, and response mapping scenarios.</p>

<p><strong>Coder</strong>: Implemented in small steps - first the basic use case, then input validation, then proper error handling.</p>

<p>I could test each iteration using Rider:</p>

<div class="language-http highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="err">### Test location search
GET http://localhost:5282/api/maps/search?query=Amsterdam
Accept: application/json

### Test empty query (should return 400)
GET http://localhost:5282/api/maps/search?query=
Accept: application/json
</span></code></pre></div></div>

<h2 id="the-results">The Results</h2>

<p>Since adopting this approach on my project:</p>

<ul>
  <li>My code quality improved because every feature goes through architectural review</li>
  <li>I catch bugs earlier because of comprehensive test scenarios</li>
  <li>Development feels less overwhelming because I work in small, manageable pieces</li>
  <li>I ship features faster because there’s less debugging of large code changes</li>
</ul>

<p>The best part is that each agent’s output becomes documentation for the feature. The architect’s decisions explain why the system works a certain way, the tester’s scenarios become regression tests, and the coder’s incremental approach makes the git history very clear.</p>

<h2 id="getting-started">Getting Started</h2>

<p>Here’s how to set this up on your own projects:</p>

<h3 id="1-install-claude-code-and-initialize">1. Install Claude Code and Initialize</h3>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># Install from Anthropic's website, then:</span>
claude init
</code></pre></div></div>

<h3 id="2-update-default-claude-markdown-file">2. Update default Claude markdown file</h3>

<p><strong><code class="language-plaintext highlighter-rouge">.claude.md</code></strong>:</p>

<div class="language-markdown highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="gu">## Other project specific guidance below</span>

<span class="nt">&lt;Removed</span> <span class="na">for</span> <span class="na">brevity</span><span class="nt">&gt;</span>

<span class="gu">## Development Commands</span>

<span class="gu">### Build and Test</span>

<span class="gh"># Build the entire solution</span>

dotnet build

<span class="gh"># Run all tests</span>

dotnet test

<span class="gh"># Run specific test project</span>

dotnet test Riderverse.Core.Tests

<span class="gh"># Run the API</span>

dotnet run --project Riderverse.Api

<span class="gu">### Project Structure</span>
<span class="p">
-</span> Controllers handle HTTP requests and delegate to use cases
<span class="p">-</span> Use cases contain business logic and orchestrate repository operations
<span class="p">-</span> Repositories are abstracted behind interfaces in Core.Ports
<span class="p">-</span> External API clients (TomTom) are wrapped in adapter projects

<span class="gu">## Configuration</span>

The API requires these configuration values:
<span class="p">
-</span> <span class="sb">`Jwt:Secret`</span>, <span class="sb">`Jwt:Issuer`</span>, <span class="sb">`Jwt:Audience`</span> for JWT authentication
<span class="p">-</span> <span class="sb">`Maps:ApiKey`</span> for TomTom Maps API
<span class="p">-</span> <span class="sb">`CosmosDb:ConnectionString`</span>, <span class="sb">`CosmosDb:DatabaseId`</span>, <span class="sb">`CosmosDb:ContainerId`</span> for Cosmos DB

<span class="gu">## Testing Framework</span>
<span class="p">
-</span> Uses xUnit for test framework
<span class="p">-</span> AutoFixture for test data generation
<span class="p">-</span> Moq for mocking dependencies
<span class="p">-</span> FluentAssertions for readable assertions

<span class="gu">## Special Agents</span>

When the user prefixes their request with one of these agent names, follow the corresponding instructions:
<span class="p">
-</span> <span class="gs">**architect**</span>: Refer to <span class="sb">`.claude-artchitect.md`</span> - Act as a software architecture specialist focused on system design, scalability, and architectural decisions
<span class="p">-</span> <span class="gs">**tester**</span>: Refer to <span class="sb">`.claude-tester.md`</span> - Act as a QA engineer generating comprehensive test cases with detailed scenarios, prerequisites, steps, and edge cases
<span class="p">-</span> <span class="gs">**coder**</span>: Refer to <span class="sb">`.claude-coder.md`</span> - Act as a senior developer implementing features and tests with clean, maintainable code following best practices

<span class="gu">## Multi-Agent Collaboration</span>
<span class="p">
-</span> Reference outputs from other agents when available
<span class="p">-</span> Ask for clarification if architectural decisions affect your domain
<span class="p">-</span> Provide outputs in formats that other agents can easily consume
</code></pre></div></div>

<h3 id="2-create-agent-configuration-files">2. Create Agent Configuration Files</h3>

<p><strong><code class="language-plaintext highlighter-rouge">.claude-architect.md</code></strong>:</p>

<div class="language-markdown highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="gh"># Architecture Agent</span>

You are a software architect focused on system design and architectural decisions.

<span class="gu">## Your Role</span>
<span class="p">
-</span> Analyze requirements and propose architectural solutions
<span class="p">-</span> Design system components and their interactions
<span class="p">-</span> Consider scalability, maintainability, and performance
<span class="p">-</span> Focus on separation of concerns and clean architecture patterns

<span class="gu">## Guidelines</span>
<span class="p">
-</span> Provide detailed architectural explanations with pros/cons
<span class="p">-</span> Suggest design patterns and architectural approaches
<span class="p">-</span> Think about long-term maintainability
<span class="p">-</span> Don't write implementation code - focus on design decisions

When asked about features, think through the system design first.
</code></pre></div></div>

<p><strong><code class="language-plaintext highlighter-rouge">.claude-tester.md</code></strong>:</p>

<div class="language-markdown highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="gh"># Test Agent</span>

You are a QA specialist focused on comprehensive testing strategies.

<span class="gu">## Your Role</span>
<span class="p">
-</span> Generate test cases covering happy paths, edge cases, and error scenarios
<span class="p">-</span> Design both unit and integration testing approaches
<span class="p">-</span> Think about what could go wrong and how to test for it
<span class="p">-</span> Consider security, performance, and reliability testing

<span class="gu">## Guidelines</span>
<span class="p">
-</span> Create specific, actionable test cases
<span class="p">-</span> Include test data setup and expected outcomes
<span class="p">-</span> Think about concurrent access and race conditions
<span class="p">-</span> Cover both positive and negative test scenarios
<span class="p">-</span> Use testing frameworks like xUnit, Moq, FluentAssertions

Focus on thorough test coverage that catches issues early.
</code></pre></div></div>

<p><strong><code class="language-plaintext highlighter-rouge">.claude-coder.md</code></strong>:</p>

<div class="language-markdown highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="gh"># Coding Agent</span>

You are a senior developer focused on clean, testable implementations.

<span class="gu">## Your Role</span>
<span class="p">
-</span> Implement features following TDD principles
<span class="p">-</span> Write small, incremental changes that are easy to test
<span class="p">-</span> Follow established coding patterns and conventions
<span class="p">-</span> Focus on clean, maintainable code

<span class="gu">## Guidelines</span>
<span class="p">
-</span> Make minimal implementations that pass tests first
<span class="p">-</span> Refactor only after tests are green
<span class="p">-</span> Write self-documenting code with clear naming
<span class="p">-</span> Handle errors appropriately
<span class="p">-</span> Keep changes small and focused

Implement one small piece at a time, ensuring it works before moving on.
</code></pre></div></div>

<h3 id="4-start-using-your-ai-development-team">4. Start Using Your AI Development Team</h3>

<p>Now you can invoke your specialized agents from any terminal:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># Get architectural guidance</span>
architect <span class="s2">"How should I design user authentication with JWT tokens?"</span>

<span class="c"># Generate comprehensive test cases</span>
tester <span class="s2">"Create test cases for user login including edge cases and security scenarios"</span>

<span class="c"># Implement the feature incrementally</span>
coder <span class="s2">"Implement the user login endpoint following TDD principles"</span>
</code></pre></div></div>

<p>The command-line approach makes it feel like you have a real development team working with you. Instead of trying to think about architecture, testing, and implementation all at once, you can focus on one aspect at a time while ensuring nothing gets missed.</p>

<p>This approach has made my side project development more systematic and way less stressful. Even with limited time on weekends, I can build quality features incrementally.</p>

<p>Have you tried anything similar? I’d be interested to know how others are structuring their AI development workflows.</p>]]></content><author><name>avegaraju</name></author><category term="Claude" /><category term="AI" /><category term="agents" /><summary type="html"><![CDATA[How I Started Using Multi-Agent workflow for Better Code Development]]></summary></entry><entry><title type="html">AWS DynamoDB - My notes on single table design</title><link href="/2023/01/13/AWS-DynamoDB-Single-table-design/" rel="alternate" type="text/html" title="AWS DynamoDB - My notes on single table design" /><published>2023-01-13T00:09:00+00:00</published><updated>2023-01-13T00:09:00+00:00</updated><id>/2023/01/13/AWS-DynamoDB-Single-table-design</id><content type="html" xml:base="/2023/01/13/AWS-DynamoDB-Single-table-design/"><![CDATA[<p><img src="../../../../images/blog/banner.jpg" width="100%" height="300px" /></p>

<!-- wp:paragraph -->
<p><span style="font-size:xx-large">W</span>hen it comes to designing a data store for your application, there are many options to choose from, each with its own set of advantages and disadvantages. One option that is gaining popularity among developers is using a single table of Amazon DynamoDB. Also, Amazon strongly recommends designing single table for most of the applications. We recently experimented with using a single table for one of our applications at work and through this article, I will be sharing my experience. I will be discussing the advantages and limitations of using a single table design, as well as the best practices that I researched and learned along the way. We ended up using basic modeling techniques at work, however this article is intended to also share the research I did about some advanced single table design techniques and possible pitfalls. This article might provide some insights into how to effectively use or design a single table. 
<!-- /wp:paragraph --></p>

<!-- wp:paragraph -->

<p>Its always best to come to a common understanding of what is meant by single table design. So Let’s start from basics:</p>

<!-- /wp:paragraph -->

<!-- wp:heading {"level":2} -->
<h2>Introduction</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>In DynamoDB, single-table design is a method of storing all data in a single table, rather than using multiple tables for different data types or use cases. This approach is achieved by using a composite primary key, which consists of both a partition key and a sort key.
A composite primary key allows you to store multiple data types or entities in a single table, while still being able to retrieve and query data efficiently. 
<!-- /wp:paragraph --></p>

<!-- wp:paragraph -->
<p>For example, imagine you have an e-commerce application and you want to store data about customers, orders, and products. With single-table design, you could store all of this data in a single DynamoDB table, using the partition key to distinguish between different types of data, and the sort key to sort data within each partition.
Here’s an example of how you might set up a table:
<!-- /wp:paragraph --></p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>| partition key  | sort key     | other attributes|
---------------------------------------------------
| "customer"     | "customer_id"| name, address, etc|
---------------------------------------------------
| "order"        | "order_id"   | customer_id, total, etc |
---------------------------------------------------
| "product"      | "product_id" | name, price, etc       |

</code></pre></div></div>
<!-- wp:paragraph -->
<p>In this example, the partition key is “entity” and the sort key is “entity_id” . This table can have many other attributes like name, address, price etc. Using this structure, you can retrieve all orders  by using the “order” partition key and order_id as the sort key. Or you can retrieve all product details for a specific product by using “product” as the partition key and the product_id as the sort key.
<!-- /wp:paragraph --></p>

<!-- wp:paragraph -->
<p>With basic definition out of our way, lets dive into the bend of mind that is required to design such a table. Before starting to design a table you have to come up with ways in which you’d like to access data from this table. This is commonly known as “Access Pattern”. In fact, in the previous paragraph what you read about retrieving data with the help of partition and sort keys are indeed access patterns. Coming up with access patterns at the beginning helps to model the table better.
<!-- wp:paragraph --></p>

<!-- wp:heading {"level":2} -->
<h2 id="access-patterns-explained">Access Patterns explained</h2>
<!-- /wp:heading -->
<!-- wp:paragraph -->
<p>Needless to say, just having a partition and sort key on a table cannot support all the possible access patterns. For instance, what if I want to retrieve all orders for a given customer? As you can see in the above table, there is no way you can query that information. This is where GSIs, abbreviation for Global Secondary Index comes to rescue. 
<!-- /wp:paragraph -->
<!-- wp:paragraph -->
Let’s take a look at GSIs and try to understand that with help of an example.
<!-- /wp:paragraph --></p>

<!-- wp:heading {"level":2} -->
<h3 id="global-secondary-indexes">Global Secondary Indexes</h3>
<!-- /wp:heading -->
<!-- wp:paragraph -->
<p>A global secondary index (GSI) in Amazon DynamoDB is a secondary index that has a different partition key than the primary key of the table. This allows you to create and maintain one or more secondary indexes on your DynamoDB table in addition to the primary index.
<!-- /wp:paragraph --></p>

<!-- wp:paragraph -->
<p>Using the same example mentioned before, let’s say you want to query all orders for a give customer_id then you might want to create a GSI on the table to support this access pattern. This GSI would have customer_id as the primary key. 
<!-- /wp:paragraph --></p>

<p><strong>Note</strong>
I am using <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/workbench.settingup.html" target="_blank" rel="noopener" data-mce-href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/workbench.settingup.html">[No Sql Workbench]</a> to model the database table below. I highly recommend to use this tool for modeling, as it makes it easy to quickly visualize the changes made on the model.</p>

<!-- wp:paragraph -->
<p>Pictures are worth 1000 words, so here is a screenshot of how the table is designed with primary and sort key with different attributes. 
<!-- /wp:paragraph --></p>

<p><img src="../../../../images/blog/table-with-attributes.jpg" /></p>

<!-- wp:paragraph -->
<p>Here is the screenshot of GSI to support the access pattern of accessing orders based on a customer_id
<!-- /wp:paragraph --></p>

<p><img src="../../../../images/blog/gsi-orders-by-customer.jpg" /></p>

<!-- wp:paragraph -->
<p>I added some dummy data to show how the GSI was able to support our access pattern.
<!-- /wp:paragraph --></p>

<p><img src="../../../../images/blog/aggregate-view.jpg" /></p>

<!-- wp:paragraph -->
<p>As you can see, the GSI made customer id as the primary key and projected all other attributes related to order in this view.
<!-- /wp:paragraph --></p>

<!-- wp:paragraph -->
<p>Similarly its is easy to create GSIs to support additional patterns in future.
<!-- /wp:paragraph --></p>

<!-- wp:paragraph -->
<p>GSI is not the only way to support additional access patterns, there are three more ways to support additional access patterns:
<!-- /wp:paragraph --></p>

<ul>
  <li>
    <p>Local Secondary Index (LSI): Similar to GSI but only allows to use the same partition key but different sort key. It can be useful if you only need to change the sort key and are fine with the queries always happening within a single partition.</p>
  </li>
  <li>
    <p>Scans and Queries: Another option is to use the Scan and Query operations provided by DynamoDB. These operations allow you to retrieve data from your table based on any attribute, but they can be less efficient than using a well-designed index. Scans and queries can be useful when you need to perform ad-hoc queries or retrieve data that doesn’t fit easily into a predefined index.</p>
  </li>
  <li>
    <p>Dynamic Attributes: You can also make your schema more flexible by allowing dynamic attributes. This allows you to add arbitrary new attributes to your table, allowing you to store more information on your items, and potentially, enable new access patterns with it. For instance, you can create an attribute of type <code class="language-plaintext highlighter-rouge">map</code> and add data in the form of key value pairs. In the below schema, dynamic_attribute is a map and it can store any additional information that might be required about a customer</p>
  </li>
</ul>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>{
    "pk": "customer#1",
    "sk": "info",
    "name": "John Smith",
    "email": "john.smith@test.com",
    "dynamic_attribute": {
        "phoneNumber": "+31 67777777",
        "address": "123 some street, 3332AA"
    }
}
</code></pre></div></div>

<!-- wp:heading {"level":4} -->
<p><strong>Note</strong>
<!-- /wp:heading {"level":2} -->
<!-- wp:paragraph -->
It’s important to keep in mind that adding new access patterns to an existing table can have an impact on the performance and cost of your application, so you should carefully evaluate any changes you make. For example, creating new GSIs can increase the amount of data stored in your table and the read/write capacity needed to support them.
<!-- /wp:paragraph --></p>

<!-- wp:heading {"level":2} -->
<h2 id="guidance-for-creating-partition-key-for-high-volume-applications">Guidance for creating partition key for high volume applications</h2>
<!-- /wp:heading {"level":4} -->

<!-- wp:paragraph -->
<p>When you choose an appropriate partition key, it should be chosen in such a way that it naturally distributes the requests across partitions in an even manner. This can be achieved by choosing a partition key that has a high cardinality, meaning that it has a large number of unique values. This will ensure that the requests are spread across multiple partitions and reduce the chance of a hot partition (more about this is explained below).
<!-- /wp:paragraph --></p>

<!-- wp:paragraph -->
<p>For example, if you have an e-commerce application and want to store information about different products, you could choose the product id as a partition key. This would ensure that the requests for different products are spread across different partitions and would reduce the chance of a hot partition.
<!-- /wp:paragraph --></p>

<!-- wp:paragraph -->
<p>Another example is if you have a customer data on DynamoDB and you have customer Id as partition key but most of the requests are for a specific customer then customer Id partition will become hot partition. To avoid this, you can use salted partition keys, where you add some random value to partition key before storing, this will ensure that requests are spread across all partitions.
<!-- /wp:paragraph --></p>

<!-- wp:heading {"level":2} -->
<h2 id="consequences-of-bad-design">Consequences of bad design</h2>
<!-- /wp:heading {"level":2} -->

<!-- wp:paragraph -->
<p>There are consequences of wrong choice of partition keys. A wrong choice may lead to a specific partition to be accessed over and over again resulting in creating a so called “Hot partition”.
<!-- /wp:paragraph --></p>

<!-- wp:heading {"level":3} -->
<h4 id="hot-partition">Hot Partition</h4>
<!-- /wp:heading {"level":3} -->

<!-- wp:paragraph -->
<p>Hot partition can occur when the access patterns of a single table design are not well-distributed across the table’s partition key, resulting in a disproportionate number of requests going to a single partition. This can cause performance issues, such as increased latency and throttling.
<!-- /wp:paragraph --></p>

<!-- wp:paragraph -->
<p>A common cause of hot partitions is when the access pattern is not evenly distributed. For example, if most of the requests are for a specific partition key value then that partition will become hot.
<!-- /wp:paragraph --></p>

<!-- wp:heading {"level":3} -->
<h4 id="mitigation-techniques">Mitigation techniques</h4>
<!-- /wp:heading {"level":3} -->

<!-- wp:paragraph -->
<p>There are several ways to mitigate hot partitions in DynamoDB Single Table Design:
<!-- /wp:paragraph --></p>

<ul>
  <li>
    <p><strong>Scaling:</strong> One way to address hot partitions is to scale the read and write capacity of the table to handle the increased traffic.</p>
  </li>
  <li>
    <p><strong>Spread the access evenly:</strong> By choosing an appropriate partition key and distributing the access patterns evenly across the partition key, you can reduce the likelihood of hot partitions.</p>
  </li>
  <li>
    <p><strong>Use advanced partitioning techniques:</strong> By using advanced partitioning techniques like dynamic partitioning, where the partition key is computed at runtime based on the data, you can also reduce the likelihood of hot partitions. More on this a later.</p>
  </li>
  <li>
    <p><strong>Use Time To Live (TTL) attribute:</strong> you can use DynamoDB’s TTL feature to automatically delete old data, which can help to avoid hot partitions caused by stale data.</p>
  </li>
  <li>
    <p><strong>Use read replicas:</strong> If you are using a single table design and the read hot partition is a concern, you can make use of read replicas. This will replicate the data to multiple tables and read requests can be distributed across them.</p>
  </li>
</ul>

<!-- wp:heading {"level":3} -->
<h3 id="dynamic-partitioning">Dynamic partitioning</h3>
<!-- /wp:heading {"level":3} -->

<!-- wp:paragraph -->
<p>Dynamic partitioning in DynamoDB is a technique that allows you to spread data across multiple partitions by changing the partition key based on the data. This can be useful when dealing with large amounts of data, or when you expect the access patterns to change over time.
<!-- /wp:paragraph --></p>

<!-- wp:paragraph -->
<p>One way to achieve dynamic partitioning in DynamoDB is to use a computed partition key. For example, instead of using a simple partition key like a user ID, you could use a hash of the user ID combined with a timestamp. This way, new items with the same user ID will be spread across different partitions based on the timestamp, reducing the chance of a hot partition caused by a monotonically increasing partition key.
<!-- /wp:paragraph --></p>

<!-- wp:paragraph -->
<p>Another way to achieve dynamic partitioning is to use a partition key that is derived from the data. For example, if you are storing documents, you could use the first letter of the document title as the partition key. This way, the data will be spread across partitions based on the first letter of the title, and the access patterns will be evenly distributed.
<!-- /wp:paragraph --></p>

<!-- wp:paragraph -->
<p>Here is an example of how you could use dynamic partitioning to store tweets in DynamoDB:
<!-- /wp:paragraph --></p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>var date = DateTime.Now;
var timestamp = date.Ticks;
var tweetText = "This is my tweet!";
var tweetUserId = "1001";

using (var md5 = MD5.Create())
{
    var hash = md5.ComputeHash(Encoding.UTF8.GetBytes(tweetUserId));
    var partitionKey = $"tweet_{BitConverter.ToString(hash).Replace("-", "")}_{timestamp}";
    var doc = new Document();
    doc["partitionKey"] = partitionKey;
    doc["tweet"] = tweetText;
    doc["tweetUserId"] = tweetUserId;
    var client = new AmazonDynamoDBClient();
    var request = new PutItemRequest
    {
        TableName = "tweets",
        Item = doc
    };
    var response = await client.PutItemAsync(request);
}

</code></pre></div></div>

<!-- wp:paragraph -->
<p>here the partition key <code class="language-plaintext highlighter-rouge">partitionKey</code> is generated by concatenating the hash of the <code class="language-plaintext highlighter-rouge">tweetUserId</code> and a timestamp. This ensures that tweets by the same tweet user are spread across different partitions based on the timestamp and not clustered on the same partition key, thus reducing the chance of hot partition.
<!-- /wp:paragraph --></p>

<!-- wp:heading {"level":2} -->
<h2 id="when-to-avoid-single-table-design">When to avoid single table design</h2>
<!-- /wp:heading {"level":3} -->

<!-- wp:paragraph -->
<p>While single table design in DynamoDB can be powerful and efficient for many types of applications, there are certain cases where it may not be the best choice. Here are a few examples of when a single table design might not be suitable:
<!-- /wp:paragraph --></p>

<ul>
  <li>
    <p><strong>Applications with highly relational data:</strong></p>

    <p>Single table design can work well for storing denormalized data, but if your data has complex relationships and you need to perform joins across tables, a single table design may not be the best option. In this case, it may be more appropriate to use a relational database like Amazon RDS or MySQL.</p>
  </li>
  <li>
    <p><strong>Applications with very high write loads:</strong></p>

    <p>Single table design allows you to horizontally scale your read and write capacity, but if your application requires extremely high write loads, it may be more cost-effective to use a different storage solution that is optimized for write-intensive workloads, such as Amazon S3 or Amazon Redshift.</p>
  </li>
  <li>
    <p><strong>Applications that need advanced query capabilities:</strong></p>

    <p>While single table design can support complex filtering and sorting using global secondary indexes and Elasticsearch, some applications may require more advanced querying capabilities like geospatial indexing and full-text search. In this case, it might be more appropriate to use a different database solution such as Amazon Elasticsearch service or Amazon RDS for PostgreSQL.</p>
  </li>
  <li>
    <p><strong>Applications that need to support very large items:</strong></p>

    <p>DynamoDB has a limit of 400 KB for item size. If your item size is likely to exceed this limit, then you may need to consider using a different storage solution like Amazon S3 or Amazon Redshift</p>
  </li>
  <li>
    <p><strong>Applications with unpredictable access patterns:</strong></p>

    <p>Single table design is based on the primary key, if the access patterns are not predictable it could lead to uneven distribution of the data and cause hot partitions. In this case, you might want to consider using a different database solution like Amazon RDS, which allows you to create read replicas to handle uneven read workloads.</p>
  </li>
</ul>

<!-- wp:paragraph -->
<p>The article is quite long, however I believe I’ve just scratched the surface of this design technique. For further reading I would advise to refer to the <a href="https://docs.aws.amazon.com/dynamodb/index.html" target="_blank" rel="noopener" data-mce-href="https://docs.aws.amazon.com/dynamodb/index.html">AWS documentation on DynamoDB</a> and watch <a href="https://www.youtube.com/watch?v=Xn12QSNa4RE" target="_blank" rel="noopener" data-mce-href="https://www.youtube.com/watch?v=Xn12QSNa4RE">this video</a> (a bit lengthy, but worth watching) by Rick Houlihan where he explained the technique quite nicely.
<!-- /wp:paragraph --></p>

<!-- wp:paragraph -->
<p>Please <a href="https://ashishvegaraju.com/contact" target="_blank" rel="noopener" data-mce-href="https://ashishvegaraju.com/contact">contact me</a> if you have any questions on this topic and feel free to share it with others if you think it is useful!
<!-- /wp:paragraph --></p>]]></content><author><name>avegaraju</name></author><category term="Single table design" /><category term="AWS" /><category term="dynamoDB" /><summary type="html"><![CDATA[]]></summary></entry><entry><title type="html">Test doubles ; Over the wire</title><link href="/2019/03/01/test-doubles-over-the-wire/" rel="alternate" type="text/html" title="Test doubles ; Over the wire" /><published>2019-03-01T00:09:00+00:00</published><updated>2019-03-01T00:09:00+00:00</updated><id>/2019/03/01/test-doubles-over-the-wire</id><content type="html" xml:base="/2019/03/01/test-doubles-over-the-wire/"><![CDATA[<!-- wp:paragraph {"customFontSize":12} -->
<p style="font-size:12px;"><strong>Please note</strong>: If the code snippets in this article are not visible on your mobile browser then try to view this article with <em>Desktop site</em> option enabled.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph {"dropCap":true} -->
<p class="has-drop-cap">Developing microservices is complex and testing its integration is even  more complex. Assuring availability of all the inter-dependent services with up-to-date builds in the test environment is quite a tedious &amp; costly setup to maintain. Stubs and mocks on the other hand are cheap, easily maintainable and they make integration tests predictable and repeatable. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Almost two years ago, we faced a problem at work where we were desperately looking for a solution to test multiple Web API interactions with an external system over HTTP. In short, we wanted a hassle free mechanism to stub and verify invocation of an external service. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>We researched and came across <a href="http://www.mbtest.org/">Mountebank</a>, which was not only painful to configure, but was error prone too. To top it all off, configuring dynamic behavior required enabling javascript injection. No points for guessing, the security team of my company outrightly rejected the request to enable javascript injection on any of our servers. Not to mention, no clean way to deploy and integrate it with our CI/CD pipelines. Later, due to various constraints, we decided to spend our time on delivering new features instead of solving this problem. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Feeling dejected, I started <a href="https://github.com/avegaraju/Imposter">imposter</a> project in my free time with an intent to develop a simple, developer friendly stubbing and mocking mechanism. The project is now in a decent enough state to deserve a blog article.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Without further ado, in this article I will demonstrate how to create and configure stubs &amp; mocks using the <a href="https://github.com/avegaraju/Imposter">imposter</a> project. Let's begin with configuring and creating stubs.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>Configuring &amp; creating stubs</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>To configure a stub, you need to reference <a href="https://www.nuget.org/packages/Appify.FluentImposter.AspnetCore/">FluentImposter.AspNetCore package</a>. This package contains an ASP.Net middleware <code>UseStubImposters</code>, to configure stubs. All you need to do is to configure it in the <code>Startup.cs</code> as shown below:</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><noscript><pre>404: Not Found</pre></noscript><script src="https://gist.github.com/2e0e4c12d21a0a15d706fc6b0a514161.js"> </script></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><code>ImpostersAsStubConfiguration</code>, as the name suggests, accepts a list of imposters-as-stubs. These imposters are hosted as REST endpoints by the middleware. To demonstrate, let's create an imposter which will stub the <code>Orders</code> REST endpoint. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><noscript><pre>404: Not Found</pre></noscript><script src="https://gist.github.com/505104b11cb45fda1bd0e7dca0b68f48.js"> </script></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Being a fan of fluent APIs, I made the <code>ImposterDefinition</code> fluent. I like the idea of an API guiding me about the next steps. To begin with, it guides to define a resource to be stubbed, followed by a set of conditions that must match for the imposter to accept a request and respond with a canned response.  In this example, if the request body contains <code>Product:1234</code> then  this imposter will return a pre-configured response.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":4} -->
<h4>Creating Pre-configured responses.</h4>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>The <code>ResponseBuilder</code> helps to build the canned response. The code is pretty straight forward. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><noscript><pre>404: Not Found</pre></noscript><script src="https://gist.github.com/9c71b7d3b946211332bc51220b67737b.js"> </script></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>As shown in the below POSTMan screenshot, the <code>Orders</code> imposter endpoint is responding with a preconfigured response and a <code>Created (201)</code> status code because the request body has the content <code>Product:1234</code>. </p>
<!-- /wp:paragraph -->

<!-- wp:image {"id":676} -->
<figure class="wp-block-image"><img src="https://ashishvegaraju.files.wordpress.com/2019/02/image.png" alt="" class="wp-image-676" /><figcaption>The screen shot is of PostMan invoking Orders imposter and receiving a pre-configured response.</figcaption></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>Let's move on to configure and create an imposter as a mock.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>Configuring &amp; creating mocks</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>The same package<a href="https://www.nuget.org/packages/Appify.FluentImposter.AspnetCore/">&nbsp;FluentImposter.AspNetCore package</a>  has another middleware <code>UseMockImposters</code>, which is capable of configure and hosting mocks. Example shown below:</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><noscript><pre>404: Not Found</pre></noscript><script src="https://gist.github.com/02cf07d5aa9fa748e009e99dbfc44bd6.js"> </script></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Mocking requires invocation verification, hence a backing store is needed to keep the count of REST endpoint invocations. At the time of writing this article, I've only added support for <a href="https://aws.amazon.com/dynamodb/">Amazon DynamoDb</a> as a backing store which can be enable by adding   <br /><a href="https://www.nuget.org/packages/Appify.FluentImposter.DataStore.AwsDynamoDb/">Appify.FluentImposter.DataStore.AwsDynamoDb</a> Nuget package in your project. In case you do not have an Amazon AWS account, you can work with <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DynamoDBLocal.html">local DynamoDb installation</a> as well. But be aware that local DynamoDb, as the name suggests, is good for local testing and not recommended for production use. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Below is how you can create a MocksDatStore which connects to local DynamoDb installation.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><noscript><pre>404: Not Found</pre></noscript><script src="https://gist.github.com/8c050b7fafdd808e515be8355cc92c10.js"> </script></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>I wouldn't go into the details of this datastore. All that the <code>MocksDataStore</code> should do is to return <code>AwsDynamoDbDataStore</code> instance which does all the magic of maintaining request invocations.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>The next step is to create Imposters for the REST endpoints. To demonstrate, lets create a mock for <code>api/Products</code> endpoint.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><noscript><pre>404: Not Found</pre></noscript><script src="https://gist.github.com/90378aac89406d5d6023a60635916969.js"> </script></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Let's spin up POSTMan and invoke <code>api/Products</code> endpoint.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>As shown in the screen shot, the imposter responded with a canned response.</p>
<!-- /wp:paragraph -->

<!-- wp:image {"id":688} -->
<figure class="wp-block-image"><img src="https://ashishvegaraju.files.wordpress.com/2019/02/image-2.png" alt="" class="wp-image-688" /><figcaption>POSTMan screenshot of invoking api/Products endpoint.</figcaption></figure>
<!-- /wp:image -->

<!-- wp:heading {"level":4} -->
<h4>Mock verification</h4>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>The <code>UseMockImposters</code> middleware hosts a mock verification endpoint with resource path <code>mocks/verify</code> accepting Http GET requests. The request body should contain the details of the REST endpoint for which invocation verification has to be done.  Below is how the invocation verification for <code>api/Products</code> endpoint can be done using POSTMan</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p></p>
<!-- /wp:paragraph -->

<!-- wp:image {"id":689} -->
<figure class="wp-block-image"><img src="https://ashishvegaraju.files.wordpress.com/2019/02/image-3.png" alt="" class="wp-image-689" /><figcaption>Verification of invocation using POSTMan</figcaption></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>The mock verification endpoint responds back with the resource invoked along with the total number of invocations so far. </p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>Conclusion</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Thanks for reading. I am actively working on this project from last few months and planning to support more protocols. If you have any suggestion or improvements for the project then do let me know via comments. If you want to contribute then feel free to create pull requests in <a href="https://github.com/avegaraju/Imposter">github</a>. </p>
<!-- /wp:paragraph -->]]></content><author><name>avegaraju</name></author><category term="fakes" /><category term="integration testing" /><category term="Microservice testing" /><category term="mocks" /><category term="stubs" /><category term="test doubles over the wire" /><category term="test driven development" /><summary type="html"><![CDATA[Please note: If the code snippets in this article are not visible on your mobile browser then try to view this article with Desktop site option enabled.]]></summary></entry><entry><title type="html">Function Purity in F#</title><link href="/2018/12/24/function-purity-in-f/" rel="alternate" type="text/html" title="Function Purity in F#" /><published>2018-12-24T23:44:00+00:00</published><updated>2018-12-24T23:44:00+00:00</updated><id>/2018/12/24/function-purity-in-f</id><content type="html" xml:base="/2018/12/24/function-purity-in-f/"><![CDATA[<!-- wp:paragraph -->
<p>In my last article about <a href="https://ashishvegaraju.com/2018/09/24/functional-domain-modeling/">Functional domain modeling</a>, I explored the expressiveness of F# in modeling a domain. I fell in love with the simplicity and expressiveness of the language. In this article I will attempt to explore function purity in F#. In F#, functions are first class citizens because it allows to pass function as an argument to other function, return a function or assign function to a variable. Initially I found it a bit hard to wrap my head around the concept of treating functions as first class citizens. In fact one of the biggest challenge for me was surprisingly not the weird syntax of F#, but to think in terms of functions.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Coming from an OO background and not very comfortable with F#, below was my first attempt to write a use case. I basically tried to mimic a use case in a typical ports and adapters project from one of the C# projects. This use case serves a basic purpose which is to update the dimensions of a product, if it exists, of course.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><noscript><pre>404: Not Found</pre></noscript><script src="https://gist.github.com/18a503c2351100ee5c3568efc8426f49.js"> </script></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Pretty straight forward. The use case accepts a <code>DataStore</code> dependency using which the <code>update</code> method can query the <code>Products</code> table for existence of a product. If the product is found then the product is fetched from the data store and dimensions are updated. Finally, the product with updated dimensions is persisted in the database using the data store.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Though this use case works, there are several problems with this way of writing code. Lets take a look at the problems:</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":4} -->
<h4><strong>Testability</strong></h4>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>The code above is not easily testable. Why you ask? Lets look at how many ways things can go wrong with this code.</p>
<!-- /wp:paragraph -->

<!-- wp:list {"ordered":true} -->
<ol><li>What if the constructor arguments are null?</li><li>What if the <code>productExists</code> data store method returns an exception.</li><li>What if <code>updateDimensions</code>, which in turn calls <code>getProduct</code> and <code>updateProduct</code> methods on the data store returns exception?</li><li>What if the product does not exist?</li><li>What if product dimensions does not exist?</li><li>what if ....</li></ol>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>and the list will go on ..</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>So many scenarios to test with just one dependency. What if I add <code>ExternalService</code> as another dependency to this use case? Imagine the number of ways this third party service call can go wrong. The point is that whenever we deal with external systems, be it database or an external service, we are entering a world of uncertainty and we do not have much control over the behavior of those external systems. It would be nice if the use case and the domain model could completely avoid any type of IO operations or side affects. Sounds like a nice idea, but a use case which does not perform IO is next to useless. Stay with me and we will explore a way to minimize or avoid IO and side affects in the use case and domain model by the end of this article.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":4} -->
<h4>Hidden dependencies</h4>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>One of the beautiful things about F# is its expressiveness. The <code>update</code> method in our example is all but expressive about its intent. It has a dependency on <code>DataStore</code> which is not evident when we look at the method signature. This is what I call as a hidden dependency. What if in future someone modifies the <code>update</code> method and calls a completely different method on the datastore? Since the <code>update</code> method is not expressive enough, developers can assume a lot of things. Is there a way to avoid these hidden dependencies? Can we make the update method a little more expressive to avoid mistakes by future developers? Again, by the end of this article, we will try to re-write the <code>update</code> method to make it a little bit more expressive.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":4} -->
<h4>Referential Transparency</h4>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Methods in our use case are not referentially transparent. Especially the <code>update</code> method is not by any means. What is referential transparency? A function is referentially transparent if the function can be replaced with its corresponding value without affecting the behavior of the system. For example,</p>
<!-- /wp:paragraph -->

<!-- wp:preformatted -->
<pre class="wp-block-preformatted">if, x + y = 10<br /><br />then, the expression x + y + z = 20 can be written as 10 + z = 20</pre>
<!-- /wp:preformatted -->

<!-- wp:paragraph -->
<p>In our use case the method <code>update</code>, depending on whether one of the data store methods return an exception, may or may not update the product dimensions. We can never assume that a call to <code>update</code> method always updates product dimensions. Due to this uncertainty, I will not be able to include <code>update</code> method in a method chain like this and assume that warehouse system will be always notified after the product dimensions update.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><noscript><pre>404: Not Found</pre></noscript><script src="https://gist.github.com/53dd6dc264b22ae4664983445e567312.js"> </script></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>There are other smaller problems with this code. But for now, lets focus on fixing the problems that we identified above and making this use case a little bit better.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Here is an attempt to fix some of the problems we discussed above.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><noscript><pre>404: Not Found</pre></noscript><script src="https://gist.github.com/1e90438e3ae2c7aa8905977a751d74aa.js"> </script></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>First thing worth noticing is that these functions are not inside a <code>type</code> because there is no common dependency between these two functions. These functions exists on its own (under a module) and only accepts parameters that they can work with. The function name and signature are self documenting and they clearly communicate the intent. There is no scope of nasty exceptions bubbling up because of an unstable dependency. <strong><i>These are pure functions</i></strong>.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Lets see how easy it is to test these functions.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><noscript><pre>404: Not Found</pre></noscript><script src="https://gist.github.com/d8c27b1a3b8ef64cb5549e89115e5fca.js"> </script></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Simple and straightforward. There is no need to setup mocks for different scenarios here. You can create test data to your hearts content and test this function out. I have used <a href="https://github.com/AutoFixture/AutoFixture">Autofixture</a>, but <a href="https://fsharpforfunandprofit.com/posts/property-based-testing/">Property based tests</a> are better suited for testing these functions.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Coming back to the referential transparency. The <code>find</code> and <code>update</code> functions are referentially transparent. For instance, if the <code>Product</code> exists in the list of products then <code>find</code> will always return the Product. Otherwise, it always returns <code>None</code>, consistently.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>So, we have seen how getting rid of impure operations tremendously simplifies the program. But wait, this new shiny pure functional program does nothing useful. The end goal of this program is to update dimensions in the <i>database.</i> How do we make sure that we stick to function purity but also be able to perform impure operations like persisting data in a database or calling a third party service etc? You need to do the following:</p>
<!-- /wp:paragraph -->

<!-- wp:list {"ordered":true} -->
<ol><li>Push IO (impure) functions at the boundary of your domain.</li><li>Call pure functions from the impure functions and not the other way round.</li></ol>
<!-- /wp:list -->

<!-- wp:quote -->
<blockquote class="wp-block-quote"><p>As long as an impure function calls a Pure function you are good. When a pure function calls an impure function then the whole method chain becomes impure.</p></blockquote>
<!-- /wp:quote -->

<!-- wp:paragraph -->
<p>You would have guessed where we are going with this kind of separation between pure and impure functions. OK, no points for guessing, moving impure functions at the boundary and calling pure functions from there naturally leads you to <a href="http://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html">clean architecture</a>.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Let's see how does the call to pure functions from an impure function looks like.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><noscript><pre>404: Not Found</pre></noscript><script src="https://gist.github.com/e27a7abe2645023078015666fdf07b49.js"> </script></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><br /><code>tryUpdateProductDimensions</code>is an impure function because it calls <code>getAllProducts</code> which in turn calls <code>allProducts</code> from the <code>DB</code> module. <code>DB</code> module performs a bunch of impure operations. We can call it as the core of impurity (pun intended). For the sake of completeness, here is how I have implemented the DB module.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><noscript><pre>404: Not Found</pre></noscript><script src="https://gist.github.com/03d60370b3d794575affc1e505975c0c.js"> </script></p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":4} -->
<h4>Conclusion</h4>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>For a developer who is not fully familiar with F# or the functional programming paradigm may quite easily fall into the pit of writing OO style code with F# just like me in the beginning of this article. In F#, separating impure functions from pure functions requires discipline. As I understand, F# has no in-built magic to prevent you from mixing pure and impure functions. Haskell in that respect is pretty strict because it forces you to wrap impure functions using an <a href="https://wiki.haskell.org/Introduction_to_IO">IO monadic system</a>. In simple terms an IO monad is an abstract data structure which elevates a value. Once the value is elevated you can no longer access the original value. To access the original value, you must use one of the mapping functions of the monad. I can write a similar IO monad in F#, but is it really worth the effort? The F# compiler would not honor such an IO monad. Though I think that it may be a good idea to enforce it as a coding convention for your projects.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Let me know in the comments section below what you think about the IO system in Haskell. Should F# support something similar? If yes, why and if no why not?</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p></p>
<!-- /wp:paragraph -->]]></content><author><name>Ashish Vegaraju</name></author><summary type="html"><![CDATA[In my last article about Functional domain modeling, I explored the expressiveness of F# in modeling a domain. I fell in love with the simplicity and expressiveness of the language. In this article I will attempt to explore function purity in F#. In F#, functions are first class citizens because it allows to pass function as an argument to other function, return a function or assign function to a variable. Initially I found it a bit hard to wrap my head around the concept of treating functions as first class citizens. In fact one of the biggest challenge for me was surprisingly not the weird syntax of F#, but to think in terms of functions.]]></summary></entry><entry><title type="html">Functional Domain Modeling</title><link href="/2018/09/24/functional-domain-modeling/" rel="alternate" type="text/html" title="Functional Domain Modeling" /><published>2018-09-24T23:02:00+00:00</published><updated>2018-09-24T23:02:00+00:00</updated><id>/2018/09/24/functional-domain-modeling</id><content type="html" xml:base="/2018/09/24/functional-domain-modeling/"><![CDATA[<p style="text-align:justify;" data-mce-style="text-align: justify;">Lately, I've been reading about functional paradigm and related programming languages. More I read about it, more I feel that modeling domains in pure C# (or Java for that matter) is <em>unnatural</em> and does not communicate the intent of the domain clearly.</p>
<p style="text-align:justify;" data-mce-style="text-align: justify;">After so many years of writing C# code, that's quite a statement to make. But, I am serious. Lets model a simple subdomain <strong>Order</strong> for a hypothetical e-commerce company using F# then later using C# and see which of the models looks more expressive.</p>
<p style="text-align:justify;" data-mce-style="text-align: justify;">Lets start with C# first. Below is a typical <code>Order</code> entity with some typical properties.</p>
<noscript><pre>404: Not Found</pre></noscript>
<script src="https://gist.github.com/a0738e33f449f4fda4c11328293b5c95.js"> </script>

<p style="text-align:justify;" data-mce-style="text-align: justify;"><em>(For brevity, I have removed other properties &amp; methods which add behavior to this model.)</em></p>
<p style="text-align:justify;" data-mce-style="text-align: justify;">At first glance, this model looks decent. <em>Technically,</em> it has all the properties required to represent an&nbsp;<code>​​Order</code>. It uses <a href="https://martinfowler.com/bliki/UbiquitousLanguage.html" data-mce-href="https://martinfowler.com/bliki/UbiquitousLanguage.html">ubiquitous language</a> for modeling the domain, it uses strong types to represent attributes of an order (so, the smell of <a href="http://wiki.c2.com/?PrimitiveObsession" target="_blank" rel="noopener" data-mce-href="http://wiki.c2.com/?PrimitiveObsession">primitive obsession</a> is also taken care of). The properties expose only public getters, so state change (if we choose to do so) is only possible via public methods. But, does this model document the design of Order subdomain? Can a developer look at this model and understand what are the business constraints in this sub-domain? The answer is No. Let's examine this model closely to see why.</p>
<p style="text-align:justify;" data-mce-style="text-align: justify;"><strong>Lack of <em>Choice</em></strong></p>
<p style="text-align:justify;" data-mce-style="text-align: justify;">The <code>PaymentMethod</code> property is of type <code>IPaymentMethod</code>. Typically, this interface would be implemented by concrete payment method classes like <code>​CashOnDelivery</code>, <code>CreditCard</code> <code>Paypal</code> etc. But, this property does not <em>scream</em> about all the supported payment methods of the order sub-domain.</p>
<p style="text-align:justify;" data-mce-style="text-align: justify;">Of course, I can always see what are the types implementing <code>IPaymentMethod</code> interface, but, its well.. ehm... <em>unnatural</em> ...(you will see why when we examine the F# model). In short, the payments methods are not explicitly documented <em>in the</em> <em>model</em>. Another problem with having an interface is that it does not allow the domain modeler to make the property hold different <em>types (or combination of types)</em> of values depending on a particular payment method. For instance, in case of CreditCard, I would like the property to hold Card number <em>and</em> CardType information, if the payment method is PayPal then the property should hold the paypal Id etc.</p>
<p style="text-align:justify;" data-mce-style="text-align: justify;">Another problem, though minor, is that we do not know if we are dealing with a closed set of payment methods. What if an innocent developer makes an <em>innocent</em> mistake and adds <code>MyAwesomePaymentMethod</code> as another implementation of <code>IPaymentMethod</code>. So, now <code>Order</code> is secretly supporting a new payment method and no one (include the innocent developer) has a clue about it.</p>
<p style="text-align:justify;" data-mce-style="text-align: justify;">Here comes F# for the rescue. F# has discriminated unions. In other words a <em><strong>choice type,</strong></em> which, if used, unambiguously documents about the only three supported payment methods available. In other words, its a <em>closed set</em> of payment methods. Below is how the <code>PaymentMethod</code> type would be modeled in F#. Looking at this file, one can see the complete spec of <code>PaymentMethod</code> type.</p>
<p><em>
</em></p>

<noscript><pre>404: Not Found</pre></noscript>
<script src="https://gist.github.com/bfae189f33aad1cd24498df4230eb521.js"> </script>

<p>If I want to print a payment method (Of course, I wouldn’t from a domain model, perhaps I would execute a function for each <em>matched</em> payment method), I can <em>pattern match</em> and print (or do something more useful) in here.</p>

<noscript><pre>404: Not Found</pre></noscript>
<script src="https://gist.github.com/f5c6040682597f7535eba60962a62ea8.js"> </script>

<p style="text-align:justify;" data-mce-style="text-align: justify;">Notice how pattern matching allows us to return different information depending on&nbsp; the <em>choice</em> of payment method. In case of Paypal, I can use the PaypalId. Similarly, in case of <code>Card</code> payment, I can use the card number and card type.</p>
<p style="text-align:justify;" data-mce-style="text-align: justify;">Coming back to C#, I can use pattern matching and try to mimic the F# <em>choice type</em> behavior. But its ugly and convoluted (IDK why I am even mentioning it here :D ).</p>
<noscript><pre>404: Not Found</pre></noscript>
<script src="https://gist.github.com/d53bccf85e229197c021c854b9b52437.js"> </script>

<p><strong>Stuck without <em>Option</em></strong></p>
<p style="text-align:justify;" data-mce-style="text-align: justify;">Let's take a good look at the C# domain model once again. Can you infer which properties are required and which are optional? Typically, an order may or may not have a discount code which makes the property <code>DiscountCode</code> optional. But, the C# model fails to document that constraint. You may argue that <code>DiscountCode</code> could be made <code>nullable</code> and then all is good. But, is <code>null</code> equivalent to <em>not having</em> a discount code?</p>
<p>In F#, we can use <code>​Option&lt;'a&gt;</code> to denote an optional field as shown here:</p>

<noscript><pre>404: Not Found</pre></noscript>
<script src="https://gist.github.com/b296ebfa02ef75274e9409eeca9c4a3a.js"> </script>

<p style="text-align:justify;" data-mce-style="text-align: justify;">This is a self documenting domain model. By looking at it I know that an order may or may not have <code>DiscountCode</code>.</p>
<p style="text-align:justify;" data-mce-style="text-align: justify;">Luckily, <a href="https://github.com/louthy/language-ext" target="_blank" rel="noopener" data-mce-href="https://github.com/louthy/language-ext">Language Ext</a> package allows us to do this in C#. The <code>Order</code> model in C# (using Language Ext) now looks like this:</p>
<noscript><pre>404: Not Found</pre></noscript>
<script src="https://gist.github.com/252c9d48dbb459594054edc01420786b.js"> </script>

<p style="text-align:justify;" data-mce-style="text-align: justify;">Much better!</p>
<p>As mentioned, an <code>​Option</code> may or may not have a value. This is denoted with <code>​Some</code> or​ <code>None</code> respectively. Below is how one can inspect / match an <code>Option</code> to see if it contains a <code>Some</code> or a <code>None</code><em>.</em></p>

<p><em>
</em></p>

<noscript><pre>404: Not Found</pre></noscript>
<script src="https://gist.github.com/eef9b73057ef1a9cdfc9708dfbf9ae5f.js"> </script>

<p style="text-align:justify;" data-mce-style="text-align: justify;">That's a short one on why I feel that functional languages are naturally good for modeling domains as they make domain models expressive and self documenting. I am still experimenting with a couple of functional languages and so far I can see clear benefits of functional languages over imperative languages when it comes to developing a project with domain driven design.</p>
<p style="text-align:justify;" data-mce-style="text-align: justify;">I am not sure how easy or painful it is to access database or perform I/O with a functional language. I would probably run into it at some point. Do share your experiences (good and /or painful) with functional languages under comments and Thanks for reading!</p>]]></content><author><name>Ashish Vegaraju</name></author><summary type="html"><![CDATA[Lately, I've been reading about functional paradigm and related programming languages. More I read about it, more I feel that modeling domains in pure C# (or Java for that matter) is unnatural and does not communicate the intent of the domain clearly. After so many years of writing C# code, that's quite a statement to make. But, I am serious. Lets model a simple subdomain Order for a hypothetical e-commerce company using F# then later using C# and see which of the models looks more expressive. Lets start with C# first. Below is a typical Order entity with some typical properties. 404: Not Found (For brevity, I have removed other properties &amp; methods which add behavior to this model.) At first glance, this model looks decent. Technically, it has all the properties required to represent an&nbsp;​​Order. It uses ubiquitous language for modeling the domain, it uses strong types to represent attributes of an order (so, the smell of primitive obsession is also taken care of). The properties expose only public getters, so state change (if we choose to do so) is only possible via public methods. But, does this model document the design of Order subdomain? Can a developer look at this model and understand what are the business constraints in this sub-domain? The answer is No. Let's examine this model closely to see why. Lack of Choice The PaymentMethod property is of type IPaymentMethod. Typically, this interface would be implemented by concrete payment method classes like ​CashOnDelivery, CreditCard Paypal etc. But, this property does not scream about all the supported payment methods of the order sub-domain. Of course, I can always see what are the types implementing IPaymentMethod interface, but, its well.. ehm... unnatural ...(you will see why when we examine the F# model). In short, the payments methods are not explicitly documented in the model. Another problem with having an interface is that it does not allow the domain modeler to make the property hold different types (or combination of types) of values depending on a particular payment method. For instance, in case of CreditCard, I would like the property to hold Card number and CardType information, if the payment method is PayPal then the property should hold the paypal Id etc. Another problem, though minor, is that we do not know if we are dealing with a closed set of payment methods. What if an innocent developer makes an innocent mistake and adds MyAwesomePaymentMethod as another implementation of IPaymentMethod. So, now Order is secretly supporting a new payment method and no one (include the innocent developer) has a clue about it. Here comes F# for the rescue. F# has discriminated unions. In other words a choice type, which, if used, unambiguously documents about the only three supported payment methods available. In other words, its a closed set of payment methods. Below is how the PaymentMethod type would be modeled in F#. Looking at this file, one can see the complete spec of PaymentMethod type.]]></summary></entry><entry><title type="html">Test Driven Development with TypeScript</title><link href="/2016/10/31/test-driven-development-with-typescript/" rel="alternate" type="text/html" title="Test Driven Development with TypeScript" /><published>2016-10-31T00:05:00+00:00</published><updated>2016-10-31T00:05:00+00:00</updated><id>/2016/10/31/test-driven-development-with-typescript</id><content type="html" xml:base="/2016/10/31/test-driven-development-with-typescript/"><![CDATA[<p align="justify">In this article, I will demonstrate how to write testable code using TypeScript. I assume that the reader is familiar with JavaScript, heard about Typescript and has done or secretly desires to do test driven development.</p>
<p align="justify">There is an excellent <a href="https://www.typescriptlang.org/docs/tutorial.html">quick start guide</a> on Typescript that I recommend you to go through before moving ahead.</p>
<p align="justify"><!--more--></p>

<h2><strong>Project Setup</strong></h2>
<p>I am writing the code in Visual Studio 2015 Update 2 (which already has the necessary ingredients to author TypeScript applications). You can also use Visual Studio Code for authoring web applications with TypeScript.</p>
<p align="justify">1. Start Visual Studio and Create a new project. From the installed templates, select <strong>Html Application With TypeScript</strong> template.</p>
<p align="justify"><a href="http://ashishvegaraju.files.wordpress.com/2016/10/project_template.png"><img style="background-image:none;padding-top:0;padding-left:0;display:inline;padding-right:0;border-width:0;" title="Project_template" src="http://ashishvegaraju.files.wordpress.com/2016/10/project_template_thumb.png" alt="Project_template" width="521" height="365" border="0" /></a></p>
<p align="justify">2. Notice how Visual Studio has done the required scaffolding for your first TypeScript application. In fact, if you press F5 on your keyboard, you will be able to run this application in your browser. Take some time here and see how closely TypeScript resembles an object oriented programming language. You’d see a class, a constructor method etc.</p>
<p align="justify">3. When you are done with admiring the beauty of TypeScript, you may select the code in <strong>app.ts</strong> and delete it. Since we are doing Test Driven Development, we will not be writing any Production code without accompanying tests!</p>
<p align="justify">4. In an enterprise project, you’d usually create a new Test Project in the solution. But for the purpose of this article and also to keep things simple in the beginning, I will just create a new folder called as “<strong>Tests</strong>” under the same project and add a test file in it. .</p>
<p align="justify">The goal of the application is to calculate area of different shapes. I usually choose simple applications and simple domains to demonstrate new stuff. This helps in focusing more on the subject rather than focusing on details of the domain.</p>
<p align="justify">At this point, I have renamed <strong>app.ts</strong> to <strong>Rectangle.ts</strong> and the test file name is <strong>RectangleTests.ts</strong></p>
<p><a href="http://ashishvegaraju.files.wordpress.com/2016/10/image2.png"><img style="background-image:none;padding-top:0;padding-left:0;display:inline;padding-right:0;border-width:0;" title="image" src="http://ashishvegaraju.files.wordpress.com/2016/10/image_thumb2.png" alt="image" width="409" height="271" border="0" /></a></p>
<h2>Set up for writing Tests</h2>
<p align="justify">To test TypeScript code, you’d need a testing framework. There are few popular frameworks available like Jasmine and QUnit. For the purpose of this article and also because at the time of writing this article, I couldn't find any example where typescript is used with QUnit and Chutzpah (more on that later), I decided to write this article using QUnit.</p>
<p align="justify">Go ahead and add Qunit-MVC via the package manager console.</p>

<div id="codeSnippetWrapper" class="csharpcode-wrapper">
<div id="codeSnippet" class="csharpcode">
<pre class="alteven"><span id="lnum1" class="lnum">   1:</span> Install-Package Qunit-MVC</pre>
<!--CRLF-->

</div>
</div>
<p align="justify">You’d also need a type definition file for Qunit. The purpose of type definition file (file with extension *.d.ts) is to let TypeScript know about the types that exist in an API. There is a github project called as <a href="https://github.com/DefinitelyTyped/DefinitelyTyped">Definitely Typed</a>,  which provides high quality type definitions for almost all JavaScript APIs.</p>
<p align="justify">Run below command to add the type definition file for QUnit.</p>

<div id="codeSnippetWrapper" class="csharpcode-wrapper">

<!--CRLF-->

</div>
<blockquote>
<p align="justify">Install-Package qunit.TypeScript.DefinitelyTyped</p>
</blockquote>
<p align="justify">Apart from that, you’d need a test runner, where you can see your passing/failing tests. For that I am going to use <a href="https://github.com/mmanela/chutzpah">Chutzpah</a>. To use Chutzpah in Visual studio you need to add an extension. Select <strong>Tools</strong>&gt;<strong>Extensions and Updates </strong>and search for Chutzpah. (Since I already have Chutzpah extension added in my VS, I see the option to disable or uninstall it.)</p>
<p><a href="http://ashishvegaraju.files.wordpress.com/2016/10/image.png"><img style="background-image:none;padding-top:0;padding-left:0;display:inline;padding-right:0;border-width:0;" title="image" src="http://ashishvegaraju.files.wordpress.com/2016/10/image_thumb.png" alt="image" width="526" height="371" border="0" /></a></p>
<p align="justify">Add chutzpah.json file in the root of your project. This json file provides a range of configuration for Chutzpah test runner. For the sake of simplicity, I am configuring the json file with very basic settings:</p>

<p><noscript><pre>404: Not Found</pre></noscript><script src="https://gist.github.com/39c4b175b706121f1a7fef34eab791e1.js"> </script></p>

<p align="justify">Compile Mode <strong>External</strong> denotes that Chutzpah test runner can expect compiled .JS file in the default output directory. If you select mode as <strong>Executable </strong>then you need to provide a powershell or bat file which will convert .ts files to .js file. In this project, I will use tsconfig.json file and configure it in such a way that visual studio will take care of generating a .js file while building (ctrl + shift + b) the project.</p>
<p align="justify">Add a file with name <strong>tsconfig.json</strong> in the root of the project with below settings.</p>

<p><noscript><pre>404: Not Found</pre></noscript><script src="https://gist.github.com/7abfdf6818481183519962ce7c846e6e.js"> </script></p>

<p>With that in place, we are all set to write the tests.</p>
<h2>The <span style="color:#ff0000;">Red</span> <span style="color:#008000;">Green</span> <span style="color:#0000ff;">Refactor</span> Cycle</h2>
<p>Open <strong>RectangleTests.ts</strong> file and write you first failing test. Below is my first failing test.</p>

<p><noscript><pre>404: Not Found</pre></noscript><script src="https://gist.github.com/857c540752b3708614a7e47a807dd727.js"> </script></p>

<p>There is no need to run tests. The project will not compile because I have not created the Rectangle class yet. A non-compiling class is equivalent to a failing test. So lets write just enough code to make this test pass.</p>

<p>Open <strong>Rectangle.ts</strong> file and type below code:</p>
<p><noscript><pre>404: Not Found</pre></noscript><script src="https://gist.github.com/d80aba54cec4112de1ab75e811c74f00.js"> </script></p>

<p>Perfect! This is exactly what we need to make the failing test pass. Lets run the test and confirm if our test is passing.</p>

<p><a href="http://ashishvegaraju.files.wordpress.com/2016/10/image3.png"><img style="background-image:none;padding-top:0;padding-left:0;display:inline;padding-right:0;border-width:0;" title="image" src="http://ashishvegaraju.files.wordpress.com/2016/10/image_thumb3.png" alt="image" width="419" height="182" border="0" /></a></p>

<p>So that’s our Red and Green cycle in TDD. But, what about Refactor? As of now, I do not see any need to refactor the code.</p>
<p style="text-align:justify;">Let’s write the next test. I would like the length and breadth of the rectangle to be passed as constructor argument to the Rectangle class, so lets add another test which passes length and breadth to the Rectangle class.</p>
<p style="text-align:justify;">You'd notice that the project is not compiling because there is no constructor in the Rectangle class which accepts two arguments. To make the project compile, lets add a constructor to the Rectangle class:</p>

<p><noscript><pre>404: Not Found</pre></noscript><script src="https://gist.github.com/8006adf0eaf30604a3d7bf2a6e7b4bf6.js"> </script></p>

<p>Now lets run the tests again.</p>

<p>But hey! Our first test is now failing! Because we do not have any blank constructor in the Rectangle class. At this point we need to do some <span style="color:#1a1a1a;">refactoring</span>!</p>

<p>Do we really need the first test? I would say <strong>No</strong>, because with the new constructor, we are enforcing a contract that to calculate area of a Rectangle you need to provide length and breadth of the rectangle before hand. So lets <strong>delete </strong>the first test.</p>
<blockquote><span style="color:#1a1a1a;">During the refactoring cycle, not only the production code, but the test code can and should be refactored. </span>
<p align="justify">Tests deserve to be maintained to the same level of quality as the production code. Indeed, perhaps the tests deserve even more attention than the production code since the quality of the production code depends on the tests;</p>
<p align="right">-Bob Martin</p>
</blockquote>
<p>At this point, I would skip demonstrating all the Red Green and refactor cycles that I went through to add the function which calculates the area of a rectangle. The reason I want to skip that is because I want to demonstrate an interesting concept called as “Stubbing”!</p>
<h2>Stubbing</h2>
<p>For those who are familiar with test driven development would know that unit tests without the ability to stub external dependencies are not of much use. To demonstrate stubbing in our example, I am introducing an external dependency, a webservice which helps in calculating the area of a triangle.</p>
<blockquote>Area of Triangle = 1/2 (height * base)</blockquote>
<p>In our hypothetical world, there exists a service, which if called, provides the height of the triangle. The requirement is that we call a web service to get the height value.</p>

<p>To enable stubbing, we need to add typeMoq framework to the project. Using typeMoq, we can stub external dependencies and also use mocking to verify expectations on method calls.</p>
<blockquote>
<p align="justify">Install-Package typemoq</p>
</blockquote>
<p>Let’s create a class with name TriangleTests.ts and write the first failing test.</p>

<p><noscript><pre>404: Not Found</pre></noscript><script src="https://gist.github.com/665ea1805d5ef5a2055d99a972e693d8.js"> </script></p>
<p>This class fails to compile, so lets quickly add Triangle.ts class with a constructor accepting base value:</p>
<p><noscript><pre>404: Not Found</pre></noscript><script src="https://gist.github.com/9af785f45ad02aabad7a256d9e0954f9.js"> </script></p>
<p>Now, the tests should pass. Next, we need to somehow call a service from this class to get height of the triangle. This means, we need to add a new class which does the Ajax call to a hypothetical service. With that information, lets write our next test.</p>

<p><noscript><pre>404: Not Found</pre></noscript><script src="https://gist.github.com/b0cc4d4a6c38406abb006840cdf57d60.js"> </script></p>

<p>Notice the usage of mock.object. At this point the project will not compile, so lets fix it and make the tests run. Add an interface in Triangle.ts file.</p>
<p><noscript><pre>404: Not Found</pre></noscript><script src="https://gist.github.com/140f24a92ce52eb0fa8f85442d14e58f.js"> </script></p>

<p>and an empty class which implements this interface</p>
<p><noscript><pre>404: Not Found</pre></noscript><script src="https://gist.github.com/40f0de21969bb8bc445205cd12e12e48.js"> </script></p>

<p>Notice that we are not writing any implementation for this class. In fact, any attempt to invoke the performAjaxCall method on this class will throw an exception. At this point, we just want our test to pass which is using the mock object to stub an external dependency.</p>

<p>Lets modify the Triangle class and add a new constructor argument:</p>
<p><noscript><pre>404: Not Found</pre></noscript><script src="https://gist.github.com/aeadc011c987d21f9c473568492fd134.js"> </script></p>
<p>Notice the usage of IAjaxWrapper interface in the constructor argument, just like how its done in any object oriented language. Add below references in the test class. With these references, we are telling Chutzpah test runner where to find the typemoq library.</p>
<p><noscript><pre>404: Not Found</pre></noscript><script src="https://gist.github.com/294bb8f0958321a380adbe17abd2e234.js"> </script></p>
<p>With typemoq referenced in the test class, lets define our mock object.</p>

<p><noscript><pre>404: Not Found</pre></noscript><script src="https://gist.github.com/1c720bd0d64763f1cdb0f550c45690d8.js"> </script></p>

<p>Below is the complete code:</p>
<p><noscript><pre>404: Not Found</pre></noscript><script src="https://gist.github.com/ef8bd15ad5854a7cf3ec4cffc6425919.js"> </script></p>
<p>This test will pass!</p>

<p>Let’s write the next test to actually calculate the area of triangle.</p>
<p><noscript><pre>404: Not Found</pre></noscript><script src="https://gist.github.com/ae4c98ec4387da063db5398ad97ca6a3.js"> </script></p>

<p align="justify">Notice how the performAjaxCall method is being set up to return a predefined height value. At this point, we do not care how AjaxWrapper is going to fetch the value of triangle’s height, all we know is that the performAjaxCall method is setup to provide that value. Notice we just need an interface, so that we can handle the dependency with fake implementation and move ahead with our tests.</p>
<p align="justify">Of course, this test will fail, because calculateArea method does not exist. Let’s fix that and make the test pass. Create a calculateArea method in the Triangle.ts class. Below is the code:</p>

<p><noscript><pre>404: Not Found</pre></noscript><script src="https://gist.github.com/97b608c380d51888cd808cc4c571d8bb.js"> </script></p>

<p>This should be enough for the tests to pass.</p>

<p>With that, I’d conclude this article. Hope the article was helpful.</p>
<h2>Quick Tips</h2>
<ol>
  <li>Chutzpah can show test results on a web page. To view your tests in a browser, right click on the test file and from the context menu Select <strong>Run Chutzpah with &gt; Debugger. </strong>You can also put breakpoints and debug your tests.</li>
</ol>
<p align="justify"><a href="http://ashishvegaraju.files.wordpress.com/2016/10/image4.png"><img style="background-image:none;padding-top:0;padding-left:0;display:inline;padding-right:0;border-width:0;" title="image" src="http://ashishvegaraju.files.wordpress.com/2016/10/image_thumb4.png" alt="image" width="268" height="136" border="0" /></a></p>
<ol>
  <li>You can check the code coverage of your TypeScript code. Below is the code coverage of TriangleTests.ts</li>
</ol>

<p><a href="http://ashishvegaraju.files.wordpress.com/2016/10/image5.png"><img style="background-image:none;padding-top:0;padding-left:0;display:inline;padding-right:0;border-width:0;" title="image" src="http://ashishvegaraju.files.wordpress.com/2016/10/image_thumb5.png" alt="image" width="218" height="218" border="0" /></a></p>

<p>The code for this demonstration can be found at my <a href="https://github.com/avegaraju/TDDWithTypeScript" target="_blank" rel="noopener">github repository</a>.</p>]]></content><author><name>avegaraju</name></author><category term="chutzpah" /><category term="javascript" /><category term="mocking" /><category term="QUnit" /><category term="stubbing" /><category term="TDD" /><category term="test driven development" /><category term="typemoq" /><category term="typescript" /><category term="unit test" /><summary type="html"><![CDATA[In this article, I will demonstrate how to write testable code using TypeScript. I assume that the reader is familiar with JavaScript, heard about Typescript and has done or secretly desires to do test driven development. There is an excellent quick start guide on Typescript that I recommend you to go through before moving ahead.]]></summary></entry><entry><title type="html">A WCF Chat Service &amp;amp; Client</title><link href="/2015/12/15/a-wcf-chat-service-client/" rel="alternate" type="text/html" title="A WCF Chat Service &amp;amp; Client" /><published>2015-12-15T17:33:00+00:00</published><updated>2015-12-15T17:33:00+00:00</updated><id>/2015/12/15/a-wcf-chat-service-client</id><content type="html" xml:base="/2015/12/15/a-wcf-chat-service-client/"><![CDATA[<p align="justify">I attended a interview recently for which the pre-requisite was to develop a chat application using WCF as part of a <em>code challenge</em>. The requirement was quite simple, so instead of taking the usual route of creating a WCF service and adding its reference to a client application, I decided to hand code everything without any configuration or service references!</p>
<p align="justify">Of course the  assumption here is that the service and client applications are owned by a single company/team so that the contracts can be shared between the service and client.</p>
<p align="justify"><!--more--></p>
<p align="justify">The complete code is available in my <a href="https://github.com/avegaraju/WCFChatApp" target="_blank" rel="noopener">Github</a> account.</p>

<h6>The Problem Statement</h6>
<div id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:c247d9f7-42bd-467e-a56a-5bb236a92f5d" class="wlWriterEditableSmartContent" style="float:none;margin:0;display:inline;padding:0;">

[sourcecode language="text" gutter="false" light="true"]
Goal - Create a Chat Server and Client application using 
.NET 4.0/4.5 with WCF as the communication mechanism. 
The Chat Server should be a standalone application and 
the Chat Client should be a standalone application with 
a basic UI for users to interact and exchange messages 
through the Chat server. Stability of the code is a 
must-have and it should be ensured that the 
Server/Client do not crash during operation to 
maintain quality user experience. 

The basic functionality to be supported is as follows: 

1. The chat server should open up a TCP port for
 listening to incoming client requests. 

2. The server should be able to handle at 
least 2 distinct clients’ communication in parallel. 

3. On successful connection with the server, 
the chat client should be able to send plain text 
messages to the server. 

4. The server should be able to respond to each 
message by a static message &quot;Hello!&quot; appended 
with the server's timestamp. 

5. Both chat clients should be able to communicate 
with the server without the messages of either being 
visible to the other one. 

[/sourcecode]

</div>
<h6 align="justify">The Approach</h6>
<p align="justify">Since the service contract has to be shared between the service and client the best place to create the service contract is in a common library project. I have created a “contract” folder which has few more sub folders having contracts for service, response, request,  fault and a contract for callback service (more on this later).</p>
<p><a href="http://ashishvegaraju.files.wordpress.com/2015/12/image.png"><img style="background-image:none;padding-top:0;padding-left:0;display:inline;padding-right:0;border-width:0;" title="image" src="http://ashishvegaraju.files.wordpress.com/2015/12/image_thumb.png" alt="image" width="299" height="370" border="0" /></a></p>
<h6>The Duplex Message Exchange Pattern via Callbacks</h6>
<p>IEAChatService.cs is the service contract defined as shown below</p>
<div id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:53f692e4-3830-4b21-bc23-0989a6240c9a" class="wlWriterEditableSmartContent" style="float:none;margin:0;display:inline;padding:0;">

[sourcecode language="csharp"]
 [ServiceContract(
        SessionMode = SessionMode.Required, 
        CallbackContract= typeof(IChatCallback))]
 public interface IEAChatService
[/sourcecode]

</div>
<p align="justify">I have defined a CallbackContract for this service contract. This callback contract interface is defined in IChatCallback.cs and is implemented by the client application (EA.Client.EAChat.UI).</p>

<div id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:f5c8c95c-e1a9-4f44-83ac-bfef0512728e" class="wlWriterEditableSmartContent" style="float:none;margin:0;display:inline;padding:0;">

[sourcecode language="csharp" padlinenumbers="true"]
    [ServiceContract]
    public interface IChatCallback
    {
        [OperationContract(IsOneWay=true)]
        void RefreshUserList(List&lt;User&gt; onlineUsers);

        [OperationContract]
        void ResponseMessage(ResponsePacket response);
    }
[/sourcecode]

</div>
<p align="justify">This contract is called as a duplex service contract. Duplex service contract is a message exchange pattern where service as well as client can send messages to other independently. Since this interface is implemented by client (EA.Client.EAChat.UI), the service can directly call the client methods. In this case, whenever a new user enters the chat room the <em>Register  </em>method of the EAChatService.cs calls the callback method <em>RefreshUserList </em>on the client, so that client can refresh the user interface and show the name of the newly entered user in the list of users of the chat room. Below is the relevant piece of code.</p>

<div id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:2389c65a-1bbb-4b08-ab09-c7210d0e443d" class="wlWriterEditableSmartContent" style="float:none;margin:0;display:inline;padding:0;">

[sourcecode language="csharp"]
       public void Register(User userHandle)
        {
            try
            {
						//---irrelevant code removed ---------
                       foreach (KeyValuePair&lt;string, IChatCallback&gt; kvp in registeredUser)
                        {
                            IChatCallback callback = kvp.Value;
                            callback.RefreshUserList(onlineUsers);
                        }
                    }

                }
               // ---irrelevant code removed ---------

            }
            catch (UserHandleInUseException uEx)
            {
                log.Error(&quot;User handle is alread in use. Error Detail: &quot; + uEx.Message);
                throw;

            }

        }
[/sourcecode]

</div>
<h6 align="justify">The Service Side Code</h6>
<p>EAChatService.cs inherits from ServiceBase.cs. ServiceBase class has some common properties used why the EAChatService class. For instance, the ServiceBase class has a protected getter property  which returns the channel to the client instance which called the operation currently. Below is the code snippet.</p>
<div id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:5c2a9717-b10b-4593-8ad3-7fcf6c9cc15e" class="wlWriterEditableSmartContent" style="float:none;margin:0;display:inline;padding:0;">

[sourcecode language="csharp"]
      protected IChatCallback Callback
       {
           get
           {
               return OperationContext.Current.GetCallbackChannel&lt;IChatCallback&gt;();
           }
       }
[/sourcecode]

</div>
<p> </p>
<p align="justify">ServiceBase class also has a protected dictionary for registeredUsers which stores the userID and the corresponding Callback as a keyvalue pair in the dictionary object. Since multiple users may call the <em>Register </em>method at once, the critical section of adding users in the dictionary is synchronized using a lock. below is the complete code of register method.</p>

<div id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:a2ece10f-4f44-4329-81ca-decd9b13b982" class="wlWriterEditableSmartContent" style="float:none;margin:0;display:inline;padding:0;">

[sourcecode language="csharp"]
       public void Register(User userHandle)
        {
            try
            {
                if (!registeredUser.ContainsKey(userHandle.UserId) &amp;&amp;
                    !registeredUser.ContainsValue(Callback))
                {
                    lock (syncObject)
                    {
                        registeredUser.Add(userHandle.UserId, Callback);
                        onlineUsers.Add(userHandle);

                        foreach (KeyValuePair&lt;string, IChatCallback&gt; kvp in registeredUser)
                        {
                            IChatCallback callback = kvp.Value;
                            callback.RefreshUserList(onlineUsers);
                        }
                    }

                }
                else
                {
                    throw new UserHandleInUseException(ServiceFaultCode.HANDLE_IN_USE, &quot;User with this handle already exist. Please choose a different handle.&quot;);
                }
            }
            catch (UserHandleInUseException uEx)
            {
                log.Error(&quot;User handle is alread in use. Error Detail: &quot; + uEx.Message);
                throw;

            }

        }
[/sourcecode]

</div>
<h6>The Client Code</h6>
<p align="justify">The client code is implemented in the <em>ChatWindow</em> cliass. The <em>ChatWindow</em>  class has a SynchronizationContext which is used to marshal messages from one thread to another thread. You must be wondering, why do we need to marshal messages from one thread to another. The reason is that the client UI runs on a separate thread and the duplex message from the WCF service is delivered to the client application via another thread. Now the message sent from WCF service as part of duplex call cannot be directly used by the client UI. To enable the message transmission between the UI thread and callback thread, we use the UI thread’s SynchronizationContext and call its <em>Post</em> method to pass the message. I am using Unity container to hold and resolve instances of SynchronizationContext object. Below is the implementation of <em>RefreshUserList</em> callback method which demonstrates the SynchronizationContext usage.</p>

<div id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:935a3bc5-6dc3-412f-984e-6869b3b190f6" class="wlWriterEditableSmartContent" style="float:none;margin:0;display:inline;padding:0;">

[sourcecode language="csharp" padlinenumbers="true"]
       public void RefreshUserList(List&lt;User&gt; onlineUsers)
        {
            ClearOnlineUserList();

            foreach (User user in onlineUsers)
            {

                SendOrPostCallback callback =
                delegate(object state)
                {
                    this.OnlineUserListBox.Items.Add(user.UserId);
                };

                _uiSyncContext = (SynchronizationContext)container.Resolve(typeof(SynchronizationContext));
                _uiSyncContext.Post(callback, user.UserId);
            }
        }
[/sourcecode]

</div>
<h6>The WCF endpoint &amp; Hosting</h6>
<p align="justify">The WCF endpoint is configured programmatically in the EA.Host.ServiceHostEngine project where we have the logic of hosting the WCF service as well.</p>
<p align="justify">I have defined an Interface IHostScheme.cs which has the declaration of  <em>Host </em>method and this interface is implemented by NetTcpHost.cs. Since one of the assumptions is that this chat application works in intranet, I choseto use NetTcp binding for the communication. In future if we decide to make to this chat application work in extranet then we can create another class implementing the IHostScheme interface with appropriate binding implementation.</p>
<p align="justify">Lets look at the NetTcpScheme.cs class.</p>

<div id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:a2203c92-2db1-433f-b25b-1f9d25cc64d8" class="wlWriterEditableSmartContent" style="float:none;margin:0;display:inline;padding:0;">

[sourcecode language="csharp"]
    public class NetTcpHost : IHostScheme
    {
        public ServiceHost Host(string portNumber, bool enableMetaData)
        {
            Type contractType = typeof(IEAChatService);
            Type serviceType = typeof(EAChatService);

            Uri baseAddress = GetBaseAddress(portNumber);

            ServiceHost serviceHost = new ServiceHost(serviceType, baseAddress);
            serviceHost.AddServiceEndpoint(contractType, new NetTcpBinding(), baseAddress.AbsoluteUri);

            ServiceMetadataBehavior metaDataBehavior = new ServiceMetadataBehavior();
            metaDataBehavior.HttpGetEnabled = false;
            serviceHost.Description.Behaviors.Add(metaDataBehavior);

            if (enableMetaData)
            {
                serviceHost.AddServiceEndpoint(ServiceMetadataBehavior.MexContractName,
              MetadataExchangeBindings.CreateMexTcpBinding(), &quot;mex&quot;);
            }

            return serviceHost;
        }

        private Uri GetBaseAddress(string portNumber)
        {
            string prefix = ConfigurationManager.AppSettings[&quot;nettcp_prefix&quot;];
            string chatServicePath = ConfigurationManager.AppSettings[&quot;EAChatServicePath&quot;];

            return new Uri(prefix + portNumber + chatServicePath);

        }
    }
[/sourcecode]

</div>
<p align="justify">The code is pretty much self explanatory. This class is responsible for creating a ServiceHost and a ServiceEndpoint. To create a ServiceHost, we need the type of Service contract and to create a service endpoint which will be hosted by the ServiceHost, we need the contract’s type, address (along with the port) where we will host the service and binding is set to NetTcpBinding because that’s one of the requirement in the problem statement that communication has to take place over tcp port.</p>
<p align="justify">I have made HttpGetEnabled property of ServiceMetadataBehavior to false, as I don’t se any benefit of exposing the wsdl over http for our application. However, MEX endpoint is made configurable, so that if in future we wish to create a new client and create a proxy using svcutil for communication, we could do so easily.</p>
<p align="justify">That’s it! There are other utility projects and relatively less interesting code in the solution, so I will skip the remaining details.</p>
<p align="justify">Feel free to use the code and modify it according to your requirements. The code is available  in my <a href="https://github.com/avegaraju/WCFChatApp" target="_blank" rel="noopener">Github</a> account.</p>
<p>If you have any queries, feel free to ask in the comments section.</p>]]></content><author><name>avegaraju</name></author><category term="callback" /><category term="chat" /><category term="code challenge" /><category term="Coding Challenge &amp;amp; Competitions" /><category term="coding competition" /><category term="duplex" /><category term="interview question" /><category term="synchronizationcontext" /><category term="wcf" /><category term="WCF chat service" /><summary type="html"><![CDATA[I attended a interview recently for which the pre-requisite was to develop a chat application using WCF as part of a code challenge. The requirement was quite simple, so instead of taking the usual route of creating a WCF service and adding its reference to a client application, I decided to hand code everything without any configuration or service references! Of course the  assumption here is that the service and client applications are owned by a single company/team so that the contracts can be shared between the service and client. The complete code is available in my Github account.]]></summary></entry><entry><title type="html">Mobile Push Notification Service - Design Approach (Part 1)</title><link href="/2015/12/08/mobile-push-notification-service-design-approach-part-1/" rel="alternate" type="text/html" title="Mobile Push Notification Service - Design Approach (Part 1)" /><published>2015-12-08T18:00:00+00:00</published><updated>2015-12-08T18:00:00+00:00</updated><id>/2015/12/08/mobile-push-notification-service-design-approach-part-1</id><content type="html" xml:base="/2015/12/08/mobile-push-notification-service-design-approach-part-1/"><![CDATA[<h6><span style="font-weight:normal;">Overview of Push Notifications</span></h6>
<p align="justify">In this article, I am going to design the architecture for implementing push notifications for you mobile application. This part only has design and architecture information, code will be covered in Part 2.</p>

<blockquote>If you are new to push notifications, please read <a href="https://en.wikipedia.org/wiki/Notification_service">wiki </a>article about the technology and also about <a href="https://en.wikipedia.org/wiki/Google_Cloud_Messaging">GCM </a>and <a href="https://en.wikipedia.org/wiki/Apple_Push_Notification_Service">APN </a>services.</blockquote>
<!--more-->

<p>Below diagram depicts a high level overview of device registration process.</p>

<p><img src="https://ashishvegaraju.files.wordpress.com/2015/11/devicereg.png?w=559" alt="DeviceReg" width="1312" height="758" /></p>
<ol>
	<li>
<div align="justify">Device sends sender ID, application ID to GCM server for registration.</div></li>
	<li>
<div align="justify">Upon registration Cloud Service (GCM/APNs) sends a unique registration ID to the device.</div></li>
	<li>
<div align="justify">After receiving the registration ID from the cloud service the device will forward the registration ID to the Push Notification Web Service.</div></li>
	<li>
<div align="justify">The Push Notification web service will store the registration ID in a local database for later use.</div></li>
</ol>
<p align="justify">a. Whenever Push Notification service needs to send the notification, it has to call GCM/APN service with registration ID of the device which is stored in the database.</p>
<p align="justify">b. GCM/APN service will deliver the notification to respective mobile device based on the registration ID.</p>

<blockquote>Push Notification service would require an outbound internet connection to send messages to cloud services. Make sure to open two outbound ports on your push notification server.</blockquote>
<h4><strong>Push Notification Components</strong></h4>
<p>You would need to implement two components:</p>
<ol>
	<li>
<h5><em><strong>Push Notification Web Service</strong></em></h5>
</li>
</ol>
<p align="justify">Push notification web service could be a rest service. Bare minimum the web service should have two functionalities. One, to register new device and Second, to unregister a device.</p>

<ol>
	<li>
<h5><strong><em>Push Notification Windows Service.</em></strong></h5>
</li>
</ol>
<p align="justify">You need to implement a windows service which could spawn multiple threads to listen to a messaging queue at a specified address. This service should be capable to pick up messages as and when it arrives to the messaging queue. The service will then query the local database and get a list of eligible devices which should receive the notification message and communicate with the cloud messaging services to get the notifications delivered.</p>

<blockquote>
<p align="justify">Push Notification Windows service is a Microsoft Windows<sup>® </sup>terminology. On non-windows platform this windows service will be a process which will be initiated with a start-up batch file which could be hooked up with tomcat initialization process.</p>
</blockquote>
<h4><strong>Push Notification Architecture</strong></h4>
<p>Diagram below depicts the push notification architecture at high level.</p>

<p><img src="https://ashishvegaraju.files.wordpress.com/2015/11/hld.png?w=559" alt="HLD" width="1313" height="924" /></p>
<ol>
	<li>
<div align="justify">As depicted in the diagram above, the first step is get the unique device ID from the cloud messaging service. The mobile application should make a call to the cloud messaging service every time it is launched. It is important to make this call every time as it may so happen that the unique device ID assigned earlier has now expired.</div></li>
	<li>
<div align="justify">

Second step is to call the Push Notification web service from the mobile application and include the unique device ID (received from cloud messaging service) in the payload. You may want to pass some additional information like the device type, device operating system etc in the payload. A sample payload JSON is shown below:
<div id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:8deaa2ad-61ae-43d6-8179-78575cbdfd0d" class="wlWriterEditableSmartContent" style="float:none;margin:0;display:inline;padding:0;">

[sourcecode language="javascript"]
DevicePayload:{

deviceId:'APA9sdsdA',

deviceType:'mobile/tablet',

deviceOS:'android/apple',

userID:'xyz@gmail.com',

}

[/sourcecode]

</div>
</div></li>
	<li>
<div align="justify">Push notification web service will persist the payload in a local database.</div></li>
	<li>
<div align="justify">Core product which is responsible for generating events per user will create notification messages and publish it to the Messaging Queue.</div></li>
	<li>
<div align="justify">Push notification windows service’s functionality is to constantly poll the Messaging Queue and pull any new message that arrives to the queue. The service should then query the local database to get the device id associated with the user id for which the notification was generated.</div></li>
	<li>
<div align="justify">With the fetched device id, the windows service will then communicate with cloud messaging services (GCM/APN).</div></li>
</ol>
<p align="justify">This is the architecture at high level to design push notification service for your mobile application. In the next article (Part-2), I will cover the code required to communicate with the cloud messaging services.</p>]]></content><author><name>avegaraju</name></author><category term="APN" /><category term="apple push notification service" /><category term="architecure" /><category term="cloud messaging services" /><category term="design" /><category term="Design &amp;amp; Architecture" /><category term="GCM" /><category term="google cloud messaging service" /><category term="mobile" /><category term="push notification" /><summary type="html"><![CDATA[Overview of Push Notifications In this article, I am going to design the architecture for implementing push notifications for you mobile application. This part only has design and architecture information, code will be covered in Part 2.]]></summary></entry><entry><title type="html">A Thread Safe Singleton Class in .NET</title><link href="/2015/12/08/a-thread-safe-singleton-class-in-net/" rel="alternate" type="text/html" title="A Thread Safe Singleton Class in .NET" /><published>2015-12-08T17:32:00+00:00</published><updated>2015-12-08T17:32:00+00:00</updated><id>/2015/12/08/a-thread-safe-singleton-class-in-net</id><content type="html" xml:base="/2015/12/08/a-thread-safe-singleton-class-in-net/"><![CDATA[<p align="justify">In this post I will demonstrate creating a singleton class in .Net that is thread safe. As usual the singleton class should have a private constructor as shown below so that any other class cannot “directly” create an instance of our singleton class.</p>
<p align="justify"><!--more--></p>
<p align="justify">Apart from that, I have created two global variables, one to hold the instance of the Singleton class and another one of type object which will be used later for synchronization between threads (more on that later).</p>

<div id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:fa80e900-39bf-485c-b945-fc9e5bb5939c" class="wlWriterEditableSmartContent" style="float:none;margin:0;display:inline;padding:0;">

[sourcecode language="csharp" padlinenumbers="true" light="true" wraplines="true"]
    static SingletonSample _instance;
    static readonly object _synchronizer = new object();
    /// &amp;amp;lt;summary&amp;amp;gt;
    /// Private C'tor, so that this class cannot be instantited by other classes directly
    /// &amp;amp;lt;/summary&amp;amp;gt;
    private SingletonSample()
    {

    }

[/sourcecode]

</div>
<h6>Method 1 – Using synchronization lock</h6>
<p> </p>
<p align="justify">GetInstance is a public static method, this method is the only way by which any other class can get instance of the singleton class.</p>
<p align="justify">Below code snippet uses double check pattern before creating the instance of the singleton class. The first If statement, if true, will give the instance of Singleton class instantly. However, if _instance variable is null then program will enter a critical section (the lock statement) synchronized using a global object (_synchronizer). Inside the critical section, I am checking the _instance  variable again if it is null (double check), if it is, then we finally create the instance of the class.</p>
<p align="justify">One interesting point to note here is, I am not creating the instance directly and returning it back. I am first assigning the class reference into a temporary object of type SingletonClass (tempInstance) and then doing a  <a href="https://msdn.microsoft.com/en-us/library/system.threading.volatile(v=vs.110).aspx">Volatile</a> write on the actual instance variable (_instance).</p>
<p> </p>

<p> </p>
<div id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:2559210c-f730-46f3-821d-6bb73ce1632b" class="wlWriterEditableSmartContent" style="float:none;margin:0;display:inline;padding:0;">

[sourcecode language="csharp"]
        /// &amp;amp;lt;summary&amp;amp;gt;
        /// Method is responsible for providing instance of this class.
        /// &amp;amp;lt;/summary&amp;amp;gt;
        /// &amp;amp;lt;returns&amp;amp;gt;Instance of SingleTonSample class&amp;amp;lt;/returns&amp;amp;gt;
        public static SingletonSample GetInstance()
        {
            //If instance is available return that.
            if (_instance != null)
                return _instance;

            //Critical section. Ony one thread can enter at a time.
            lock(_synchronizer)
            {
                //Check again if the instance in null
                if(_instance == null)
                {
                    SingletonSample tempInstance = new SingletonSample();
                    //Volatile write to make sure that _instance is 
                    //populated with tempInstance reference without any compiler optimization.
                    Volatile.Write(ref _instance, tempInstance);
                }
            }

            return _instance;
        }
[/sourcecode]

</div>
<p align="justify">The problem with this approach is that if this method is used in a highly parallel system, the critical section will cause all threads to do nothing but wait for an instance of Singleton class to be created. However, this will happen only once when the first instance is getting created, but still, this is wasteful of the resources.</p>
<p align="justify">Below is another, more efficient way of creating a singleton which neither uses double check pattern nor it has a critical section for thread synchronization.</p>

<h6>Method 2 – Without Critical Section or Double Check</h6>
<p align="justify">Below method will allow multiple threads to create instance of Singleton class, but <a href="https://msdn.microsoft.com/en-us/library/system.threading.interlocked(v=vs.110).aspx">Interlocked</a> class’s CompareExchange will make sure that only one instance is assigned to _instance variable. Objects created by other  threads and not assigned to _instance variable will soon become Orphan and  will be garbage collected at a later point of time by the CLR.</p>

<div id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:3c6dd858-1ab2-41bc-9bfa-fc04938077a4" class="wlWriterEditableSmartContent" style="float:none;margin:0;display:inline;padding:0;">

[sourcecode language="csharp"]
        /// &amp;amp;lt;summary&amp;amp;gt;
        /// Method is responsible for providing instance of this class without critical section
        /// or double check pattern.
        /// &amp;amp;lt;/summary&amp;amp;gt;
        /// &amp;amp;lt;returns&amp;amp;gt;Instance of SingletonSample class&amp;amp;lt;/returns&amp;amp;gt;
        public static SingletonSample GetInstance()
        {
            //If instance is available return that.
            if (_instance != null)
                return _instance;

            SingletonSample tempInstance = new SingletonSample();
            /*Multiple threads will create singleton object, but only 
            *one will be asssgined to _instance variable. Rest others will be 
            *GC'd (Garbage Collected) later at some point of time. 
            */
            Interlocked.CompareExchange(ref _instance, tempInstance,null);

            return _instance;
        }
[/sourcecode]

</div>
<p>Both methods are thread safe. However, method 2 is marginally more efficient and lean as compared to the first one.</p>]]></content><author><name>avegaraju</name></author><category term=".net" /><category term="c#" /><category term="csharp" /><category term="Design &amp;amp; Architecture" /><category term="double check pattern" /><category term="Singleton" /><category term="thread safe" /><summary type="html"><![CDATA[In this post I will demonstrate creating a singleton class in .Net that is thread safe. As usual the singleton class should have a private constructor as shown below so that any other class cannot “directly” create an instance of our singleton class. Apart from that, I have created two global variables, one to hold the instance of the Singleton class and another one of type object which will be used later for synchronization between threads (more on that later).]]></summary></entry></feed>