<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>c# &#8211; Cognim &#8211; Internet development</title>
	<atom:link href="https://www.cognim.co.uk/category/c/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.cognim.co.uk</link>
	<description>Enterprise system implementation. Making the complex simple</description>
	<lastBuildDate>Tue, 10 May 2016 15:24:34 +0000</lastBuildDate>
	<language>en-GB</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	
<site xmlns="com-wordpress:feed-additions:1">91553907</site>	<item>
		<title>An introduction to U-SQL &#8211; SQL and C# combined!</title>
		<link>https://www.cognim.co.uk/introduction-u-sql-sql-c-combined/</link>
					<comments>https://www.cognim.co.uk/introduction-u-sql-sql-c-combined/#respond</comments>
		
		<dc:creator><![CDATA[Darren Hall]]></dc:creator>
		<pubDate>Tue, 10 May 2016 15:24:34 +0000</pubDate>
				<category><![CDATA[c#]]></category>
		<category><![CDATA[U-SQL]]></category>
		<guid isPermaLink="false">http://www.cognim.co.uk/?p=5458</guid>

					<description><![CDATA[I just returned from SQLBits 2016 and had a fantastic time. They really put on a great conference, with brilliant speakers on a variety of SQL topics (and increasingly NoSQL/Big Data). Throw in good catering and an amazing [simple_tooltip content=&#8217;My favourite thing this year was a game of human space invaders, using nerf guns, moderated by Mario for [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>I just returned from <a href="https://sqlbits.com">SQLBits 2016</a> and had a fantastic time. They really put on a great<br />
conference, with brilliant speakers on a variety of SQL topics (and increasingly NoSQL/Big Data). Throw in good catering and an amazing [simple_tooltip content=&#8217;My favourite thing this year was a game of human space invaders, using nerf guns, moderated by Mario for some reason&#8217;]<em>space themed party</em>[/simple_tooltip], all for a very reasonable price and you have a conference I really can&#8217;t recommend enough!</p>
<hr />
<p>The talk that excited me most this year was an introduction to U-SQL by Michael Rys. U-SQL is a new querying/processing language that acts as a composite of SQL and C#, allowing you to call C# code from within SQL-like queries. You can write C# code in-line in queries, or call it from referenced assemblies. Here&#8217;s a sample query from <a href="https://azure.microsoft.com/en-gb/documentation/articles/data-lake-analytics-u-sql-get-started/">https://azure.microsoft.com/en-gb/documentation/articles/data-lake-analytics-u-sql-get-started/</a></p>
<pre class="lang:tsql decode:true ">DROP FUNCTION IF EXISTS Searchlog;

CREATE FUNCTION Searchlog() 
RETURNS @searchlog TABLE
(
            UserId          int,
            Start           DateTime,
            Region          string,
            Query           string,
            Duration        int?,
            Urls            string,
            ClickedUrls     string
)
AS BEGIN 
@searchlog =
    EXTRACT UserId          int,
            Start           DateTime,
            Region          string,
            Query           string,
            Duration        int?,
            Urls            string,
            ClickedUrls     string
    FROM "/Samples/Data/SearchLog.tsv"
USING Extractors.Tsv();
RETURN;
END;</pre>
<p>For the most part it looks like standard T-SQL, but you see that call to &#8220;Extractors.Tsv()&#8221; near the bottom? That&#8217;s C# code. In this case it&#8217;s an inbuilt function for U-SQL, but it could be any C# you wrote or referenced. You can also see some handy inbuilt features that allow it to easily extract data from files (the demo took them from an Azure Blob Storage account).</p>
<p>U-SQL acts as Data Processing As A Service &#8211; you write your U-SQL query, submit it to Azure, then wait for the results. You pay per query, and it handles all infrastructure orchestration. You don&#8217;t need to set up machines &#8211; it also handles parallelization automatically for you!</p>
<p>Microsoft are positioning this as a Big Data solution designed to be used with the new Azure Data Lake features, but I think it has the potential to be used in a wide variety of scenarios.</p>
<p>It&#8217;s very early days, but it&#8217;s something I&#8217;ll be definitely keeping my eye on.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.cognim.co.uk/introduction-u-sql-sql-c-combined/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">5458</post-id>	</item>
		<item>
		<title>Modern Logging with SeriLog and Seq &#8211; part 2. Entry Point Logging</title>
		<link>https://www.cognim.co.uk/modern-logging-with-serilog-and-seq-part-2/</link>
					<comments>https://www.cognim.co.uk/modern-logging-with-serilog-and-seq-part-2/#comments</comments>
		
		<dc:creator><![CDATA[Darren Hall]]></dc:creator>
		<pubDate>Wed, 13 Apr 2016 13:02:26 +0000</pubDate>
				<category><![CDATA[c#]]></category>
		<category><![CDATA[Logging]]></category>
		<guid isPermaLink="false">http://www.cognim.co.uk/?p=5435</guid>

					<description><![CDATA[Entry Point Logging allows you to track all your API calls and the calls they make from a single place In the first part of this series I gave a brief overview of Serilog and Seq and what differentiates them from logging you may have done in the past.  One of the most useful aspects [&#8230;]]]></description>
										<content:encoded><![CDATA[<h3>Entry Point Logging allows you to track all your API calls and the calls they make from a single place</h3>
<p><a href="https://www.cognim.co.uk/modern-logging-serilog/" target="_blank">In the first part of this series I gave a brief overview of Serilog and Seq</a> and what differentiates them from logging you may have done in the past.  One of the most useful aspects of structured logging is the ability to trace the path of any particular call to your site, including key variables along the way. This post will explain how to set that up using Owin and middleware.</p>
<p>A key requirement in entry point logging is standardisation &#8211; all entry point logs should be generated by the same code if they are to be universally searchable (as well as being good SOLID practice!).</p>
<h4>Example</h4>
<p>Here is an example of a static entry point logger we are using, it is very simple code and uses the class SiteAccessDetails (which is added to our ClaimsPrincipal in middleware &#8211; <a href="https://www.cognim.co.uk/transforming-claims-claimsprincipal/">see this blog for details on how to do that</a>) to supply a shopName to be used as additional context.</p>
<pre class="lang:c# decode:true ">public static class EntryPointLogger
{
	public static IDisposable AddEntryPointContext(ILogger logger, SiteAccessDetails siteAccessDetails, string entryPointName)
	{
		var disposable = LogContext.PushProperty("HttpRequestId", Guid.NewGuid());

		if (!string.IsNullOrWhiteSpace(siteAccessDetails?.ShopName))
			LogContext.PushProperty("Shop", siteAccessDetails.ShopName);

		if (!string.IsNullOrWhiteSpace(entryPointName))
			LogContext.PushProperty("entryPointName", entryPointName);

		logger.Information("Entry Point: {entryPointName} called", entryPointName);

		return disposable;
	}

	public static IDisposable AddEntryPointContext(ILogger logger, string shopNameOrUrl, string entryPointName)
	{
		var userSiteDetails = new SiteAccessDetails(shopNameOrUrl, null, null);
		return AddEntryPointContext(logger, userSiteDetails, entryPointName);
	}

	public static IDisposable AddEntryPointContext(ILogger logger, string entryPointName)
	{
		return AddEntryPointContext(logger, (SiteAccessDetails)null, entryPointName);
	}
}</pre>
<p>We can call this manually from entry points in our code (Web API controllers etc) by adding a line like the following</p>
<pre class="lang:c# decode:true">var disposableLogContext = EntryPointLogger.AddEntryPointContext(logger, siteAccessDetails, "/api/customer/info");</pre>
<p>to the start of the controller action and</p>
<pre class="lang:c# decode:true ">disposableLogContext.Dispose();</pre>
<p>to the end, where logger has been defined in the constructor and passed in by IOC  or defined directly in the class as a private variable by using</p>
<pre class="lang:c# decode:true ">private readonly ILogger logger = Log.ForContext&lt;CustomerController&gt;();</pre>
<h4>Using Owin</h4>
<p>..but this means remembering to add it to every entry point that you create.  A better way if you are using Owin is to define a piece of middleware that calls it for you. Using the standard template for adding middleware&#8230;</p>
<pre class="lang:c# decode:true ">public class AppendEntryPointToSerilogContextMiddleware
{
	private readonly Func&lt;IDictionary&lt;string, object&gt;, Task&gt; _next;
	private readonly ILogger logger = Log.ForContext&lt;AppendEntryPointToSerilogContextMiddleware&gt;();

	public AppendEntryPointToSerilogContextMiddleware(Func&lt;IDictionary&lt;string, object&gt;, Task&gt; next)
	{
		_next = next;
	}

	public async Task Invoke(IDictionary&lt;string, object&gt; env)
	{
		var userSiteDetails = ClaimsPrincipal.Current.GetSiteDetails();
		object requestPath;
		env.TryGetValue("owin.RequestPath", out requestPath);

		using (EntryPointLogger.AddEntryPointContext(logger, userSiteDetails, requestPath?.ToString()))
		{
			await _next(env);
		}
}</pre>
<p>Which is invoked in the configuration method of your startup.cs class</p>
<pre class="lang:c# decode:true "> public void Configuration(IAppBuilder app)
{
  ...
  app.Use(typeof(AppendEntryPointToSerilogContextMiddleware));
  ...
}</pre>
<p>Notice that my code gets the site details from the ClaimsPrincipal as mentioned above and gets the path of the entry point from the Owin  RequestPath.</p>
<p>You will now get every call to your API fully logged with the path and in this case, the shop.</p>
<p>If you have entry points to your code that do not go through a request &#8211; we have subscriptions to an Azure Service Bus Topic for instance &#8211; you can just add the manual call to the entry point logger at the start.</p>
<h4>Try it!</h4>
<p>This is an extremely useful method for tracking live code which we now use extensively. If it has given you food for thought, give it a try, it&#8217;s really simple to use.</p>
<p>Get Serilog from here, get Seq from here</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.cognim.co.uk/modern-logging-with-serilog-and-seq-part-2/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">5435</post-id>	</item>
		<item>
		<title>Modern Logging with SeriLog and Seq</title>
		<link>https://www.cognim.co.uk/modern-logging-serilog/</link>
					<comments>https://www.cognim.co.uk/modern-logging-serilog/#comments</comments>
		
		<dc:creator><![CDATA[Darren Hall]]></dc:creator>
		<pubDate>Tue, 12 Apr 2016 15:28:39 +0000</pubDate>
				<category><![CDATA[c#]]></category>
		<category><![CDATA[Logging]]></category>
		<category><![CDATA[Seq]]></category>
		<category><![CDATA[Serilog]]></category>
		<guid isPermaLink="false">http://www.cognim.co.uk/?p=5419</guid>

					<description><![CDATA[Add structure to your log entries and bring your logs up to date It used to be that logging was a bit of an after thought where a few statements such as &#8216;Connecting to the database&#8217; or &#8216;Invalid user login&#8217; were written to a text file that was rarely looked at.  Well things have moved on a [&#8230;]]]></description>
										<content:encoded><![CDATA[<h3>Add structure to your log entries and bring your logs up to date</h3>
<p>It used to be that logging was a bit of an after thought where a few statements such as &#8216;Connecting to the database&#8217; or &#8216;Invalid user login&#8217; were written to a text file that was rarely looked at.  Well things have moved on a fair bit since then.</p>
<p>Part 1 of 2.  <a href="https://www.cognim.co.uk/modern-logging-with-serilog-and-seq-part-2/">Go here for part 2</a></p>
<h4>Serilog and Seq</h4>
<p><a href="http://serilog.net/" target="_blank">Serilog</a> is a modern structured logging solution that allows you to add context to your logs so that you can easily track a particular execution path.  <a href="https://getseq.net/" target="_blank">Seq</a> (pronounced &#8216;seek&#8217;) gives you the ability to host, display and search those logs.</p>
<p>For instance, imagine a customer calling and saying that when they log into your swanky portal and go to their profile page they don&#8217;t see their address.  With structured logging you could easily highlight all the logged api calls <em>made by that customer</em>, filter to the profile page and follow the execution path through to the address query to see the actual data returned.</p>
<h4>So simple!</h4>
<p>To add a context to Serilog and log to it, you just use</p>
<pre class="lang:c# decode:true">LogContext.PushProperty("customerName", customerName);</pre>
<p>Any further logging will now happen in that context, such as</p>
<pre class="lang:c# decode:true ">logger.Information("Getting customer profile");
...
logger.Information("Customer address: {customerAddress}", customerAddress);</pre>
<p>These two informational logs will now be tagged with the customer name. Notice also how Serilog uses a format similar to C# 6.0 string interpolation to embed variables. Doing it this way means you can filter by the variable in your logs.</p>
<h4>An example</h4>
<p>Here is a snapshot of a single log entry on our Seq server.</p>
<div id="attachment_5421" style="width: 731px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2016/04/SeqTag.png?ssl=1" rel="attachment wp-att-5421"><img data-recalc-dims="1" decoding="async" aria-describedby="caption-attachment-5421" loading="lazy" class="wp-image-5421 size-full" src="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2016/04/SeqTag.png?resize=721%2C135&#038;ssl=1" alt="Seq and Serilog structured logging" width="721" height="135" srcset="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2016/04/SeqTag.png?w=721&amp;ssl=1 721w, https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2016/04/SeqTag.png?resize=300%2C56&amp;ssl=1 300w" sizes="auto, (max-width: 721px) 100vw, 721px" /></a><p id="caption-attachment-5421" class="wp-caption-text">A seq view of a serilog entry, highlighting the use of a tagged context.</p></div>
<p>It is from a system we created to track users through online shops and it highlights several things;</p>
<ul>
<li>We are logging the entry point of all our API calls</li>
<li>We have set tagging on Seq to display the entry point name at the beginning of the log entry (in this case it is &#8216;api/customers&#8217;) &#8211; this will then be displayed at the beginning of every subsequent log entry created during the execution of that particular api</li>
<li>We have assigned a unique id to every httpRequest that comes through which can also be tagged or filtered</li>
<li>We can also tag or filter by the Shop that was being tracked by the system</li>
</ul>
<p>If I tell Seq to limit the log display to only &#8216;api/customer&#8217; and also to filter by the httpRequestId I get the following (click to view full size);</p>
<div id="attachment_5422" style="width: 1034px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2016/04/SeqFiltered.png?ssl=1" rel="attachment wp-att-5422"><img data-recalc-dims="1" decoding="async" aria-describedby="caption-attachment-5422" loading="lazy" class="wp-image-5422 size-large" src="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2016/04/SeqFiltered.png?resize=1024%2C265&#038;ssl=1" alt="Serilog and Seq, context in use" width="1024" height="265" srcset="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2016/04/SeqFiltered.png?resize=1024%2C265&amp;ssl=1 1024w, https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2016/04/SeqFiltered.png?resize=300%2C78&amp;ssl=1 300w, https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2016/04/SeqFiltered.png?resize=768%2C199&amp;ssl=1 768w, https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2016/04/SeqFiltered.png?w=1119&amp;ssl=1 1119w" sizes="auto, (max-width: 1000px) 100vw, 1000px" /></a><p id="caption-attachment-5422" class="wp-caption-text">Tracking the path of an api call through your code using Serilog and Seq</p></div>
<p>I can now see that the call to &#8216;customers/api&#8217; generated three further calls from our server to external apis (to our analytics server). Clicking on any of those will show me the details of the call or the response as we embedded the information in the log.</p>
<p>If I had instead chosen to tag and filter by the shop name I could see all activity related to a particular online shop.</p>
<p>What is great about this is how easy it is to quickly narrow down the exact log entries you are looking for and having done so, inspect the state of whatever variables you chose to embed in your log.</p>
<h4>Go try it yourself!</h4>
<p>I strongly recommend you to go and try out both Serilog and Seq.  <a href="https://www.cognim.co.uk/modern-logging-with-serilog-and-seq-part-2/">In the second part of this blog I show how we used Owin and middleware to create the entry point logging</a>.</p>
<p><a href="http://pluralsight.com/training/Courses/TableOfContents/modern-structured-logging-serilog-seq" target="_blank">If you want to know even more, take a look this Pluralsight course.</a></p>
<p>Have fun!</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.cognim.co.uk/modern-logging-serilog/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">5419</post-id>	</item>
		<item>
		<title>Enhancing Claims with Owin Middleware &#038; Claims Transformation</title>
		<link>https://www.cognim.co.uk/transforming-claims-claimsprincipal/</link>
					<comments>https://www.cognim.co.uk/transforming-claims-claimsprincipal/#comments</comments>
		
		<dc:creator><![CDATA[Darren Hall]]></dc:creator>
		<pubDate>Mon, 11 Apr 2016 14:44:55 +0000</pubDate>
				<category><![CDATA[Authentication]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[Owin]]></category>
		<category><![CDATA[ClaimsPrincipal]]></category>
		<guid isPermaLink="false">http://www.cognim.co.uk/?p=5385</guid>

					<description><![CDATA[Standardise your basic user data and add it to your ClaimsPrincipal for easy access! Recently I was working on a web api 2.0 project that used a bearer token for authentication and passed a UserId in the claims for the generated ClaimsPrincipal. Each controller in the project was accessing the User property from the ApiController [&#8230;]]]></description>
										<content:encoded><![CDATA[<h3>Standardise your basic user data and add it to your ClaimsPrincipal for easy access!</h3>
<p>Recently I was working on a web api 2.0 project that used a bearer token for authentication and passed a UserId in the claims for the generated ClaimsPrincipal.</p>
<p>Each controller in the project was accessing the User property from the ApiController base class to get the UserId from the claims and creating various other data to pass to a CQRS style query.  Some (simplified)  sample code follows;</p>
<pre class="lang:c# decode:true">var userId = ((ClaimsPrincipal)User).Claims.SingleOrDefault(x =&gt; x.Type == ClaimTypes.NameIdentifier);
var userRegion = GetUserRegionForUser(userId);
var userAccountName = GetUserAccountNameForUser(userId);
... Call an external query with userRegion and userAccountType to assemble data to return</pre>
<p>Doesn&#8217;t seem too bad, but this kind of code was littered throughout the project and in some cases only the UserId was passed to the external query which was then getting the other data itself.  Clearly we needed a unifying UserData class.</p>
<p>The UserData was only ever going to be three simple pieces of information (UserId, UserRegion and UserAccountName) and seemed like an ideal candidate for adding directly to the ClaimsPrinipal. You might think that a custom ClaimsPrincipal that inherits from a base class and adds UserData would be the way to go, but <a href="https://leastprivilege.com/2012/10/08/custom-claims-principals-in-net-4-5/" target="_blank">on his blog, Dominick Baier, suggests that deriviation is not ideal</a> and I tend to agree.</p>
<p>You could simply add the three pieces of information as separate claims and then read them back again in your controller:</p>
<pre class="lang:c# decode:true">var userId = ((ClaimsPrincipal)User).Claims.SingleOrDefault(x =&gt; x.Type == ClaimTypes.NameIdentifier);
var userRegion = ((ClaimsPrincipal)User).Claims.SingleOrDefault(x =&gt; x.Type == "UserRegion");
var userAccountName = ((ClaimsPrincipal)User).Claims.SingleOrDefault(x =&gt; x.Type == "UserAccountName");</pre>
<p>but this approach is messy and doesn&#8217;t give us much more than the code we are trying to change.</p>
<h4>Using extensions</h4>
<p>The answer, as suggested in Dominick&#8217;s blog, relies on extension methods. Careful use of these allows us to not only get and set the UserData class on the principal but also to check for its existence.</p>
<pre class="lang:c# decode:true">public static class ClaimsPrincipalExtensions
{
  private const string UserRegion = "UserRegion";
  private const string UserAccountName = "UserAccountName";

  public static bool HasUserData(this ClaimsPrincipal principal)
  {
    return principal.HasClaim(claim =&gt; claim.Type == UserRegion);
  }

  public static UserData GetUserData(this ClaimsPrincipal principal)
  {
    var userId = principal.Claims.SingleOrDefault(x =&gt; x.Type == ClaimTypes.NameIdentifier)?.Value;
    var userRegion = principal.Claims.SingleOrDefault(x =&gt; x.Type == UserRegion)?.Value;
    var userAccountName = principal.Claims.SingleOrDefault(x =&gt; x.Type == UserAccountName)?.Value;

    return new UserData(userId, userRegion, userAccountName);
  }

  public static void AddSiteDetails(this ClaimsPrincipal principal, UserData userData)
  {
    principal.Identities.First().AddClaim(new Claim(ClaimTypes.NameIdentifier, siteAccessDetails.UserId));
    principal.Identities.First().AddClaim(new Claim(UserRegion, userData.UserRegion));
    principal.Identities.First().AddClaim(new Claim(UserAccountName, userData.UserAccountName));
  }
}</pre>
<h4>Getting the UserData</h4>
<p>Now we can access the UserData class from the principal with</p>
<pre class="lang:c# decode:true">var userData = ((ClaimsPrincipal)User).GetUserData();</pre>
<p>or, not relying on the ApiController base class</p>
<pre class="lang:c# decode:true ">var userData = ClaimsPrincipal.Current.GetUserData();</pre>
<h4>Creating the claims transformation</h4>
<p>But how do we add the claims in the first place, especially considering we are using Owin middleware? The easiest way is to use the freely available NuGet package <a href="https://www.nuget.org/packages/IdentityModel.Owin.ClaimsTransformation/" target="_blank">IdentityModel Owin ClaimsTransformation</a> <a href="https://github.com/identitymodel/owin.claimstransformation" target="_blank">(the simple source for which is available here if you want to hand craft it</a>).</p>
<p>Having installed this package, add a claims transformer class:</p>
<pre class="lang:c# decode:true ">public interface IClaimsTransformer
{
  Task&lt;ClaimsPrincipal&gt; TransformWithSiteDetails(ClaimsPrincipal principal);
}

public class ClaimsTransformer : IClaimsTransformer
{
  private readonly IUserDataProvider userDataProvider;

  public ClaimsTransformer(IUserDataProvider userDataProvider)
  {
    this.userDataProvider = userDataProvider;
  }

  public Task&lt;ClaimsPrincipal&gt; TransformWithUserData(ClaimsPrincipal principal)
  {
    if (principal.Identity.IsAuthenticated &amp;&amp; !principal.HasUserData())
    {
      principal.AddUserData(userDataProvider.GetDataByClaimsPrincipal(principal));
    }
    return Task.FromResult(principal);
  }
}</pre>
<p>Here I am passing in a UserDataProvider that can get me the user data from wherever it originates and using that to populate the principal.</p>
<h4>Integrating with Owin middleware</h4>
<p>Next add the transformer to your Startup.cs class (after your authentication middleware)</p>
<pre class="lang:c# decode:true">app.UseClaimsTransformation(incoming =&gt; Container.Resolve&lt;IClaimsTransformer&gt;().TransformWithUserData(incoming));</pre>
<p>Note that I am resolving the claimsTransformer from our IOC container, you can do it whichever way you choose.</p>
<p>And that&#8217;s it! Your authenticated controllers will now have the UserData contained in the ClaimsPrincipal and can easily be accessed or tested for.</p>
<p>I hope that helps.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.cognim.co.uk/transforming-claims-claimsprincipal/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">5385</post-id>	</item>
		<item>
		<title>Going Further with Fluent Builders in your Tests &#8211; C#</title>
		<link>https://www.cognim.co.uk/going-further-with-fluent-builders-in-your-tests-c/</link>
					<comments>https://www.cognim.co.uk/going-further-with-fluent-builders-in-your-tests-c/#comments</comments>
		
		<dc:creator><![CDATA[Darren Hall]]></dc:creator>
		<pubDate>Tue, 25 Aug 2015 15:59:29 +0000</pubDate>
				<category><![CDATA[c#]]></category>
		<category><![CDATA[TDD]]></category>
		<guid isPermaLink="false">http://www.cognim.co.uk/?p=5231</guid>

					<description><![CDATA[Fluent Builders are extremely useful. Once you start using them there is no going back! In my first article I outlined fluent builders &#8211; what they look like and how to put them together. This time I will go a little deeper to show you just how versatile they can be. Method Naming You can [&#8230;]]]></description>
										<content:encoded><![CDATA[<h3>Fluent Builders are extremely useful. Once you start using them there is no going back!</h3>
<p><a href="https://www.cognim.co.uk/use-fluent-builders-in-your-tests/">In my first article I outlined fluent builders &#8211; what they look like and how to put them together</a>. This time I will go a little deeper to show you just how versatile they can be.</p>
<h4>Method Naming</h4>
<p>You can be as flexible as you like in naming the methods in your builders. A standard starting place is to use &#8216;With&#8230;&#8217; for example WithFirstName(..), WithDateOfBirth(..) etc. I find the best naming convention is one that makes your tests as easy to read as possible.  For instance</p>
<pre class="lang:c# decode:true">Customer testCustomer = new CustomerBuilder().
    .WithName("Peter Perfect")
    .Aged(32)
    .ThatIsAFirstTimeBuyer();</pre>
<p>Remember that it is fine to add specific methods such as &#8216;ThatIsAFirstTimeBuyer()&#8217; above where it could be setting an individual property, a series of properties or calling further methods within the customer class to create that state. You can also add specific tests for your builders to ensure those methods are working as expected.</p>
<h4>Adding Lists</h4>
<p>Your builder methods can also take in lists or add to lists. Let&#8217;s say that our CustomerBuilder allows us to add products they have bought.  It could be created in two ways;</p>
<pre class="lang:c# decode:true ">public CustomerBuilder WithProduct(Product product)
{
    this.customer.Products.Add(product);
    return this;
}</pre>
<p>or</p>
<pre class="lang:c# decode:true ">public CustomerBuilder WithProducts(List products)
{
    this.customer.Products = products;
    return this;
}</pre>
<p>In the first case we could use a product builder to add each product to the customer</p>
<pre class="lang:c# decode:true ">Customer customer = new CustomerBuilder()
    .WithProduct(new ProductBuilder().WithName("Apple")))
    .WithProduct(new ProductBuilder().WithName("Orange"))</pre>
<p>In the second we could create a specific ProductListBuilder()</p>
<pre class="lang:c# decode:true ">public class ProductListBuilder
{
    private readonly List products;

    public ProductListBuilder()
    {
        this.products = new List();
    }

    public static implicit operator List(ProductListBuilder builder)
    {
        return builder.products;
    }

    public ProductListBuilder WithProduct(string productName)
    {
        this.products.Add(new Product { Name = productName });
        return this;
    }
}</pre>
<p>Which we would use this way</p>
<pre class="lang:c# decode:true ">    List&lt;Product&gt; products = new ProductListBuilder().WithProduct("Apple").WithProduct("Orange");
    Customer customer = new CustomerBuilder().WithProducts(products);</pre>
<h4>Builders for Mocked Objects</h4>
<p>Do you often have to mock repositories?  How about using a builder to do it?</p>
<pre class="lang:c# decode:true  ">public class MockCustomerRepositoryBuilder
{
    private readonly Mock&lt;irepository&gt; mockCustomerRepository;

    public MockCustomerRepositoryBuilder()
    {
        this.mockCustomerRepository= new Mock&lt;irepository&gt;();
    }

    public Customer SavedCustomer { get; private set; }

    public static implicit operator Mock&lt;irepository&gt;(MockCustomerRepositoryBuilder builder)
    {
        return builder.mockCustomerRepository;
    }

    public MockCustomerRepositoryBuilder WhereGetByIdReturns(Customer customer)
    {
        this.mockCustomerRepository.Setup(cfr =&gt; cfr.GetById(It.IsAny())).Returns(customer);
        return this;
    }

    public MockCustomerRepositoryBuilder WithSave()
    {
        this.mockCustomerRepository.Setup(cfr =&gt; cfr.Save(It.IsAny())).Callback(cfr =&gt; { SavedCustomer = cfr; });
        return this;
    }
}</pre>
<p>The usage is as follows</p>
<pre class="lang:c# decode:true">    var mockCustomerRepository = new MockCustomerRepositoryBuilder()
        .WithSave()
        .WhereGetByIdReturns(new Customer().WithName("Tom Test"));</pre>
<p>What is really cool about this is that you can set up the save method in your mocked repository to save whatever you pass in to a public property. This allows you to assert that your code under test has actually passed the right object through.  You can also direct it to return whatever you like from the GetById() method of this repository so that you don&#8217;t have to set it up in each test.</p>
<p>I hope this has helped you to further appreciate the power of these builders.  Please feel free to ask any questions you may have below.  Next time I will show how to test MVC controllers with builders in a fluent way.</p>
<p>Thanks for listening.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.cognim.co.uk/going-further-with-fluent-builders-in-your-tests-c/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">5231</post-id>	</item>
		<item>
		<title>Use Fluent Builders In Your Tests &#8211; C#</title>
		<link>https://www.cognim.co.uk/use-fluent-builders-in-your-tests/</link>
					<comments>https://www.cognim.co.uk/use-fluent-builders-in-your-tests/#comments</comments>
		
		<dc:creator><![CDATA[Darren Hall]]></dc:creator>
		<pubDate>Wed, 05 Aug 2015 16:22:04 +0000</pubDate>
				<category><![CDATA[c#]]></category>
		<category><![CDATA[TDD]]></category>
		<category><![CDATA[Coding]]></category>
		<guid isPermaLink="false">http://www.cognim.co.uk/?p=5107</guid>

					<description><![CDATA[When creating tests (for TDD or BDD), use fluent builders No, I don&#8217;t mean the kind that come around and drink all your coffee / tea. When you are testing your code you often have to initialise various classes beforehand. There are several ways to do this. Consider this simple api that takes in a [&#8230;]]]></description>
										<content:encoded><![CDATA[<h3>When creating tests (for TDD or BDD), use fluent builders</h3>
<p>No, I don&#8217;t mean the kind that come around and drink all your coffee / tea. When you are testing your code you often have to initialise various classes beforehand. There are several ways to do this. Consider this simple api that takes in a &#8216;Booking&#8217; object and returns the cost of the booking.</p>
<pre class="">public int GetCostOfBooking(Booking booking)
{
    // ... implementation not important here
}</pre>
<p>Where the Booking object is</p>
<pre class="">public class Booking
{
    public DateTime FirstDay { get; set; }

    public DateTime LastDay { get; set; }

    public decimal LocationCostPerNight { get; set; }

    public Customer Customer { get; set; }
}</pre>
<p>and the Customer object is</p>
<pre class="">public class Customer
{
    public decimal PercentDiscount { get; set; }
}</pre>
<p>Your test could be set up as follows</p>
<pre class="">[TestMethod]
public void BookingCostIsCorrect()
{
    var customer = new Customer { PercentDiscount = 10 };
    var booking = new Booking
                      {
                          FirstDay = DateTime.Parse("2015/08/15"), 
                          LastDay = DateTime.Parse("2015/08/20"), 
                          LocationCostPerNight = 10, 
                          Customer = customer
                      };
    var actual = GetCostOfBooking(booking);
    var expected = 45;
    Assert.AreEqual(expected, actual);
}</pre>
<p>(please bear with me on these primitive samples and tests!)</p>
<p>Now this doesn&#8217;t look too bad, but what if I add more properties to Customer and Booking or force the use of constructors and specific set methods?</p>
<pre class="lang:c# decode:true">public class Booking
{
    public DateTime FirstDay { get; private set; }
    public DateTime LastDay { get; private set; }
    public decimal LocationCostPerDay { get; private set; }
    public Customer Customer { get; private set; }

    public void SetCostPerDay(decimal costPerDay)
    {
        this.LocationCostPerDay = costPerDay;
    }

    public void SetFirstDay(DateTime firstDay)
    {
        this.FirstDay = firstDay;
    }

    public void SetLastDay(DateTime lastDay)
    {
        this.LastDay = lastDay;
    }

    public void SetCustomer(Customer customer)
    {
        this.Customer = customer;
    }
}</pre>
<pre class="lang:c# decode:true">public class Customer
{
    public Customer(string firstName, string lastName, DiscountScheme discountScheme)
    {
        this.FirstName = firstName;
        this.LastName = LastName;
        this.DiscountScheme = discountScheme;
    }

    public string FirstName { get; private set; }

    public string LastName { get; private set; }

    public DiscountScheme DiscountScheme { get; private set; }
}</pre>
<pre class="lang:c# decode:true">public class DiscountScheme
{
    public decimal PercentDiscount { get; private set; }

    public void SetDiscount(decimal discount)
    {
        this.PercentDiscount = discount;
    }
}</pre>
<p>Now my test setup becomes</p>
<pre class="lang:c# decode:true">[TestMethod]
public void BookingCostIsCorrect()
{
     var discountScheme = new DiscountScheme();
     discountScheme.SetDiscount(10);
     var customer = new Customer("Johnny", "BigCheese", discountScheme);
     var booking = new Booking();
     booking.SetCustomer(customer);
     booking.SetFirstDay(DateTime.Parse("2015/08/15"));
     booking.SetLastDay(DateTime.Parse("2015/08/15"));
     booking.SetCostPerDay(10);
     var actual = GetCostOfBooking(booking);
     var expected = 45;
     Assert.AreEqual(expected, actual);
}</pre>
<p>Oh, not so nice any more. I have polluted my test with superfluous information, I am relying on calling the right methods to initialise properties and I have made the test that bit more obfuscated.</p>
<p>Instead, how about this</p>
<pre class="lang:c# decode:true ">[TestMethod]
public void BookingCostIsCorrect()
{
    var customer = new CustomerBuilder()
                        .WithDiscount(10);

    var booking = new BookingBuilder()
                        .FromFirstDay("2015/08/15")
                        .ToLastDay("2015/08/19")
                        .ForCustomer(customer)
                        .AtCostPerDay(10);

    var actual = GetCostOfBooking(booking);
    var expected = 45;
    Assert.AreEqual(expected, actual);
}</pre>
<p>Much nicer! It is easy to see what we are testing and how it is set up. There is no unnecessary information here. Also, thanks to the use of a builder, all the code for creating those objects is in a central place so you don&#8217;t have to edit all your tests when there is a change in how they should be initialised.</p>
<h3>Great!  How do I do it?</h3>
<p>It&#8217;s really not that difficult and once you have written a few you start to get the hang of it.  For instance here are the builder classes we have used above</p>
<pre class="lang:c# decode:true" title="BookingBuilder">public class BookingBuilder
{
    private Booking booking;

    public BookingBuilder()
    {
        this.booking = new Booking();
    }

    public static implicit operator Booking(BookingBuilder builder)
    {
        return builder.booking;
    }

    public BookingBuilder ForCustomer(Customer customer)
    {
        this.booking.SetCustomer(customer);
        return this;
    }

    public BookingBuilder FromFirstDay(string firstDay)
    {
        this.booking.SetFirstDay(DateTime.Parse(firstDay));
        return this;
    }

    public BookingBuilder ToLastDay(string lastDay)
    {
        this.booking.SetLastDay(DateTime.Parse(lastDay));
        return this;
    }

    public BookingBuilder AtCostPerDay(decimal costPerDay)
    {
        this.booking.SetCostPerDay(costPerDay);
        return this;
    }
}</pre>
<pre class="lang:c# decode:true" title="CustomerBuilder">public class CustomerBuilder
{
    private Customer customer;

    public CustomerBuilder()
    {
        this.customer = new Customer("Test", "Test", new DiscountScheme());
    }

    public static implicit operator Customer(CustomerBuilder builder)
    {
        return builder.customer;
    }

    public CustomerBuilder WithDiscount(decimal discount)
    {
        this.customer.DiscountScheme.SetDiscount(discount);
        return this;
    }
}</pre>
<p>The main thing to remember when creating a fluent builder is that your methods return the class itself, that allows you to chain them. Note also the static implicit operator that converts between the builder and the object it is building. Adding that means we can directly use the builder in place of the object being built (ie passing the booking builder into the GetCostOfBooking method.</p>
<p>I mean this blog to be an introduction to fluent builders &#8211; <a href="https://www.cognim.co.uk/going-further-with-fluent-builders-in-your-tests-c/">you can get much more fancy with them than this and I have written a blog here that shows how to do that</a>.</p>
<p>If you have any questions or want to add your own feedback, please comment below.  We would love to hear from you.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.cognim.co.uk/use-fluent-builders-in-your-tests/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">5107</post-id>	</item>
		<item>
		<title>More concise, more readable. C# 6.0 real world gains</title>
		<link>https://www.cognim.co.uk/more-concise-more-readable-c-6-0-real-world-gains/</link>
					<comments>https://www.cognim.co.uk/more-concise-more-readable-c-6-0-real-world-gains/#comments</comments>
		
		<dc:creator><![CDATA[Darren Hall]]></dc:creator>
		<pubDate>Mon, 20 Jul 2015 10:39:58 +0000</pubDate>
				<category><![CDATA[c#]]></category>
		<category><![CDATA[C# 6.0]]></category>
		<guid isPermaLink="false">http://www.cognim.co.uk/?p=4982</guid>

					<description><![CDATA[With Visual Studio 2015 comes C# 6.0. The team at Microsoft put a whole lot of effort into the Roslyn compiler this time around and the language features are primarily syntactic sugar, but they are still extremely welcome. The Null-Conditional Operator Here is a small piece of code that I inherited recently.  It has a [&#8230;]]]></description>
										<content:encoded><![CDATA[<h3>With Visual Studio 2015 comes C# 6.0. The team at Microsoft put a whole lot of effort into the Roslyn compiler this time around and the language features are primarily syntactic sugar, but they are still extremely welcome.</h3>
<h5>The Null-Conditional Operator</h5>
<p>Here is a small piece of code that I inherited recently.  It has a very simple task, get the client&#8217;s postcode or return &#8216;unknown&#8217;</p>
<pre>public string GetPostCodeOfClientsOffice(Client client)
{
  if ((client == null) || (client.Office == null)
   || (client.Office.Address == null) || (client.Office.Address.PostCode == null))
  {
    return "unknown";
  }
  return client.Office.Address.PostCode;
}</pre>
<p>how much nicer it becomes when we use the new null conditional operator</p>
<pre>public string GetPostCodeOfClientsOffice(Client client)
{
 return client?.Office?.Address?.PostCode ?? "unknown";
}
</pre>
<p>Note that the type of client?.Office?.Address?.PostCode is nullable String.</p>
<p>This isn&#8217;t restricted to properties, the following method can also be refactored</p>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp" data-enlighter-theme="beyond" data-enlighter-linenumbers="false">public int GetNumberOfClientsAwatingFeedback(List clients)
{
 if (clients != null) {
  return clients.Where(client=>client.NeedsFeedback).Count;
 }
 return 0;
}</pre>
<p>which is expressed more simply as</p>
<pre>public int GetNumberOfClientsAwatingFeedback(List clients)
{
 return clients?.Where(client=>client.NeedsFeedback).Count ?? 0;
}</pre>
<h5>Nameof Expressions</h5>
<p>When we have methods that expect non null properties we might typically see code like this</p>
<pre>public MemberParty GetMainClientAffiliation(Client client)
{
 If (client == Null)
  throw new ArgumentNullException("client");
 If (client.MemberParty == Null)
  throw new ArgumentNullException("MemberParty ");
 return client.MemberParty ;
}
</pre>
<p>Notice here that the method refers to client affiliation and the property it returns is &#8216;MemberParty &#8216;. <em><a href="http://martinfowler.com/bliki/UbiquitousLanguage.html">Not a very ubiquitous approach</a>.</em></p>
<p>When we refactor to use affiliation however, the following occurs</p>
<pre>public Affiliation GetMainClientAffiliation(Client client)
{
 If (client == Null)
  throw new ArgumentNullException("client");
 If (client.Affiliation == Null)
  throw new ArgumentNullException("MemberParty ");
 return client.Affiliation;
}
</pre>
<p>Aargh, the dreaded magic string has caught us out.  C# 6.0 to the rescue</p>
<pre>public Affiliation GetMainClientAffiliation(Client client)
{
 If (client == Null)
  throw new ArgumentNullException(nameof(client));
 If (client.Affiliation == Null)
  throw new ArgumentNullException(nameof(client.Affiliation));
 return client.Affiliation;
}
</pre>
<p>Now we have strongly typed properties and safe refactoring. Not a massive advance but something that has caught me out many times over the years.</p>
<h5>Expression bodied properties and functions</h5>
<p>Let&#8217;s say we have the following code</p>
<pre>public class Client
{
 public string FirstName { get; set; }
 public string LastName { get; set; }

 public string FullName { 
  get{ 
   return string.Format("{0} {1}",FirstName,LastName); 
  }
 }
}
</pre>
<p>we can now rewrite this as</p>
<pre>public class Client
{
 public string FirstName { get; set; }
 public string LastName { get; set; }

 public string FullName => string.Format("{0} {1}",FirstName,LastName);
}
</pre>
<p>Note that these are not lambda expressions, they are just syntactic sugar intended to simplify your code and make it more readable.</p>
<h5>String Interpolation</h5>
<p>even better, we can change this to</p>
<pre>public class Client
{
 public string FirstName { get; set; }
 public string LastName { get; set; }

 public string FullName => $"{FirstName} {LastName}";
}
</pre>
<p>Much more readable!</p>
<p>Also if we wanted to override the ToString method for this class, we might use several new features together in the following way</p>
<pre> public override string ToString() => $"Full name: {FullName} City: {Address?.City ?? "Unknown"}";
</pre>
<p>These are a few of the new language features. Like I said at the start, most of the effort this time around went into Roslyn but I really appreciate that the subtle changes they did make add to the beauty of the language.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.cognim.co.uk/more-concise-more-readable-c-6-0-real-world-gains/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">4982</post-id>	</item>
	</channel>
</rss>
