<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Jon Blankenship on Medium]]></title>
        <description><![CDATA[Stories by Jon Blankenship on Medium]]></description>
        <link>https://medium.com/@jonblankenship?source=rss-b96d4d34a540------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*adhkNmGiakQ3iM4q.</url>
            <title>Stories by Jon Blankenship on Medium</title>
            <link>https://medium.com/@jonblankenship?source=rss-b96d4d34a540------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 20:24:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jonblankenship/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[My Top 10 Traits in a Development Job]]></title>
            <link>https://medium.com/@jonblankenship/my-top-10-traits-in-a-development-job-540d9335cf8?source=rss-b96d4d34a540------2</link>
            <guid isPermaLink="false">https://medium.com/p/540d9335cf8</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[remote-working]]></category>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[jobs]]></category>
            <dc:creator><![CDATA[Jon Blankenship]]></dc:creator>
            <pubDate>Sat, 13 Jun 2020 18:30:00 GMT</pubDate>
            <atom:updated>2020-06-13T20:44:17.927Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Q0A25TdhyA6VH9yi.jpg" /></figure><p>In my almost two decades as a developer I’ve become increasingly aware of what matters to me in a job, having been in half dozen different environments that excel in some traits but are lacking in others.</p><p>This list is my list of the things that are most important to me in a dev job at this time in my life.</p><p>This list changes with time as my circumstances and priorities change.</p><p>This list is likely different than your list.</p><p>It’s rare to find your “dream job” that fits all of your criteria.</p><p>Oftentimes you must compromise some of the less important traits for some of the more important ones.</p><p>I’ve done this.</p><p>It’s OK, as long as you understand the trade-offs you’re making.</p><p>Early in your career you have fewer choices. You can’t afford to be picky.</p><p>This is OK, because you likely have…</p><p>✔ More time<br> ✔ More to learn<br> ✔ Fewer limitations<br> ✔ More to experience</p><p>I share this list in hopes that it will help someone out there think critically about their next career move.</p><p>So without further ado, my Top 10 Desired Traits in a Development Job (roughly in order of importance):</p><h3>1. Remote-First Culture 🏡</h3><p>Being able to work remotely is key for me — I won’t ever work in an office again if I can avoid it.</p><p>The freedom to see my kids when they get home from school, have a coffee break with my wife, and just share more “regular” moments of daily life with my family is priceless.</p><p>I can’t get back the hours I’ve spent commuting to and from work, but going forward I can appreciate the time that I won’t spend sitting behind the wheel every day.</p><p>The company should be remote first, with remote work ingrained in the company culture.</p><p>I don’t want to be the odd man out on a team of mostly co-located coworkers.</p><p>It’s not enough for a company to simply slap a few Skype invites on their meeting requests and call it a day.</p><p>A healthy expectation for remote workers is needed.</p><p>Bad: Since you’re remote, you should be available 24/7.</p><p>Good: 40 hrs/wk is enough. Though there may be an occasional week where extra hours are needed, usually you put in your 40 hrs &amp; then go enjoy your non-work life.</p><h3>2. Culture of Craftsmanship 🛠</h3><blockquote><em>craft (n.): an art, trade, or occupation requiring special skill</em></blockquote><p>Good software is produced when development is viewed as a craft.</p><p>Bad software is produced when development is viewed as an assembly line process.</p><p>I want to work with colleagues who view their work as a craft to be honed.</p><p>I don’t want to work for a company that views development as mechanical process that can be streamlined by simply adding more metrics, KPIs, and process.</p><p>Benefits of a culture of craftsmanship:</p><p>✔ Higher quality<br> ✔ Pride of ownership<br> ✔ Continuous improvement</p><h3>3. Software is the Product 💾</h3><p>There is a big difference between working for a company where software development is a supporting function vs. one where it is the primary function.</p><p>Cost center vs. profit center mentality.</p><p>I recently <a href="https://twitter.com/Jon_Blankenship/status/1261703417489211392">tweeted about this</a>.</p><p>When viewed as a cost center, the emphasis is on keeping costs down.</p><p>This usually means minimizing investment the people and processes involved in producing software, since it is not the company’s core function.</p><p>When viewed as a profit center, the emphasis is on maximizing profits.</p><p>This usually means investing in the people and processes involved in producing the main product, which contributes directly to the company’s bottom line.</p><p>In my experience, the cost center attitude is “Get it done.”</p><p>The profit center attitude is “Get it done well.”</p><p>I much prefer the latter.</p><h3>4. Observes Development Best Practices 👨‍💻</h3><p>This one is a byproduct of a culture of craftsmanship.</p><p>A team that strives to produce quality software follows best practices.</p><p>Best practices include…</p><p>✔ YAGNI<br> ✔ Clean code<br> ✔ Defensive code<br> ✔ Design patterns<br> ✔ Consistent style<br> ✔ SOLID principles<br> ✔ Automated tests<br> ✔ Minimize complexity<br> ✔ Side-effect free functions<br> ✔ etc…</p><p>Using good development practices promotes…</p><p>👍 quality<br> 👍 reliability<br> 👍 readability<br> 👍 maintainability<br> 👍 robustness</p><p>A clean, well-structured, well-tested codebase is also more enjoyable to work in.</p><p>This is the kind of codebase I prefer to work in.</p><h3>5. Observes DevOps Best Practices 💻</h3><p>A company that prioritizes software quality prioritizes DevOps.</p><p>An investment in DevOps goes a long way towards improving the lives of the developers.</p><p>The benefits of DevOps automation are many:</p><p>☑ Higher stability<br> ☑ Higher throughput<br> ☑ Easier deployments<br> ☑ Reduced human error<br> ☑ Less developer time spent on deployments</p><h3>6. Talented and Driven Colleagues 👩‍💻</h3><p>I want to work with colleagues who will make me better by working alongside them.</p><p>These aren’t people who simply punch the clock to earn their paycheck.</p><p>They’re talented, smart, curious, and driven individuals who take pride in their work.</p><p>I’ve worked with several people like this over my career, and they’re responsible for much of my growth as a developer, for which I’m indebted.</p><p>You can’t help but grow in your craft if you’re interacting with talented individuals on a daily basis via design meetings, code reviews, debugging sessions, architectural discussions, etc…</p><h3>7. Anti-Enterprise 🏢</h3><p>By “anti-enterprise,” I mean a company where there is minimal corporate process/bureaucracy.</p><p>I prefer working for a small, fast company over a large, slow enterprise.</p><p>I have a low tolerance for waste.</p><p>I prefer to spend my time creating value rather than sitting in meetings and entering support tickets.</p><p>I want to be empowered to do the things that I need to do to do my job.</p><p>I don’t want to have to…<br> ↪ spend 15 minutes entering a change request<br> ↪ to have a dev database restored<br> ↪ that will take a week to complete<br> ↪ that would have otherwise taken me 5 minutes<br> ↪ if given the adequate permissions.</p><p>I don’t like to be handcuffed by process.</p><p>I have no desire to climb the corporate ladder or play status games.</p><h3>8. Potential for Professional Growth 📈</h3><p>I want to be challenged to grow professionally.</p><p>My growth as a developer is a function of…</p><p>1️⃣ my own initiative,<br> 2️⃣ the project(s) I’m working on, and<br> 3️⃣ the people that I’m working with.</p><p>The greatest periods of growth in my career have been a result of not only own initiative, but also the fact that I was working on interesting projects with, more importantly, smart colleagues (#6).</p><p>Your potential to grow as a developer will change over the course of your time with a company.</p><p>Often this potential is greatest when you first join and diminishes over time, but not always.</p><p>New projects or new team members can rekindle the fires of growth.</p><h3>9. Clear Line from Contribution to Value ➡</h3><p>I want to be able to see how my contribution contributes to the success of the company.</p><p>This contributes to a greater satisfaction in a job well done.</p><p>It’s easier to see how your contribution affects the overall success of the company when …</p><p>✔ the company is small (#7), and<br> ✔ software is the product (#3).</p><h3>10. Compensation/Benefits/Equity 💵</h3><p>This one comes last in my top 10, but that doesn’t mean it’s not important.</p><p>I want to be compensated fairly for my work. Ideally that includes equity in the company.</p><p>If my contribution is tied to the success of the company, I prefer my compensation to be as well.</p><p>Once equity enters the equation, you shift from purely trading time for money, to trading time for money + a stake in something of potentially great value.</p><p>Being well-compensated is one way that a company can show me that my contribution is valued.</p><p>There you have it. My Top 10 Desired Traits in a Software Development Job.</p><p>What are some things on your list? Drop your comment on the original thread <a href="https://twitter.com/Jon_Blankenship/status/1269716700682993666">here</a>.</p><p>- Jon</p><p><em>I’m a developer and solo SaaS founder who likes to build things and share what I learn with others. If you’re interested software development, launching things, or random early morning thoughts, consider </em><a href="https://twitter.com/Jon_Blankenship"><em>following me</em></a><em> on Twitter or </em><a href="https://unique-designer-4037.ck.page/7e33ea9455"><em>subscribe</em></a><em> to my newsletter.</em> <em>Thanks for reading!</em></p><p><em>Originally published at </em><a href="https://blog.jonblankenship.com/2020/06/13/top-10-desired-traits-in-a-development-job/"><em>https://blog.jonblankenship.com</em></a><em> on June 13, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=540d9335cf8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Global Exception Handling in ASP.NET Core Web API]]></title>
            <link>https://medium.com/@jonblankenship/global-exception-handling-in-asp-net-core-web-api-36668452844?source=rss-b96d4d34a540------2</link>
            <guid isPermaLink="false">https://medium.com/p/36668452844</guid>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[exception]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Jon Blankenship]]></dc:creator>
            <pubDate>Mon, 13 Apr 2020 00:30:00 GMT</pubDate>
            <atom:updated>2020-04-13T11:45:58.496Z</atom:updated>
            <content:encoded><![CDATA[<p>A good web API is consistent and follows established patterns for communicating error states to the client, leveraging the appropriate HTTP status codes. To that end, a global exception handler can be very helpful in consolidating a service’s error handling logic in one place and translating errors into the appropriate responses to send back to the client. In this post I’ll show you how you can plug custom exception-handling logic into the ASP.NET Core request pipeline to handle any exceptions that are thrown in your API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/0*M01KQBuWIRqWJIxc.png" /></figure><p>ASP.NET Core gives provides the ability to write middleware, which is logic inserted into the pipeline that the framework runs for every request that is received by the application. ASP.NET Core ships with core middleware components that enable things like rendering MVC pages, defining endpoint routes, and adding authentication support, and these things are configured in the application’s Startup class, where you can also add your own custom middleware components. This ability to easily configure and customize how ASP.NET Core processes requests is tremendously useful and powerful. The <a href="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?view=aspnetcore-3.1">Microsoft documentation</a> goes into more detail on how middleware works in ASP.NET Core, so I won&#39;t spend too much more time on this.</p><p>For this post, we’ll be creating exception-handling middleware to catch and handle any exceptions that are thrown during the execution of a request to our service. This is something I implement in every API that I write, and it not only makes the handling of exceptions and the responses from my API consistent, but it also helps keep my codebase a bit cleaner.</p><p>The source code for the sample project demonstrating what we’ll be implementing here can be found on Github <a href="https://github.com/jonblankenship/blog-examples/tree/master/ErrorHandlingMiddlewareSample">here</a>.</p><h3>Error-Handling Middleware</h3><p>Let’s jump straight to the code. Here’s our <a href="https://github.com/jonblankenship/blog-examples/blob/master/ErrorHandlingMiddlewareSample/Middleware/ErrorHandlingMiddleware.cs">ErrorHandlingMiddleware</a> class:</p><pre>public class ErrorHandlingMiddleware<br>{<br>    private readonly RequestDelegate _next;<br><br>    public ErrorHandlingMiddleware(RequestDelegate next)<br>    {<br>        _next = next;<br>    }<br><br>    public async Task Invoke(HttpContext context)<br>    {<br>        try<br>        {<br>            await _next(context);<br>        }<br>        catch (Exception ex)<br>        {<br>            await HandleExceptionAsync(context, ex);<br>        }<br>    }<br><br>    private static Task HandleExceptionAsync(HttpContext context, Exception exception)<br>    {<br>        HttpStatusCode status;<br>        string message;<br>        var stackTrace = String.Empty;<br><br>        var exceptionType = exception.GetType();<br>        if (exceptionType == typeof(BadRequestException))<br>        {<br>            message = exception.Message;<br>            status = HttpStatusCode.BadRequest;<br>        }<br>        else if (exceptionType == typeof(NotFoundException))<br>        {<br>            message = exception.Message;<br>            status = HttpStatusCode.NotFound;<br>        }<br>        else<br>        {<br>            status = HttpStatusCode.InternalServerError;<br>            message = exception.Message;            <br>            if (env.IsEnvironment(&quot;Development&quot;))<br>                stackTrace = exception.StackTrace;<br>        }<br><br>        var result = JsonSerializer.Serialize(new { error = message, stackTrace });<br>        context.Response.ContentType = &quot;application/json&quot;;<br>        context.Response.StatusCode = (int)status;<br>        return context.Response.WriteAsync(result);<br>    }<br>}</pre><p>In the Invoke(..) method of our middleware component, we wrap the invocation of our _next delegate in a try..catch. So any processing that happens further along in the pipeline will be included in this try..catch.</p><p>If there’s an exception, our HandleExceptionAsync(..) method handles it, where we have access to the HttpContext for the request, as well as the Exception that occurred. If you implement something similar, this is where you&#39;ll likely modify the logic to meet your desired behavior according to your needs. Here I branch depending on the type of exception that was thrown.</p><p>Note that we’re setting the StatusCode property on the context.Response object depending on the type of exception that we&#39;re handling. We&#39;re also writing out the error message to the response body, as well as the the stack trace, in the case of an unhandled exception when running in the &quot;Development&quot; environment.</p><p>If I’m explicitly throwing an exception in my application, usually I’ll create my own custom exception type that inherits from Exception for the particular exceptional scenario. In this case, I&#39;ve created BadRequestException and NotFoundException, which map nicely to HTTP response codes, but your situation may differ. Your exceptions may be more specific to your particular API.</p><p>Here’s my rather boring NotFoundException class:</p><pre>public class NotFoundException : Exception<br>{<br>    public NotFoundException(string message) : base(message)<br>    { }<br>}</pre><h3>Configuring the Middleware</h3><p>To configure our API to use our new ErrorHandlingMiddleware, we call app.UseMiddleware(..), passing our middleware type in our class&#39;s Configure(..) method:</p><pre>public void Configure(IApplicationBuilder app, IWebHostEnvironment env)<br>{<br>    if (env.IsDevelopment())<br>    {<br>        app.UseDeveloperExceptionPage();<br>    }<br><br>    // Hook in the global error-handling middleware<br>    app.UseMiddleware(typeof(ErrorHandlingMiddleware));<br><br>    // Register any middleware to report exceptions to a third-party service *after* our ErrorHandlingMiddleware<br>    app.UseExcepticon();<br>    <br>    // snip<br>}</pre><p>Note that the order in which you register middleware in your application’s request pipeline matters. The various middleware components execute sequentially in the order in which they’re registered. In the case of a global exception handler like our ErrorHandlingMiddleware, we&#39;ll register it early in the Configure(..) method so that it captures exceptions that occur in downstream middleware components.</p><p>Also note that if you’re using an exception tracking service that captures the exception for reporting but then re-throws it to allow it to be handled upstream, that middleware registration should happen after the registration of our ErrorHandlingMiddleware. In this sample I&#39;m using <a href="https://excepticon.io/">Excepticon</a>. (Full disclosure: I <a href="https://blog.jonblankenship.com/2020/03/05/excepticon-exception-monitoring-for-dot-net/">wrote Excepticon</a>.) But using a third-party exception tracking service is absolutely <strong>not</strong> necessary for implementing global exception handling for you API like what I&#39;m describing in this post.</p><p>When our ErrorHandlingMiddleware catches an exception, execution of the pipeline halts, it sets the appropriate settings on the response, and the API call immediately returns the response to the client.</p><h3>Application Code</h3><p>Handling exceptions globally in our middleware not only gives us a uniform way to handle unexpected exceptions that occur in our API, but it also allows us to eliminate some boilerplate code in our controllers, if desired.</p><p>In the sample project, there’s a <a href="https://github.com/jonblankenship/blog-examples/blob/7d1192f7d21e2532d4deae6d785ff25a06fa5144/ErrorHandlingMiddlewareSample/Controllers/StocksController.cs#L27">StocksController</a> that has a GetById(Guid stockId) method that calls a domain service to get a specific stock by ID. The controller method returns the requested stock to the caller:</p><pre>[HttpGet]<br>[Route(&quot;{stockId}&quot;)]<br>public IActionResult GetById(Guid stockId)<br>{<br>    var stock = _stocksService.GetStock(stockId);<br>    return new OkObjectResult(stock);<br>}</pre><p>This is a very barebones example and most real controller methods probably won’t be this thin. But note that we’re only worrying about the happy path here — what if the client sends us a stockId that we don&#39;t have?</p><p>The GetStock(Guid stockId) method on the <a href="https://github.com/jonblankenship/blog-examples/blob/7d1192f7d21e2532d4deae6d785ff25a06fa5144/ErrorHandlingMiddlewareSample/Services/StocksService.cs#L24">StocksService</a> domain service considers a request for a stockId that doesn&#39;t exist to be an exceptional case. That is, it shouldn&#39;t happen, and if it does, the service immediately aborts, short-circuiting any further execution, and expects someone upstream to handle the exception. It throws a NotFoundException accordingly:</p><pre>/// &lt;summary&gt;<br>/// Returns the &lt;see cref=&quot;Stock&quot;/&gt; with the requested &lt;see cref=&quot;stockId&quot;/&gt;<br>/// &lt;/summary&gt;<br>/// &lt;param name=&quot;stockId&quot;&gt;The ID of the &lt;see cref=&quot;Stock&quot;/&gt; to return&lt;/param&gt;<br>/// &lt;returns&gt;The &lt;see cref=&quot;Stock&quot;/&gt; with the requested &lt;see cref=&quot;stockId&quot;/&gt;&lt;/returns&gt;<br>/// &lt;exception cref=&quot;NotFoundException&quot;&gt;&lt;/exception&gt;<br>public Stock GetStock(Guid stockId)<br>{<br>    var stock = Stocks.FirstOrDefault(s =&gt; s.StockId == stockId);<br>    if (stock == null)<br>        throw new NotFoundException($&quot;Stock with ID {stockId} not found.&quot;);<br><br>    return stock;<br>}</pre><p>When this exception is thrown, the normal execution is interrupted and the catch block on our ErrorHandlingMiddleware takes over. We stop execution closer to where the exception occurs, and avoid branching logic in our controller to determine whether to return a 200- or a 400-series HTTP response code.</p><p>Note that the method documentation indicates the exception type(s) that this method might throw. This is helpful for consumers of IStockService to know what types of exceptions might be thrown when invoking the method.</p><h3>A Note on this Example</h3><p>Some developers will bristle at the idea of using an exception for the purpose in my example above, arguing that throwing is an expensive operation, and if you can anticipate an exceptional case, you should code for it. Don’t use exceptions for control flow.</p><p>While I understand and agree with the spirit of this objection, I tend to take a more pragmatic position.</p><p>This approach eliminates a fair amount of boilerplate if...else branching logic up the callstack until we get to the controller where we can handle it and return the appropriate HTTP response, especially if the callstack is deep or we invoke this method from multiple controller methods. For me, the benefit in terms of readability and maintainability is worth the cost of throwing the exception in this case, especially since this condition won&#39;t normally happen. The likelihood of it happening is further reduced in cases where I control both the API and the client(s).</p><p>The ASP.NET Core middleware pattern gives us a clean and elegant way to interrupt execution and handle error conditions.</p><p>I wouldn’t take this approach on an API where I was trying to squeeze out very last drop of performance or an API running at massive scale. But it has served me well on the APIs that I’ve written.</p><p>Even if you don’t like my example and you choose not to throw exceptions for error conditions like the one above in your API code, implementing a global exception handling middleware component like I’ve described is still a good way to uniformly handle exceptions that you don’t anticipate.</p><h3>Testing It Out</h3><p>If we run the sample, we see that a call to the GET /stocks/{stockId} endpoint with a valid ID returns a 200 response with the stock data in the response body:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/0*2jSMSy57-YcoM2rX.png" /></figure><p>If we switch the stockId to an ID that doesn&#39;t exist, we see that the API returns a 404 Not Found and the message we included with our exception is included in the message body:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/0*mTaRAhT9w8tCTKFV.png" /></figure><p>Further, if we manually throw an ApplicationException in the StocksService.Get(Guid stockId) method, we get a 500 Internal Service response with the error and stackTrace included in the response body, since ApplicationException is not one of the exception types that we&#39;re specifically handling in ErrorHandlingMiddleware:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/0*1aOgjpI0y5pN_FGZ.png" /></figure><h3>Wrapping Up</h3><p>In this post we’ve shown how to implement a global exception handler in an ASP.NET Core web API. By creating an ASP.NET Core middleware component, we’re able to catch and handle exceptions uniformly and ensure that the API is returning consistent and expected responses to its callers.</p><p>- Jon</p><p><em>I’m a developer and solo SaaS founder who likes to build things and share what I learn with others. If you’re interested software development, launching things, or random early morning thoughts, consider </em><a href="https://twitter.com/Jon_Blankenship"><em>following me</em></a><em> on Twitter or </em><a href="https://unique-designer-4037.ck.page/7e33ea9455"><em>subscribe</em></a><em> to my newsletter.</em> <em>Thanks for reading!</em></p><p><em>Originally published at </em><a href="https://blog.jonblankenship.com/2020/04/12/global-exception-handling-in-aspnet-core-api/"><em>https://blog.jonblankenship.com</em></a><em> on April 13, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36668452844" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Razor-Powered E-mail in Azure Functions]]></title>
            <link>https://medium.com/@jonblankenship/razor-powered-e-mail-in-azure-functions-b9a395995ff?source=rss-b96d4d34a540------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9a395995ff</guid>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[azure-functions]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Jon Blankenship]]></dc:creator>
            <pubDate>Sun, 05 Apr 2020 14:15:00 GMT</pubDate>
            <atom:updated>2020-04-06T11:57:29.322Z</atom:updated>
            <content:encoded><![CDATA[<p>On a couple of recent projects I’ve had the need to send automated e-mails to my users. For both implementations I chose the same approach: use <a href="https://docs.microsoft.com/en-us/aspnet/core/mvc/views/razor?view=aspnetcore-3.1">Razor</a> templates combined with <a href="https://docs.microsoft.com/en-us/azure/azure-functions/">Azure Functions</a> to build a simple, maintainable, and loosely-coupled solution for sending transactional e-mails.</p><p>In this post I’ll show you how to do the same.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oDIPFmjlEaj0rvEI.png" /></figure><p>At a high level, here’s what happens when my application needs to send an e-mail:</p><ol><li>Application code determines that an e-mail should be sent.</li><li>Application code writes a message to an <a href="https://docs.microsoft.com/en-us/azure/service-bus-messaging/service-bus-queues-topics-subscriptions">Azure Service Bus</a> queue (email-queue).</li><li>Azure Function (email-queue-trigger-function) receives message from Service Bus queue.</li><li>Azure Function builds e-mail from a Razor template and a template model.</li><li>Azure Function sends e-mail.</li></ol><p>For this post, I’ll focus on steps 3 through 5, the building and sending of the e-mail from an Azure Function.</p><h3>Why This Approach?</h3><p>I like this approach for a couple of reasons. Let’s talk about why I chose this path first, and then we’ll get into the code.</p><h3>Azure Functions</h3><p>My application already uses Azure Functions for some of its processing, and my requirement is to automatically send a user an e-mail when certain conditions are met during the course of that processing. Sending the e-mail is a side effect of the core domain processing — it should certainly happen, but I want it to happen in a separate process. I consider the building and sending of e-mails as supporting application logic and not part of my domain logic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/120/0*7XNg0yCnEHeiP1vU.png" /></figure><p>Using a <a href="https://docs.microsoft.com/en-us/azure/azure-functions/functions-bindings-service-bus-trigger?tabs=csharp">Service Bus-triggered Azure Function</a> works nicely for this. When the conditions are met that need to trigger an e-mail, the core process can simply enqueue the appropriate message on the e-mail Service Bus queue and continue with its work. Fire and forget.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/120/0*dQGPTJEu1y0nxrIz.png" /></figure><p>The Service Bus queue is durable and reliable. We can rest assured that once the message is on the queue, it won’t be lost. The Service Bus-triggered Azure Function responsible for sending e-mails is invoked as soon as there is a message on the queue, and it starts its work building and sending the e-mail. If there’s a failure in my receiving Azure Function or it’s down for some reason, the Service Bus queue will keep the message until it can be properly handled.</p><p>Isolating the e-mail sending logic in its own Azure Function offers a few benefits:</p><ol><li>It promotes <a href="https://en.wikipedia.org/wiki/Loose_coupling">loose coupling</a>.</li><li>It keeps the domain code focused and not concerned with supporting functions.</li><li>It can be scaled independently from other functions.</li></ol><h3>Razor Templates</h3><p>Razor templates are particularly well-suited for defining the layout of an HTML-based e-mail. Razor is a markup language used tor generating HTML from a Razor template combined with a C# object.</p><p>Razor allows you to define the body of your layout <a href="https://en.wikipedia.org/wiki/Declarative_programming">declaratively</a>, which is a natural programming paradigm for expressing a desired outcome, like a user interface, query result, file format, or, as in our case, an e-mail body.</p><p>I define a Razor e-mail template for each type of e-mail that my application needs to send. Each template has a corresponding model class, representing the data that is needed to render that template. When I need to render the template (to build the e-mail), I pass my template and an instance of the corresponding model class to a Razor rendering engine, and it returns the generated HTML as a string.</p><p>I much prefer this approach to building the e-mail body <a href="https://en.wikipedia.org/wiki/Imperative_programming">imperatively</a> by concatenating strings in C#!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/0*YOsTXlY37ASWg1bC.png" /></figure><h3>Prerequisites</h3><p>There are a couple of prerequisites we’ll need in order to get our Azure Function sending e-mail:</p><ol><li>Razor Rendering Engine — I’m using the <a href="https://www.nuget.org/packages/RazorLight.Unofficial/2.0.0-beta1.3">RazorLight.Unofficial 2.0.0-beta1.3</a> package to generate my HTML from the Razor template and model. It’s a pre-release package, but if that makes you squeamish there are other alternatives out there.</li><li>Transactional E-mail Service — For my e-mail service I’m using <a href="https://www.mailgun.com/">Mailgun</a>, which I’ve been fairly happy with. You can send e-mail via their HTTP API or by SMTP, and they offer many of the features that you’d expect from an enterprise e-mail service.</li></ol><h3>Implementation</h3><p>Let’s dig into some code. We’ll start by looking at the e-mail message that we’ll be sending.</p><h3>The Message</h3><p><strong>Razor Template</strong></p><p>All of my e-mail templates live in a folder in my Functions project called \EmailTemplates. In it there&#39;s a Razor template named NewExceptionGroupTemplate.cshtml:</p><pre>@model ServiceTrace.Domain.Model.Email.NewExceptionGroupModel<br><br>&lt;h3&gt;@Model.Subject&lt;/h3&gt;<br><br>&lt;p&gt;To view the full exception details, click &lt;a href=&#39;@Model.Url&#39;&gt;here&lt;/a&gt;&lt;/p&gt;<br><br>&lt;div&gt;&lt;strong&gt;Message:&lt;/strong&gt; @Model.Message&lt;/div&gt;<br>&lt;div&gt;&lt;strong&gt;Time Occurred:&lt;/strong&gt; @Model.TimeOccurred.ToString(&quot;G&quot;) UTC&lt;/div&gt;<br>&lt;div&gt;&lt;strong&gt;Stack Trace:&lt;/strong&gt;&lt;/div&gt;<br>&lt;div&gt;<br>    &lt;pre&gt;&lt;code&gt;@Model.StackTrace&lt;/code&gt;&lt;/pre&gt;<br>&lt;/div&gt;</pre><p><strong>Important:</strong> Set the Build Action for all Razor email templates to Embedded Resource and the Copy to Output Directory to Do not copy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/0*CilcoUDv4YD3kOOd.png" /></figure><p><strong>Template Model</strong></p><p>The model that provides the data for this template is NewExceptionGroupModel. It&#39;s a <a href="https://en.wikipedia.org/wiki/Plain_old_CLR_object">POCO</a> that has properties for each of the data items that will be merged into the Razor template:</p><pre>public class NewExceptionGroupModel : IEmailTemplateModel<br>{<br>    public NewExceptionGroupModel() { }<br>    <br>    public NewExceptionGroupModel(ExceptionInstance exceptionInstance, IProject project)<br>    {<br>        Subject = $&quot;New exception thrown in {project.Name}&quot;; <br>        Message = exceptionInstance.Message;<br>        TimeOccurred = exceptionInstance.TimeOccurred;<br>        StackTrace = exceptionInstance.StackTrace;<br>        Url = exceptionInstance.Url;<br>    }<br><br>    public string Subject { get; set; } <br><br>    public string TemplateName =&gt; &quot;NewExceptionGroupTemplate&quot;;<br><br>    public string Message { get; set; }<br><br>    public DateTimeOffset TimeOccurred { get; set; }<br><br>    public string StackTrace { get; set; }<br><br>    public string Url { get; set; }<br>}</pre><p>Finally, IEmailTemplateModel has a couple of properties that are common to all of my e-mail template models:</p><pre>public interface IEmailTemplateModel<br>{<br>    string Subject { get; }<br><br>    string TemplateName { get; }<br>}</pre><p>The TemplateName property identifies the Razor template that this model corresponds with. It will be used to retrieve the appropriate Razor template when we&#39;re ready to generate the HTML for the e-mail body. The rest of the properties are data items that will be merged into the Razor template.</p><p>So that’s all that’s needed to define the e-mail message body — we’ll see how it gets turned into HTML in a moment…</p><h3>Receive the Message</h3><p>I’m using a Service Bus queue, cleverly named email-queue, as the channel by which the rest of my application notifies my e-mail function that an e-mail needs to be sent. To do this, the application creates a new NewExceptionGroupModel with the appropriate data and puts it on the queue with a couple of additional user properties:</p><ul><li>EmailModelType — tells the e-mail function what type of model is in the queue message body.</li><li>ToEmailAddress — tells the e-mail function who to send the e-mail to. (I’ve made this a user property on the message, but there’s no reason why it couldn’t be defined on IEmailTemplateModel and be part of the model.)</li></ul><p>The function that responds to a new message on email-queue reads the user properties on the message and deserializes the message body into an instance of the appropriate e-mail template model, NewExceptionGroupModel in this case, and invokes _emailSender.SendEmailAsync(..) to build and send the e-mail:</p><pre>[FunctionName(&quot;email-queue-trigger-function&quot;)]<br>public async Task Run([ServiceBusTrigger(&quot;email-queue&quot;, Connection = &quot;ServiceBusConnectionString&quot;)] Message message, ILogger log)<br>{<br>    using (ExcepticonSdk.Init(_appSettings.ExcepticonOptions))<br>    {<br>        try<br>        {<br>            if (message.UserProperties.ContainsKey(EmailModelTypeKey))<br>            {<br>                var modelType = message.UserProperties[EmailModelTypeKey].ToString();<br>                IEmailTemplateModel emailModel = null;<br>                switch (modelType)<br>                {<br>                    case nameof(NewExceptionGroupModel):<br>                        emailModel = JsonConvert.DeserializeObject&lt;NewExceptionGroupModel&gt;(Encoding.UTF8.GetString(message.Body, 0, message.Body.Length));<br>                        break;<br>                    // handle other types of e-mails here<br>                }<br><br>                if (emailModel != null)<br>                    await _emailSender.SendEmailAsync(message.UserProperties[&quot;EmailAddress&quot;].ToString(), emailModel);<br>            }<br>        }<br>        catch (Exception e)<br>        {<br>            ExcepticonSdk.CaptureException(e);<br>        }<br>    }<br>}</pre><p>(Shameless plug: I’ve wrapped my function body in a try..catch that sends any exceptions that occur to <a href="https://excepticon.io/">Excepticon</a>, an exception monitoring service. I built Excepticon and wrote about it in a <a href="https://blog.jonblankenship.com/2020/03/05/excepticon-exception-monitoring-for-dot-net/">previous post</a>. Using Excepticon is certainly not required for the topic we&#39;re discussing here, but if you&#39;re looking for an exception monitoring service, I invite you to check it out. Now, back to our program...)</p><h3>Build and Send</h3><p>The EmailSender instance is managed my IoC container and injected into the function. The interface is straight-forward:</p><pre>public interface IEmailSender<br>{<br>    Task SendEmailAsync(string toAddress, IEmailTemplateModel templateModel);<br>}</pre><p>The implementation of IEmailSender.SendEmailAsync(..) consists of rendering the e-mail template and corresponding model as a string of HTML, and then building the web request to POST to the Mailgun API:</p><pre>public class EmailSender : IEmailSender<br>{<br>    private readonly IAppSettings _appSettings;<br>    private readonly RazorLightEngine _razorLightEngine;<br>    private readonly HttpClient _httpClient;<br>    private const string MailGunBaseUrl = &quot;https://api.mailgun.net/v3&quot;;<br><br>    public EmailSender(IAppSettings appSettings)<br>    {<br>        _appSettings = appSettings ?? throw new ArgumentNullException(nameof(appSettings));<br><br>        _razorLightEngine = new RazorLightEngineBuilder()<br>            .SetOperatingAssembly(Assembly.GetExecutingAssembly())<br>            .UseEmbeddedResourcesProject(typeof(Startup))<br>            .UseMemoryCachingProvider()<br>            .Build();<br><br>        _httpClient = CreateHttpClient();<br>    }<br><br>    public async Task SendEmailAsync(string toAddress, IEmailTemplateModel templateModel)<br>    {<br>        var emailBody = await RenderEmailTemplateAsStringAsync(templateModel);<br>        var requestContent = new FormUrlEncodedContent(new List&lt;KeyValuePair&lt;string, string&gt;&gt;<br>        {<br>            new KeyValuePair&lt;string, string&gt;(&quot;from&quot;, _appSettings.EmailSettings.SupportEmailAddress),<br>            new KeyValuePair&lt;string, string&gt;(&quot;to&quot;, toAddress),<br>            new KeyValuePair&lt;string, string&gt;(&quot;subject&quot;, templateModel.Subject),<br>            new KeyValuePair&lt;string, string&gt;(&quot;html&quot;, emailBody)<br>        });<br><br>        var result = await _httpClient.PostAsync($&quot;{_appSettings.EmailSettings.Domain}/messages&quot;, requestContent);<br>        result.EnsureSuccessStatusCode();<br>    }<br><br>    private async Task&lt;string&gt; RenderEmailTemplateAsStringAsync(IEmailTemplateModel templateModel)<br>    {<br>        var templatePath = $&quot;EmailTemplates.{templateModel.TemplateName}.cshtml&quot;;<br>        return await _razorLightEngine.CompileRenderAsync(templatePath, templateModel);<br>    }<br><br>    private HttpClient CreateHttpClient()<br>    {<br>        var httpClient = new HttpClient { BaseAddress = new Uri($&quot;{MailGunBaseUrl}/&quot;) };<br>        var authHeader = $&quot;api:{_appSettings.EmailSettings.MailGunApiKey}&quot;;<br>        httpClient.DefaultRequestHeaders.Add(&quot;Authorization&quot;, $&quot;Bearer {authHeader.Base64Encode()}&quot;);<br>        return httpClient;<br>    }<br>}</pre><p>And that’s it! Most of the heavy lifting is done by the RazorLightEngine and Mailgun.</p><h3>Gotchas</h3><p>There are a few bumps I ran into along the way while trying to get this to work. Hopefully this will save you some pain if you’re going down the same path.</p><p><strong>Error compiling Razor when using the latest Microsoft.NET.Sdk.Functions package (3.0.5)</strong></p><p>My call to _razorLightEngine.ComplieRenderAsync(..) was throwing the following error:</p><pre>Could not load file or assembly &#39;System.IdentityModel.Tokens.Jwt, Version=5.6.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35&#39;</pre><p>This issue is documented <a href="https://github.com/Azure/azure-functions-host/issues/5756">here</a>.</p><p>The workaround is to downgrade Microsoft.NET.Sdk.Functions to 3.0.3.</p><p><strong>Project settings to support RazorLight rendering</strong></p><p>There are a couple of settings you’ll probably have to set in your Azure Functions project file to enable the RazorLight rendering. I had to set PreserveCompilationReferences and PreserveCompilationContext both to true:</p><pre>&lt;PropertyGroup&gt;<br>  &lt;TargetFramework&gt;netcoreapp3.0&lt;/TargetFramework&gt;<br>  &lt;AzureFunctionsVersion&gt;v2&lt;/AzureFunctionsVersion&gt;<br>  &lt;PreserveCompilationReferences&gt;true&lt;/PreserveCompilationReferences&gt;<br>  &lt;PreserveCompilationContext&gt;true&lt;/PreserveCompilationContext&gt;<br>&lt;/PropertyGroup&gt;</pre><p>The <a href="https://github.com/toddams/RazorLight">RazorLight project page</a> lists these and a couple of other project settings towards the bottom of the page that you may need to set depending on your circumstances.</p><p>The two I mentioned above were the only ones I had to set.</p><p><strong>“Mailgun Magnificent API” response</strong></p><p>It took me a little trial and error to get my Mailgun API calls to succeed and actually send the e-mail. For awhile I was getting a 200 response from the service, but the response body contained the string “Mailgun Magnificent API” and the e-mail wouldn’t send.</p><p>According to a comment on <a href="https://stackoverflow.com/questions/46163664/765-unexpected-token-at-mailgun-magnificent-api-ruby-on-rails-mailgun-rails">this Stack Overflow question</a>, “‘Mailgun Magnificent API’ is Mailgun’s way of saying ‘Your sender domain and auth are all good, but I can’t figure out what API you’re asking for.”</p><p>If you get this, I’d suggest inspecting the way I set my _httpClient.BaseAddress and how I build the URL for the PostAsync(..) call. If you have a / in the wrong place, you&#39;ll get this response.</p><p>Today we’ve seen why using Razor templates coupled with Azure Functions is a good approach to sending transactional e-mails from your application. We’ve also seen how to implement this approach.</p><p>I hope it helps you if you’re considering going down the same path.</p><p>- Jon</p><p><em>I’m a developer and solo SaaS founder who likes to build things and share what I learn with others. If you’re interested software development, launching things, or random early morning thoughts, consider </em><a href="https://twitter.com/Jon_Blankenship"><em>following me</em></a><em> on Twitter.</em> <em>Thanks for reading!</em></p><p><em>Originally published at </em><a href="https://blog.jonblankenship.com/2020/04/05/razor-powered-e-mail-in-azure-functions/"><em>https://blog.jonblankenship.com</em></a><em> on April 5, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9a395995ff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Differentiating Yourself from the Competition]]></title>
            <link>https://medium.com/@jonblankenship/differentiating-yourself-from-the-competition-c188ac35bc2?source=rss-b96d4d34a540------2</link>
            <guid isPermaLink="false">https://medium.com/p/c188ac35bc2</guid>
            <category><![CDATA[side-project]]></category>
            <category><![CDATA[competition]]></category>
            <category><![CDATA[saas]]></category>
            <category><![CDATA[mvp]]></category>
            <category><![CDATA[launch]]></category>
            <dc:creator><![CDATA[Jon Blankenship]]></dc:creator>
            <pubDate>Sun, 22 Mar 2020 21:15:00 GMT</pubDate>
            <atom:updated>2020-03-23T13:44:13.379Z</atom:updated>
            <content:encoded><![CDATA[<p>I was recently asked this question about <a href="https://excepticon.io/">Excepticon</a> in an online forum:</p><blockquote><em>Okay, so the idea is valid, but WHAT makes you different than your competition? If money was not an issue, why would I pick you over something like New Relic?</em></blockquote><p>It’s an important question, not only for me specifically, but for anyone launching a product into a market with even one competitor: <strong>What differentiates your product from your competitors?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CaMh284NZG826r8L.jpg" /></figure><p>I’ve <a href="https://blog.jonblankenship.com/2020/03/05/excepticon-exception-monitoring-for-dot-net/">mentioned before</a> that one of my reasons for building Excepticon is to test the hypothesis that your idea doesn’t have to be unique, that it’s ok (perhaps even advantageous in some regards) to launch into a market with competitors. But to do so and be successful, you need to differentiate your product from the alternatives.</p><p>Going up against an incumbent player in a niche <em>without</em> differentiation is a losing proposition. Even if the products are identical feature-for-feature, an established competitor have several big advantages over a newcomer:</p><ul><li>An existing user base</li><li>Brand recognition/reputation</li><li>Proven ability to execute</li><li>Market share</li><li>Established channels</li></ul><p>Unless there is something different about your product that makes it preferable in the eyes of at a least a segment of the market, you’ll fail to gain any traction.</p><p>Differentiation is key, and it’s important to have a strategy for how you’ll differentiate yourself early on in the process of building your SaaS.</p><h3>How Is Excepticon Different?</h3><p>I am differentiating Excepticon in four main areas:</p><p><strong>Target Niche</strong></p><p>I cater to solo .NET devs and small teams. The forum question I received mentions New Relic — products like New Relic are great, but they’re geared toward the enterprise, or at least that’s what it feels like looking at their landing page and marketing material. They offer a bunch of different solutions, dashboards, reports, and integrations in their platform that I just don’t need or care about as a solo founder/dev. Just give me a simple service that does its one or two things that I need well and at a fair price and I’ll buy it.</p><p><strong>Features</strong></p><p>There are certain features that I want in a solution that aren’t in the existing services that I’ve evaluated. I won’t get into specific features here — I’ll be developing them over the coming months. But I recognize that I can’t compete on features out of the gate, because in the spirit of building an MVP, I launched as soon as I had the core feature set that I felt was needed to launch and still provide value. As the product develops over the coming months, I’ll be adding features that will help to differentiate Excepticon from other services. It’s not there yet.</p><p><strong>Branding/Personality</strong></p><p>The brand or personality of the company plays a part in consumers’ buying decisions. My personality (for better or worse) will be a part of Excepticon — it won’t be a faceless product. I plan to be fairly public about what I’m doing as I build it, market it, and succeed or fail with it. I’ll be part of the product. My message may resonate with some folks who want to support indie software and transparent makers, and it may turn some people off. And that’s ok.</p><p><strong>Price</strong></p><p>The question I received on the forum had the caveat “if money was not an issue,” but the fact of the matter is that money plays a big part in consumer’s minds when choosing a service, especially if they’re in the niche that I’m targeting. So I won’t ignore it — price is a differentiator, and I will be one of the lower-priced options, accessible to my target market.</p><p>Out of the gate I can differentiate myself in the first, third, and fourth areas. It will take a bit of time before I can differentiate on features.</p><h3>How Are You Different?</h3><p>These certainly aren’t the only ways that one can differentiate their product from the rest. Perhaps your strategy for your product includes differentiating in areas that I’ve not mentioned, like offering customer service that goes above and beyond or leveraging unique marketing and distribution channels, for example.</p><p>Whatever the case may be, identify the ways in which your SaaS will be different than your competition and use that to your advantage.</p><p>I should point out that while your competition has several advantages by being an established player in the market, there are benefits to being a small and nimble newcomer, such as:</p><ul><li>Ability to experiment and pivot more easily</li><li>Lower overhead/expenses</li><li>Ability to ship faster</li><li>Ability to do things that don’t scale</li></ul><p>Use these to your advantage.</p><p>As you try to gain a foothold in your market, remember what makes you and your product different from your competitors and push hard on those levers!</p><p>- Jon</p><p><em>(I’m a developer and solo SaaS founder who likes to build things and share what I learn with others. If you’re interested software development, launching things, or random early morning thoughts, consider </em><a href="https://twitter.com/Jon_Blankenship"><em>following me</em></a><em> on Twitter. Thanks for reading!)</em></p><p><em>Originally published at </em><a href="https://blog.jonblankenship.com/2020/03/22/differentiating-yourself-from-the-competition/"><em>https://blog.jonblankenship.com</em></a><em> on March 22, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c188ac35bc2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Excepticon: Exception Monitoring for .NET]]></title>
            <link>https://medium.com/@jonblankenship/excepticon-exception-monitoring-for-net-c75a0c2d1c5c?source=rss-b96d4d34a540------2</link>
            <guid isPermaLink="false">https://medium.com/p/c75a0c2d1c5c</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[mvp]]></category>
            <category><![CDATA[exception-handling]]></category>
            <category><![CDATA[saas]]></category>
            <category><![CDATA[launch]]></category>
            <dc:creator><![CDATA[Jon Blankenship]]></dc:creator>
            <pubDate>Thu, 05 Mar 2020 12:15:00 GMT</pubDate>
            <atom:updated>2020-03-09T11:49:38.031Z</atom:updated>
            <content:encoded><![CDATA[<h3>Excepticon: Exception Monitoring for .NET</h3><p>Today I’m pleased to announce the launch of <a href="https://excepticon.io/">Excepticon</a>, an exception monitoring SaaS for .NET applications and services. Excepticon is easy to configure and simple to use, and it’s geared specifically towards .NET developers.</p><figure><img alt="Excepticon Landing Page" src="https://cdn-images-1.medium.com/max/1024/0*KxDzApV14EYvT87s.PNG" /></figure><p>If you’re a .NET developer and you’re in the market for an exception monitoring service for your application or service, I invite you to try out either the free <a href="https://excepticon.io/plans">Developer plan</a> or a 15-day trial on one of the paid <a href="https://excepticon.io/plans">plans</a>. I’d love to get your feedback on how I could improve it to meet your needs.</p><p>The application is very much an MVP at this stage — it performs its core function and it does it well, but there’s more to come. I’ll be building it out, improving the UI/UX, and adding features in the coming months.</p><p>Here’s a peek at an exception in Excepticon:</p><figure><img alt="Excepticon Exception Instance" src="https://cdn-images-1.medium.com/max/1024/0*tYfsnbuACwDI_XXo.PNG" /></figure><p>So how did Excepticon come to be?</p><h3>Inception</h3><p>On more than one of my past side-projects over the last couple of years I’d had the thought, “When I launch this, I’m going to need an easy way to stay on top of any exceptions that my app is throwing. I should build an exception monitoring service.”</p><p>Typical developer, right?</p><p>It seemed like a fun little project that I could build in a relatively short amount of time to meet my needs. There’s some interesting aspects to it. I understood the domain. I knew what features I’d want. Maybe others would want to use it too.</p><p>Why not?</p><p>Why not.</p><p>Well, for one, there’s already other well-established, full-featured exception monitoring services out there.</p><p>Oh well.</p><p>Idea dismissed. Back to whatever I was working on before the thought entered my brain.</p><p>Time passes. Seasons change. Fast-forward several months…</p><p><strong>The Decision to Build</strong></p><p>Last fall, I listened to a podcast where the guest was a founder of a bootstrapped business that had launched into a market where there was existing competition. He and his cofounders were enjoying success despite incumbents in their niche because they were executing on their vision of the product, offering a different version of what was already out there, and making themselves a part of their product. He encouraged the listener to not view existing competition as a barrier to success.</p><p>I’d heard similar advice before from guests of the <a href="https://www.indiehackers.com/podcast">Indie Hackers podcast</a>:</p><blockquote><em>Your idea doesn’t have to be original. Existing competition validates that there’s a market for your product. The internet’s a big place.</em></blockquote><p>The idea for what would become Excepticon resurfaced as I listened to the episode, but this time I was thinking about it in a new light.</p><p>“Maybe the market is big enough for a new service in this space. There are things about the current products that I would do differently, features that are missing. There are ways that I can differentiate myself from the competition.”</p><p>As I considered these things, I grew more excited about the project. This would be a fun thing to build. I’d build something that I’ll use, and I’d test the notion that it’s ok to build an app that solves an already solved problem.</p><p>Unlike the prior times I’d considered the idea, this time I committed to building it and got to work.</p><figure><img alt="Excepticon Exception List on Mobile" src="https://cdn-images-1.medium.com/max/550/0*Wvvr7AtTBtCAJuGZ.png" /></figure><h3>Objectives</h3><p>I have a few objectives for Excepticon, some of which I’ve already mentioned, and several of which I plan to elaborate on in future posts. Here they are, in no particular order:</p><h4>1. Test the theory, “Your idea doesn’t have to be unique.”</h4><p>Many folks wanting to build an app or start a business spend a lot of time trying to come up with a completely original idea, which is hard when you consider that many of the problems worth solving have already been solved.</p><p>However there’s quite a bit of anecdotal evidence suggesting that success can be found in executing on an idea for which there’s already a solution by building a better product, targeting a slightly different niche, or differentiating yourself somehow. Many companies that are thriving in, and in some cases even dominating, their respective industries today were not the first to market. This is true for most of the top names in tech today, including Google, Apple, and Facebook, as well as hundreds of lesser-known companies operating very successfully on a smaller scale.</p><p>Existing competition needn’t be feared. The fact that other companies exist and people are paying them money to solve the same pain point validates the idea as well as the market. There are billions of people on the internet; if your niche is large enough, you execute well, and you differentiate your product in some way, there’s usually room for another competitor.</p><p>Or, at least, so goes the prevailing wisdom.</p><p>One of my objectives for Excepticon is to test first-hand this notion that “your idea doesn’t have to be unique.”</p><h4>2. Build the features that I want</h4><p>There are several good exception monitoring services out there, but none of them tick all of the boxes of features that I’m looking for in a solution. Excepticon doesn’t either in its current MVP state, but it will. I’ll be prioritizing the features that matter to me as I plan out the post-MVP roadmap along with suggested features and changes that I receive from my users.</p><h4>3. Build for the .NET developer, not the enterprise</h4><p>Of the other exception monitoring services on the market, some of them target applications written in non-.NET languages and either don’t support .NET or .NET support is an afterthought, relying on the community to maintain a third-party Nuget package to integrate with their service.</p><p>Of the ones that do target .NET, many are part of a larger suite of enterprise tools that are marketed to C-level executives with buzzwords like “synergies,” “AI,” and “business intelligence.”</p><p>I’m building Excepticon for the .NET developer working independently or as part of a small team who needs a service to simply monitor their apps and services and to do it well.</p><h4>4. Eat my own dog food</h4><p>One of the best ways to understand how to improve your product is to be a user of your product. With Excepticon I’m eating my own dog food. Excepticon is using the same packages available to my end-users, and I’m monitoring for exceptions thrown by the Excepticon web app and API, which is already helping me to identify and fix pain points and things that can be improved.</p><p>Not only am I using Excepticon to monitor Excepticon, but I plan to use it on future projects as well.</p><h4>5. Have fun</h4><p>A side project should be something you enjoy working on. Anything that consumes as much free time as building a SaaS does should bring some personal fulfillment, especially in the early days when it’s not making any money. Further, if your heart’s not in it, you won’t stick to it and see it to completion.</p><p>I’m having fun building Excepticon. I’m excited about the features that are on the roadmap and the things that I will learn along the way.</p><p>I invite you to check out out <a href="https://excepticon.io/">Excepticon</a> today!</p><p>- Jon</p><p><em>Originally published at </em><a href="https://blog.jonblankenship.com/2020/03/05/excepticon-exception-monitoring-for-dot-net/"><em>https://blog.jonblankenship.com</em></a><em> on March 5, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c75a0c2d1c5c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using the Specification Pattern to Build a Data-Driven Rules Engine]]></title>
            <link>https://medium.com/@jonblankenship/using-the-specification-pattern-to-build-a-data-driven-rules-engine-b3db95189ff8?source=rss-b96d4d34a540------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3db95189ff8</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[domain-driven-design]]></category>
            <dc:creator><![CDATA[Jon Blankenship]]></dc:creator>
            <pubDate>Sat, 05 Oct 2019 02:34:00 GMT</pubDate>
            <atom:updated>2020-03-09T12:12:48.235Z</atom:updated>
            <content:encoded><![CDATA[<p>In my <a href="https://blog.jonblankenship.com/tag/stock-alerts/">Stock Alerts</a> project, the user configures criteria for a given stock that should be evaluated continuously and trigger a notification to the user when the criteria are satisfied.</p><p>Rather than simply setting a single price trigger, I want the user to be able to specify multiple types of criteria and combine them using Boolean logic to form a complex rule.</p><p>For example, a dividend growth investor might want to be notified when JNJ meets the following criteria:</p><ul><li>Dividend &gt; 2.5% <strong>AND</strong></li><li>Payout Ratio &lt; 50% <strong>AND</strong></li><li>(PE Ratio &lt; 20 <strong>OR</strong> Price &lt; 130)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/0*GwiH2pud-zPCbmg9.PNG" /></figure><p>Another investor might want a completely different set of criteria to alert them when their momentum stock darling is about to take off out of a range.</p><p>So how do we accomplish this in a clean, configurable, and testable manner?</p><h3>Enter the Specification Pattern</h3><p>The specification pattern has been a valuable tool in my toolbox in the past, and it is the perfect tool for the job ahead of us today: building a data-driven rules engine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/189/0*OjrrstFAMCzX5oZs.jpg" /></figure><p>The pattern was introduced by Eric Evans, author of <a href="https://amzn.to/2mqUJXv">Domain-Driven Design: Tackling Complexity in the Heart of Software</a> and father of the domain-driven design (DDD) approach to software development. Evans and <a href="https://www.martinfowler.com/">Martin Fowler</a> co-wrote a <a href="https://www.martinfowler.com/apsupp/spec.pdf">white paper</a> on specifications that is well worth the read addressing the uses of specification, types of specifications, and consequences of specification.</p><p>The <a href="https://en.wikipedia.org/wiki/Specification_pattern">Wikipedia article</a> on the specification pattern gives us a pretty good definition (as well as some sample C# code) to start with:</p><blockquote><em>In computer programming, the </em><strong><em>specification pattern</em></strong><em> is a particular </em><a href="https://en.wikipedia.org/wiki/Software_design_pattern"><em>software design pattern</em></a><em>, whereby </em><a href="https://en.wikipedia.org/wiki/Business_rules"><em>business rules</em></a><em> can be recombined by chaining the business rules together using boolean logic.</em></blockquote><p><a href="https://www.martinfowler.com/apsupp/spec.pdf">Evans and Fowler</a> identify the core problems to which the specification pattern is applicable:</p><blockquote>Selection: You need to select a subset of objects based on some criteria, and to refresh the selection at various times</blockquote><blockquote>Validation: You need to check that only suitable objects are used for a certain purpose</blockquote><blockquote>Construction-to-order: You need to describe what an object might do, without explaining the details of how the object does it, but in such a way that a candidate might be built to fulfill the requirement.</blockquote><p>The solution to each of these problems is to build a specification that defines the criteria that an object must meet to satisfy the specification. Typically, a specification has a method IsSatisfied(candidate) that takes the candidate object as a parameter. The method returns true or false, depending on whether the candidate satisfies the criteria of the specification.</p><p>In this post, we’ll focus on a particular type of specification, a <strong>composite specification</strong>, to build our rules engine. This type of specification gets its name from the fact that it is an implementation of another commonly used design pattern: the composite pattern.</p><h3>The Composite Pattern</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/199/0*4B-e633R5WXwxneZ.jpg" /></figure><p>The composite pattern is one of the twenty-three software design patterns introduced in the Gang of Four’s (GoF) seminal work, <a href="https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&amp;tag=jon100-20&amp;camp=1789&amp;creative=9325&amp;linkCode=as2&amp;creativeASIN=0201633612&amp;linkId=ce0a3b2651f5de39016ad1aa1f003b80">Design Patterns: Elements of Reusable Object-Oriented Software</a>. The authors classify the patterns into one of three categories: creational, structural and behavioral. The composite pattern is a structural pattern, meaning it is a pattern that describes how entities relate to each other with the goal of simplifying the structure of a system.</p><p>The composite pattern describes a group of entities that can be combined into a tree-like structure, where the individual parts have the same interface as the structure as a whole, allowing clients to interact with the parts and the whole uniformly. This is where the advantage of the composite pattern lies. By treating the composite and its components uniformly, clients avoid having to discriminate between a leaf node and a branch, reducing complexity and the potential for error.</p><p>Further, by structuring a component as a composite of primitive objects that are recombinable, we get the benefits of code reuse as we are able to leverage existing components to build other composites. We’ll see this in practice as we get into the code for our rules engine.</p><h3>Specification Building Blocks</h3><p>So let’s move from the abstract to the concrete and see some code. Before we start to think about domain-specific rules that we need to implement, we’ll need a few building blocks first.</p><h3>ISpecification</h3><p>First, we need an interface for interacting with the composite specification as a whole, as well as its individual component specifications. So here’s our ISpecification interface:</p><pre>public interface ISpecification&lt;in TCandidate&gt;<br>{<br>    bool IsSatisfiedBy(TCandidate candidate);<br>}</pre><p>It’s a very simple interface consisting of one method, IsSatisfiedBy(TCandidate candidate), which returns true or false depending on whether the given specification is satisfied by the candidate passed to it.</p><p>The type parameter TCandidate specifies the type of object that the specification will be used to evaluate. In the case of a composite specification, the type of candidate object passed to the root node will be passed to the child nodes, so the type is expected to be the same for all individual specifications that make up a composite specification.</p><h3>CompositeSpecification</h3><p>Next, we have an abstract class CompositeSpecification, which will be the base class for any branch (non-leaf) nodes in our composite specification:</p><pre>public abstract class CompositeSpecification&lt;TCandidate&gt; : ISpecification&lt;TCandidate&gt;<br>{<br>    protected readonly List&lt;ISpecification&lt;TCandidate&gt;&gt; _childSpecifications = new List&lt;ISpecification&lt;TCandidate&gt;&gt;();<br><br>    public void AddChildSpecification(ISpecification&lt;TCandidate&gt; childSpecification)<br>    {<br>        _childSpecifications.Add(childSpecification);<br>    }<br><br>    public abstract bool IsSatisfiedBy(TCandidate candidate);<br><br>    public IReadOnlyCollection&lt;ISpecification&lt;TCandidate&gt;&gt; Children =&gt; _childSpecifications.AsReadOnly();<br>}</pre><p>The main behavior that CompositeSpecification implements here is the management of a node&#39;s child specifications. It handles the addition of a child specification to the composite specification, and it exposes the child specifications as a read-only collection that can be traversed.</p><h3>Boolean Specifications</h3><p>The branches (non-leaf nodes) are specifications that represent Boolean operations that connect 1..n other specifications, and they derive from CompositeSpecification. For our initial implementation, we have <strong>AND</strong> and <strong>OR</strong> specifications (short-circuited).</p><p><strong>AndSpecification</strong>:</p><pre>public class AndSpecification&lt;TCandidate&gt; : CompositeSpecification&lt;TCandidate&gt;<br>{<br>    public override bool IsSatisfiedBy(TCandidate candidate)<br>    {<br>        if (!_childSpecifications.Any()) return false;<br><br>        foreach (var s in _childSpecifications)<br>        {<br>            if (!s.IsSatisfiedBy(candidate)) return false;<br>        }<br><br>        return true;<br>    }<br>}</pre><p><strong>OrSpecification</strong>:</p><pre>public class OrSpecification&lt;TCandidate&gt; : CompositeSpecification&lt;TCandidate&gt;<br>{<br>    public override bool IsSatisfiedBy(TCandidate candidate)<br>    {<br>        if (!_childSpecifications.Any()) return false;<br><br>        foreach (var s in _childSpecifications)<br>        {<br>            if (s.IsSatisfiedBy(candidate)) return true;<br>        }<br><br>        return false;<br>    }<br>}</pre><p>Of course, other Boolean operators, such as <strong>NOT</strong> and <strong>XOR</strong>, could be implemented without too much difficulty, but these are the only two that I’ve needed so far for my application, and they are sufficient for demonstrating the pattern.</p><h4>Unit Testing the Boolean Specifications</h4><p>Before we move on to the domain-specification specifications, let’s talk briefly about unit testing. One of the attractive characteristics of the specification pattern is the ease with which specifications can be unit-tested due to the clear boundaries around small, individual chunks of logic.</p><p>To assist with unit-testing, I’ve implemented very simple <strong>True</strong> and <strong>False</strong> specifications:</p><pre>public class TrueSpecification&lt;TCandidate&gt; : ISpecification&lt;TCandidate&gt;<br>{<br>    public bool IsSatisfiedBy(TCandidate candidate) =&gt; true;<br>}<br><br>public class FalseSpecification&lt;TCandidate&gt; : ISpecification&lt;TCandidate&gt;<br>{<br>    public bool IsSatisfiedBy(TCandidate candidate) =&gt; false;<br>}</pre><p>These one-line specifications aren’t useful in application code, but they come in handy when unit-testing the branch (non-leaf) node specifications. Here’s one of the unit tests for the AndSpecification, utilizing the TrueSpecification:</p><pre>[Fact]<br>public void IsSatisfiedBy_TwoTrueChildren_True()<br>{<br>    // Arrange<br>    var spec = new AndSpecification&lt;AlertEvaluationMessage&gt;();<br>    spec.AddChildSpecification(new TrueSpecification&lt;AlertEvaluationMessage&gt;());<br>    spec.AddChildSpecification(new TrueSpecification&lt;AlertEvaluationMessage&gt;());<br>    var message = new AlertEvaluationMessage();<br><br>    // Act<br>    var result = spec.IsSatisfiedBy(message);<br><br>    // Assert<br>    result.Should().BeTrue();<br>}</pre><p>TrueSpecification and FalseSpecification facilitate the writing of straight-forward unit tests like the one above that zero in on the unit under test ( AndSpecification.IsSatisfiedBy(..) in this case). (You may be wondering about AlertEvaluationMessage - it is the type of the candidate object that we are evaluating, which we&#39;ll examine in a bit.)</p><h3>Domain-Specific Specifications</h3><p>Now that we have the building blocks needed to build <em>any</em> specification, we’re ready to look at the things we’ll need to build specifications specific to our domain: stock alerts. As we transition from discussing the Boolean specifications to talking about domain-specific specifications, our focus is moving from the branch (non-leaf) nodes of the composite specification to the leaf nodes.</p><h3>PriceSpecification</h3><p>One of the main criteria that our specification will have to test for is, when given a new price quote, whether the new price exceeds a certain level. For this, we’ll create a PriceSpecification that is aware of an alert criteria specifying an important price level, and it will return true or false depending on whether a new stock quote breaches that level:</p><pre>public class PriceSpecification : ISpecification&lt;AlertEvaluationMessage&gt;<br>{<br>    private readonly AlertCriteria _alertCriteria;<br><br>    public PriceSpecification(AlertCriteria alertCriteria)<br>    {<br>        _alertCriteria = alertCriteria ?? throw new ArgumentNullException(nameof(alertCriteria));<br>    }<br><br>    public bool IsSatisfiedBy(AlertEvaluationMessage candidate)<br>    {<br>        if (_alertCriteria.Operator == CriteriaOperator.GreaterThan)<br>        {<br>            return candidate.LastPrice &gt; _alertCriteria.Level &amp;&amp;<br>                candidate.PreviousLastPrice &lt;= _alertCriteria.Level;<br>        }<br><br>        if (_alertCriteria.Operator == CriteriaOperator.GreaterThanOrEqualTo)<br>        {<br>            return candidate.LastPrice &gt;= _alertCriteria.Level &amp;&amp;<br>                   candidate.PreviousLastPrice &lt; _alertCriteria.Level;<br>        }<br><br>        if (_alertCriteria.Operator == CriteriaOperator.Equals)<br>        {<br>            return candidate.LastPrice == _alertCriteria.Level &amp;&amp;<br>                   candidate.PreviousLastPrice != _alertCriteria.Level;<br>        }<br><br>        if (_alertCriteria.Operator == CriteriaOperator.LessThanOrEqualTo)<br>        {<br>            return candidate.LastPrice &lt;= _alertCriteria.Level &amp;&amp;<br>                   candidate.PreviousLastPrice &gt; _alertCriteria.Level;<br>        }<br><br>        if (_alertCriteria.Operator == CriteriaOperator.LessThan)<br>        {<br>            return candidate.LastPrice &lt; _alertCriteria.Level &amp;&amp;<br>                   candidate.PreviousLastPrice &gt;= _alertCriteria.Level;<br>        }<br><br>        return false;<br>    }<br>}</pre><h4>AlertCriteria</h4><p>This specification has a domain model passed to it at the time it is constructed: AlertCriteria. We&#39;ll look at just the few properties of AlertCriteria that are relevant to this particular specification for now:</p><pre>public class AlertCriteria<br>{<br>    // snip<br><br>    public CriteriaType Type { get; set; }<br><br>    public CriteriaOperator Operator { get; set; }<br><br>    public decimal? Level { get; set; }<br><br>    // snip<br>}</pre><p>Type specifies the alert <a href="https://github.com/jonblankenship/stock-alerts/blob/master/StockAlerts/StockAlerts.Core/Enums/CriteriaType.cs">CriteriaType</a> that we&#39;re evaluating. Possible values are Composite, Price, DailyPercentageGainLoss, and there will likely be more. Operator specifies the <a href="https://github.com/jonblankenship/stock-alerts/blob/master/StockAlerts/StockAlerts.Core/Enums/CriteriaOperator.cs">CriteriaOperator</a> that applies for the particular scenario we&#39;re evaluating. Finally, if we need to trigger a price alert, we need to know at which level it should be triggered, which is what is specified by the Level property. With these three pieces of data, we have what we need to know to create a specification that represents a price alert for a given stock&#39;s price becomes greater than or equal to $150, for example.</p><p>The AlertCriteria domain object will ultimately come from the database, and is a key part of the data model that will make this a data-driven rules engine. We&#39;ll look at it more closely in bit.</p><h4>AlertEvaluationMessage</h4><p>The next piece needed for our PriceSpecification is AlertEvaluationMessage, which is the type of candidate object that our specification is designed to evaluate. In our example, AlertEvaluationMessage represents a new price quote (named Message since in this particular case it&#39;s being pulled off of a message queue).</p><pre>public class AlertEvaluationMessage<br>{<br>    public Guid AlertDefinitionId { get; set; }<br><br>    public decimal LastPrice { get; set; }<br><br>    public decimal PreviousLastPrice { get; set; }<br><br>    public decimal OpenPrice { get; set; }<br>}</pre><p>The relevant properties here for our PriceSpecification are LastPrice and PreviousLastPrice, so that we can determine whether a price has crossed a certain price level.</p><h4>IsSatisfiedBy(AlertEvaluationMessage candidate)</h4><p>Now that we have the required information, we can evaluate whether the PriceSpecification for our particular AlertCriteria is satisfied by the candidate AlertEvaluationMessage object. IsSatisfiedBy(AlertEvaluationMessage candidate) is a fairly simple set of if statements that perform comparisons between _alertCriteria.Level and candidate.LastPrice and candidate.PreviousLastPrice depending on _alertCriteria.Operator and returns true or false to indicate whether the price level has been breached.</p><h3>Other Domain-Specific Specifications</h3><p>I’ve also implemented a <a href="https://github.com/jonblankenship/stock-alerts/blob/master/StockAlerts/StockAlerts.Domain/Specifications/DailyPercentageGainLossSpecification.cs">DailyPercentageGainLossSpecification</a>, which returns true or false depending on whether the stock price has exceeded a given percentage gain or loss for the day. Its logic is very similar to the PriceSpecification that we just discussed.</p><p>Other types of specifications that I plan to implement in the future are things like DividendYieldSpecification, which would return true when a stock&#39;s dividend yield breaches a certain percentage, or PeRatioSpecification, which would return true when a stock&#39;s PE ratio breaches a certain level.</p><p>The sky is the limit in terms of what kinds of specifications we can implement and combine into a composite specification. The specifications that we build are generic in the sense that the specific parameters (price level, operator, etc…) are provided at runtime, so that our PriceSpecification, for example, can be re-used in any composite specification that needs to test for a price level breach as part of its logic.</p><p>Hopefully by now it’s becoming a bit clearer how the specification pattern can be used to construct a complex rule like described at the beginning of this post.</p><h3>Constructing the Composite Specification</h3><p>Now that we have the pieces needed to represent and evaluate a set of criteria, let’s revisit our use case. Users need to be able to specify their alert criteria at runtime, and the system needs to store these criteria so that it can retrieve them and construct the composite specification and evaluate it on demand when a new stock quote is received.</p><h3>Data Model</h3><p>The data model to support this use case consists of two tables:</p><p><strong>AlertDefinitions</strong></p><ul><li>Contains a record for each user-defined alert.</li><li>Represents the overall composite specification for an alert for a user for a given stock.</li></ul><p><strong>AlertCriteria</strong></p><ul><li>Contains a record for each individual criteria that make up an AlertDefinition.</li><li>Represents an individual specification.</li><li>One-to-many relationship back to AlertDefinitions.</li><li>Zero-to-many relationship back to itself.</li><li>Because AlertCriteria is a self-referencing table, it can be used to represent any number of nodes in a complex composite specification.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/0*4Fd2__OJ5Gx07UHu.PNG" /></figure><h3>Domain Model</h3><p>Moving up to the domain model, we have <a href="https://github.com/jonblankenship/stock-alerts/blob/master/StockAlerts/StockAlerts.Domain/Model/AlertDefinition.cs">AlertDefinition</a> and <a href="https://github.com/jonblankenship/stock-alerts/blob/master/StockAlerts/StockAlerts.Domain/Model/AlertCriteria.cs">AlertCriteria</a> models that are mapped from and correspond with the two tables in the underlying data model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/0*npnrn3T-BHQy_TJh.PNG" /></figure><p>These domain models make up an aggregate, and AlertDefinition is the aggregate root. The persistance of the aggregate is controlled via the SaveAsync and DeleteAsync methods on AlertDefinition.</p><p>The domain models contain logic for validating the proper configuration of the composite specification, which is checked at the time the AlertDefinition is saved. For example...</p><ul><li>A composite AlertCriteria can only have certain operators (AND, OR, other Boolean operators).</li><li>A composite AlertCriteria must have at least one child AlertCriteria.</li><li>A non-composite AlertCriteria cannot have any children.</li><li>Etc…</li></ul><p>The construction and evaluation of the composite specification is triggered in AlertDefinition.EvaluateAsync(AlertEvaluationMessage message):</p><pre>public async Task EvaluateAsync(AlertEvaluationMessage message)<br>{<br>    if (Status == AlertDefinitionStatuses.Enabled)<br>    {<br>        if (!LastSent.HasValue || DateTimeOffset.UtcNow.Date &gt; LastSent.Value.Date) // Alert not already sent today<br>        {<br>            var specification = _alertCriteriaSpecificationFactory.CreateSpecification(this);<br>            if (specification.IsSatisfiedBy(message))<br>            {<br>                var subject = $&quot;Stock Alert Triggered: {Stock.Symbol}&quot;;<br>                var notificationMessage = $&quot;Stock Alert Triggered {Environment.NewLine}&quot; +<br>                                          $&quot;Notification Name: {Name}{Environment.NewLine}&quot; +<br>                                          $&quot;Stock: {Stock.Symbol} ({message.LastPrice:C}){Environment.NewLine}&quot; +<br>                                          $&quot;Criteria: {RootCriteria}{Environment.NewLine}&quot;;<br><br>                await TriggerAlertAsync(subject, notificationMessage);<br>            }<br>        }<br>    }<br>}</pre><p>This is the culmination of all that we’ve been building. We’ve now got our composite specification (created by the _alertCriteriaSpecificationFactory, which we will visit in a moment) representing the user-defined alert definition, and we evaluate the entire set of rules with our call to specification.IsSatisfiedBy(message), which simply returns true or false.</p><p>It may seem rather anti-climactic on the surface, but there is a lot of power within the specification and the beauty of the pattern lies in the simplicity of its interface. The client simply asks the specification, “Does this object satisfy your criteria?”</p><h3>Factory</h3><p>The AlertCriteriaSpecificationFactory is the final piece of the puzzle that we&#39;ll look at. It is responsible for the actual construction of the composite specification and its children from the AlertDefinition. It is an example of the <a href="https://en.wikipedia.org/wiki/Factory_method_pattern">factory pattern</a>, a creational design pattern coined by the Gang of Four.</p><p>The AlertCriteriaSpecificationFactory will create any ISpecification&lt;AlertEvaluationMessage&gt; for a given AlertDefinition:</p><pre>public interface IAlertCriteriaSpecificationFactory<br>{<br>    ISpecification&lt;AlertEvaluationMessage&gt; CreateSpecification(AlertDefinition alertDefinition);<br>}</pre><p>Though we only publicly expose a single method in the interface for building an ISpecification from an AlertDefinition, in the implementation of the factory we see that it is also responsible for building the ISpecifications that make up the composite from individual AlertCriteria objects. The factory contains private methods for constructing each type of specification, and it recursively traverses the tree of alert criteria building the various individual specifications to construct the full composite specification for the AlertDefinition:</p><pre>public class AlertCriteriaSpecificationFactory : IAlertCriteriaSpecificationFactory<br>{<br>    private readonly IDictionary&lt;CriteriaType, Func&lt;AlertCriteria, ISpecification&lt;AlertEvaluationMessage&gt;&gt;&gt; _factoryMethods;<br><br>    public AlertCriteriaSpecificationFactory()<br>    {<br>        _factoryMethods = new Dictionary&lt;CriteriaType, Func&lt;AlertCriteria, ISpecification&lt;AlertEvaluationMessage&gt;&gt;&gt;<br>        {<br>            { CriteriaType.Composite, CreateCompositeSpecification },<br>            { CriteriaType.Price, CreatePriceSpecification },<br>            { CriteriaType.DailyPercentageGainLoss, CreateDailyPercentageGainLossSpecification }<br>        };<br>    }<br><br>    public ISpecification&lt;AlertEvaluationMessage&gt; CreateSpecification(AlertDefinition alertDefinition)<br>    {<br>        return CreateSpecification(alertDefinition.RootCriteria);<br>    }<br><br>    public ISpecification&lt;AlertEvaluationMessage&gt; CreateSpecification(AlertCriteria alertCriteria)<br>    {<br>        var factoryMethod = _factoryMethods[alertCriteria.Type];<br>        return factoryMethod.Invoke(alertCriteria);<br>    }<br><br>    private ISpecification&lt;AlertEvaluationMessage&gt; CreateCompositeSpecification(<br>        AlertCriteria alertCriteria)<br>    {<br>        CompositeSpecification&lt;AlertEvaluationMessage&gt; specification;<br>        <br>        if (alertCriteria.Operator == CriteriaOperator.And)<br>            specification = new AndSpecification&lt;AlertEvaluationMessage&gt;();<br>        else if (alertCriteria.Operator == CriteriaOperator.Or)<br>            specification = new OrSpecification&lt;AlertEvaluationMessage&gt;();<br>        else<br>            throw new ApplicationException(&quot;Operator not supported.&quot;);<br><br>        foreach (var c in alertCriteria.ChildrenCriteria)<br>        {<br>            specification.AddChildSpecification(CreateSpecification(c));<br>        }<br><br>        return specification;<br>    }<br><br>    private ISpecification&lt;AlertEvaluationMessage&gt; CreatePriceSpecification(<br>        AlertCriteria alertCriteria) =&gt;<br>        new PriceSpecification(alertCriteria);<br><br>    private ISpecification&lt;AlertEvaluationMessage&gt; CreateDailyPercentageGainLossSpecification(<br>        AlertCriteria alertCriteria) =&gt;<br>        new DailyPercentageGainLossSpecification(alertCriteria);<br>}</pre><h3>Wrapping Up</h3><p>Whew!</p><p>This was a long post, but I hope it has been a helpful introduction to the specification pattern. It’s a powerful pattern for modeling and evaluating complex rules that goes a long way towards minimizing complexity when applied to an appropriate use case.</p><p>A composite specification can be constructed at design-time for cases where the rules are known ahead of time. It simplifies things a bit while still providing all of the benefits of the pattern. Many use cases fall into this category.</p><p>On the other hand, if the rules aren’t known until runtime (as in our case, where the stock alert criteria are user-defined), the composite specification can be created from a representation of the rules stored as records in a database, resulting in a full-blown data-driven rules engine, as we demonstrated in this post.</p><p>As always, thanks for reading!</p><p>-Jon</p><p><em>Originally published at </em><a href="https://blog.jonblankenship.com/2019/10/04/using-the-specification-pattern-to-build-a-data-driven-rules-engine/"><em>https://blog.jonblankenship.com</em></a><em> on October 5, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3db95189ff8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>