<?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>Cognim &#8211; Internet development</title>
	<atom:link href="https://www.cognim.co.uk/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 , all for a very reasonable price and you have a conference I really can&#8217;t recommend enough! The talk that [&#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 <span class="tooltips " style="" title="My favourite thing this year was a game of human space invaders, using nerf guns, moderated by Mario for some reason"><em>space themed party</em></span>, 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>Gulp and Visual Studio: Code quality</title>
		<link>https://www.cognim.co.uk/gulp-and-visual-studio-code-quality/</link>
					<comments>https://www.cognim.co.uk/gulp-and-visual-studio-code-quality/#respond</comments>
		
		<dc:creator><![CDATA[Darren Hall]]></dc:creator>
		<pubDate>Tue, 10 Nov 2015 09:58:30 +0000</pubDate>
				<category><![CDATA[Gulp]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<guid isPermaLink="false">http://www.cognim.co.uk/?p=5258</guid>

					<description><![CDATA[This is Part 4 is my series on using Gulp with Visual Studio. So far we&#8217;ve covered setting up Visual Studio for use with Gulp, processing SASS, and getting the files ready for deployment. Part 1: Setting up Gulp with Visual Studio Part 2: Getting SASSy Part 3: Deployment: minification and concatenation Part 4: Code [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>This is Part 4 is my series on using Gulp with Visual Studio. So far we&#8217;ve covered setting up Visual Studio for use with Gulp, processing SASS, and getting the files ready for deployment.</p>
<ul>
<li><a href="https://www.cognim.co.uk/getting-started-with-gulp-and-vs/" target="_blank">Part 1: Setting up Gulp with Visual Studio</a></li>
<li><a href="https://www.cognim.co.uk/gulp-and-visual-studio-sass/">Part 2: Getting SASSy</a></li>
<li><a href="https://www.cognim.co.uk/gulp-vs-minification/">Part 3: Deployment: minification and concatenation</a></li>
<li>Part 4: Code quality: tests and linting</li>
<li>Part 5: Thoughts on Gulp</li>
</ul>
<p>In this post I want to talk about JavaScript code quality.</p>
<h3>Code quality: tests and linting</h3>
<p>JavaScript is a notoriously quirky language &#8211;  the tricky &#8220;this&#8221; operator, lack of block level scoping, the ability to use variables before declaring them, &#8220;==&#8221; vs &#8220;===&#8221;, etc etc.</p>
<p>We can do a number of things to tighten up our code quality. We can run tests to ensure our code works as expected, and we can run a linting program to catch any syntatic mistakes before running our code. Combining this with Gulp gives a nice workflow for development.</p>
<h4>Linting with JSHint</h4>
<p><a href="http://stackoverflow.com/questions/8503559/what-is-linting" target="_blank">Linting</a> is a process of running a program to analyse code for potential problems, catching bugs before the program gets executed. Douglas Crockford created <a href="http://www.jslint.com/" target="_blank">JSLint</a> in 2011, and of course there is a <a href="https://www.npmjs.com/package/gulp-jslint" target="_blank">gulp plugin</a> for it. However, I prefer to use <a href="http://jshint.com/" target="_blank">JSHint</a> &#8211; a community offshoot of JSLint that allows for more customisation and is slightly more relaxed in its defaults. You can find a good comparison of the two <a href="http://stackoverflow.com/a/10763615" target="_blank">here</a>.</p>
<p>First, I would seperate out any third-party libraries or frameworks you have into their own folder(s). In my opinion this is good practice anyway, but especially if we are running linting &#8211; we don&#8217;t want failures on code we haven&#8217;t written! Next, we want to add the <a href="https://www.npmjs.com/package/gulp-jshint" target="_blank">plugin</a> to our package.json:</p>
<pre class="lang:js decode:true ">{
  "scripts": { "install": "echo Done" },
    
  "devDependencies": {
    "gulp": "~3.9.0",
    "gulp-load-plugins": "~0.10.0",
    "gulp-jshint": "~1.11.2",
    // other plugins here
  } 
}</pre>
<p>Then, add the Gulp task to our gulpfile:</p>
<pre class="lang:c# decode:true" title="gulpfile.js">var sources = ['./Scripts/*.js', '!./Scripts/libs/*.js'];

gulp.task('watch-lint', function () {
    gulp.watch(sources, ['lint']);
});

gulp.task('lint', function () {
    return gulp.src(sources)
        .pipe(plugins.jshint({
            strict: true,
            predef: [""]
        }))
        .pipe(plugins.jshint.reporter('default'))
        .pipe(plugins.jshint.reporter('fail'))
    ;
});</pre>
<p>Here&#8217;s a line by line breakdown of the important stuff:</p>
<ul>
<li>Line 1: Define the JavaScript files we want linting, excluding any third party libraries and frameworks</li>
<li>Line 3-5: Set up a watch to run the linting task whenever we make a change to our JavaScript</li>
<li>Line 7: Set up our linting task</li>
<li>Line 8-12: Send our files to JSHint. JSHint has a number of options you can set to define how lenient or strict you want it to be. You can look at the <a href="http://jshint.com/docs/" target="_blank">docs</a> to get an idea of what you can set. Here I&#8217;m only using the strict option (<a href="http://www.nczonline.net/blog/2012/03/13/its-time-to-start-using-javascript-strict-mode/" target="_blank">here</a> is a good blog explaining strict mode). There is also a section to define any global variables you&#8217;re using that should be ignored &#8211; for example if you&#8217;re using Angular you&#8217;ll want to add &#8220;angular&#8221; here</li>
<li>Line 13-14: Send the output of the linting to some inbuilt reporters &#8211; one to output the results to console and one to raise an error for any failures</li>
</ul>
<p>Now we can add the watch task to our default task, and we&#8217;ll have linting every time we change our code.</p>
<h4>Tests with Karma</h4>
<p>One of the great things about Gulp is that you can get a Gulp task to run other Node based packages directly. For example, you can run <a href="http://karma-runner.github.io" target="_blank">Karma</a> within a task, without having to use a plugin. Combined with <a href="http://phantomjs.org/" target="_blank">PhantomJS</a>, a headless browser, you get a great unit testing framework for your JavaScript. First, add the packages:</p>
<pre class="lang:c# decode:true " title="package.json">{
  "scripts": { "install": "echo Done" },
    
  "devDependencies": {
    "gulp": "~3.9.0",
    "karma-jasmine": "~0.3.6",
    "karma": "~0.13.9",
    "karma-phantomjs-launcher": "~0.2.1"
    // other plugins here
  } 
}</pre>
<p>Then, we&#8217;ll need to add our karma config file (karma.conf.js) at the root of the project :</p>
<pre class="lang:js decode:true" title="karma.conf.js">module.exports = function (config) {
    config.set({
        files: ['./Scripts/*.js',
                './Scripts/Specs/**/*.js',
        ],

        exclude: ['./Scripts/libs/*.js'],

        frameworks: ['jasmine'],

        autoWatchBatchDelay: 1000,

        reporters: ['progress'],

        browsers: ['PhantomJS']
    });
};</pre>
<p>One thing I&#8217;ve found using Karma in Visual Studio: often Karma can crash in Visual Studio with an &#8220;EBUSY&#8221; error. I haven&#8217;t found an adequate explanation for this yet &#8211; I think it&#8217;s because when you modify and save a file Visual Studio writes a temporary file to replace the file you are saving, which doesn&#8217;t sit well with Node. This can be mitigated by setting the &#8220;autoWatchBatchDelay&#8221; to 1000, which waits 1 second after any change before running tests.</p>
<p>Finally, our gulp task:</p>
<pre class="lang:js decode:true">var Server = require('karma').Server;

gulp.task('runTests', function () {
    new Server({
        configFile: __dirname + '/karma.conf.js',
        singleRun: false
    }).start();
});</pre>
<p>Here, we are simply firing up Karma from within a Gulp task and passing in our karma config file. We are also telling Karma to watch our files for any changes and re-run our tests if they change. If you are going to run this task on a build server (and you should), you&#8217;ll need to configure the singleRun variable here. This can be done by using <a href="https://www.npmjs.com/package/yargs" target="_blank">yargs</a> to pass in a variable to switch this behaviour.</p>
<p>There we are! There is a commit of all the changes <a href="https://github.com/edwardridge/Gulp-and-Visual-Studio/commit/92ba6c092e262261171c642aa765129238e00283">here</a>, which includes a sample test. I highly recommend using both linting and unit tests when writing JavaScript code, and Gulp is great at running these tasks for us.</p>
<p>Next, in the last past I want to share my thoughts on Gulp, specifically within the .NET ecosystem.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.cognim.co.uk/gulp-and-visual-studio-code-quality/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">5258</post-id>	</item>
		<item>
		<title>Gulp and Visual Studio: concatenation and minification</title>
		<link>https://www.cognim.co.uk/gulp-vs-minification/</link>
					<comments>https://www.cognim.co.uk/gulp-vs-minification/#comments</comments>
		
		<dc:creator><![CDATA[Darren Hall]]></dc:creator>
		<pubDate>Thu, 24 Sep 2015 15:04:44 +0000</pubDate>
				<category><![CDATA[Gulp]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<guid isPermaLink="false">http://www.cognim.co.uk/?p=5268</guid>

					<description><![CDATA[In my previous blog I wrote about how we can use Gulp to compile SASS. This time it&#8217;s all about how we can use Gulp in Visual Studio to prepare files for a release by minifying and concatenating them. I&#8217;ve put up a project using the standard MVC 5 template for this series of posts [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>In my previous blog I wrote about how we can use Gulp to compile SASS. This time it&#8217;s all about how we can use Gulp in Visual Studio to prepare files for a release by minifying and concatenating them. I&#8217;ve put up a project using the standard MVC 5 template for this series of posts <a href="https://github.com/edwardridge/Gulp-and-Visual-Studio" target="_blank">here</a></p>
<ul>
<li><a href="https://www.cognim.co.uk/getting-started-with-gulp-and-vs/" target="_blank">Part 1: Setting up Gulp with Visual Studio</a></li>
<li><span style="color: #000000;"><a href="https://www.cognim.co.uk/gulp-and-visual-studio-sass/" target="_blank">Part 2: Getting SASSy</a></span></li>
<li><span style="color: #999999;"><a href="https://www.cognim.co.uk/gulp-vs-minification">Part 3: Deployment: minification and concatenation</a></span></li>
<li><span style="color: #999999;">Part 4: Code quality: tests and linting</span></li>
<li><span style="color: #999999;">Part 5: Thoughts on Gulp</span></li>
</ul>
<h3>Small is beautiful</h3>
<p>To increase the speed of a site, and to save bandwidth, we want to:</p>
<ul>
<li>Have as few requests for the smallest files possible</li>
<li>Cache these files for as long as possible</li>
</ul>
<p>We can achieve this by concatenating and minifying the files, then adding a hash of the files contents to the filename so they can be cached indefinitely.</p>
<p>There are a number of different ways of approaching minification and concatenation with Gulp, and a lot of different plugins and plugin combinations. The following is a style that has worked for me, you may need to adjust it to suit your own workflow.</p>
<h3>Plugins</h3>
<p>There are a number of plugins we will need:</p>
<ul>
<li><a href="https://www.npmjs.com/package/gulp-useref">gulp-useref</a> for concatenation</li>
<li><a href="https://www.npmjs.com/package/gulp-uglify">gulp-uglify</a> and <a href="https://www.npmjs.com/package/gulp-minify-css">gulp-minify-css</a> for minifcation of JavaScript and CSS respectively</li>
<li><a href="https://github.com/sindresorhus/gulp-rev">gulp-rev</a> and <a href="https://github.com/jamesknelson/gulp-rev-replace">gulp-rev-replace</a> for revisioning</li>
<li><a href="https://www.npmjs.com/package/gulp-filter">gulp-filter</a> for filtering files to process them independently</li>
</ul>
<p>Lets add these to the package.json:</p>
<pre class="lang:js decode:true">{
  "scripts": { "install": "echo Done" },
    
  "devDependencies": {
    "gulp": "~3.9.0",
    "gulp-load-plugins": "~0.10.0",
    "gulp-useref": "~1.3.0",
    "gulp-uglify": "~1.2.0",
    "gulp-minify-css": "~1.2.1",
    "gulp-rev": "~5.1.0",
    "gulp-rev-replace": "~0.4.2",
    "gulp-filter": "~3.0.0"
  } 
}
</pre>
<h3>Referencing scripts and CSS</h3>
<p>Now we&#8217;ll want to add our CSS and JavaScript files to our pages. These are put in commented <strong>build blocks</strong> that let gulp-useref know where a section it should concatenate is. So, at the top of the page (here it&#8217;s the _Layout.cshtml page) we reference the CSS:</p>
<pre class="lang:xhtml decode:true">&lt;!-- build:css /dist/site.css --&gt;
    &lt;link href="/Content/bootstrap.css" rel="stylesheet" /&gt;
    &lt;link href="/Content/Site.css" rel="stylesheet" /&gt;
&lt;!-- endbuild --&gt;    
<!-- endbuild --></pre>
<p>In the first comment, we define two things:</p>
<ul>
<li>The first part, &#8220;build:css&#8221; tells useref that this be a CSS block</li>
<li>The second is the location of the concatenated file that will eventually be referenced (more on this later)</li>
</ul>
<p>We do the same at the bottom with the JavaScript:</p>
<pre class="lang:xhtml decode:true">&lt;!-- build:js /dist/libs.js --&gt;
    &lt;script src="/Scripts/Libraries/jquery.js"&gt;&lt;/script&gt;
    &lt;script src="/Scripts/Libraries/bootstrap.js"&gt;&lt;/script&gt;
    &lt;script src="/Scripts/Libraries/respond.js"&gt;&lt;/script&gt;
&lt;!-- endbuild --&gt;<script src="/Scripts/Libraries/respond.js"></script><!-- endbuild --></pre>
<p>We can have multiple build blocks of the same type (e.g. multiple JavaScript blocks) so we can have one for libraries (Angular, jQuery etc) which will change less frequently than the code we write.</p>
<h3>The Gulp task</h3>
<p>Now for the biggie &#8211; the actual task itself. I&#8217;ll put it here and go through it in more detail below:</p>
<pre class="nums:true lang:js decode:true">gulp.task('minifyFilesForRelease', function () {

    var cssFilter = plugins.filter('**/*.css', { restore: true });
    var jsFilter = plugins.filter('**/*.js', { restore: true });

    var assets = plugins.useref.assets();
    gulp.src('./**/*.cshtml')
        .pipe(assets)

        //Process JavaScript
        .pipe(jsFilter)
        .pipe(plugins.uglify())
        .pipe(plugins.rev())
        .pipe(assets.restore())
        .pipe(jsFilter.restore)
        
        //Process CSS
        .pipe(cssFilter)
        .pipe(plugins.minifyCss({
            keepSpecialComments: 0
        }))
        .pipe(plugins.rev())
        .pipe(assets.restore())
        .pipe(cssFilter.restore)

        .pipe(plugins.useref())
        .pipe(plugins.revReplace({
            replaceInExtensions: ['.js', '.css', '.html', '.cshtml']
        }))
        .pipe(gulp.dest(function (data) {
            return data.base;
        }
        ));
});</pre>
<p>Here&#8217;s a line by line breakdown of what&#8217;s happening:</p>
<ul>
<li>Line 1: Define the task</li>
<li>Line 3-4: Setup some filters we will use later to separate out the CSS and JavaScript for individual processing</li>
<li>Line 6: Reference the assets object of useref which will return the build blocks we setup earlier</li>
<li>Line 7: Get all our cshtml files</li>
<li>Line 8: Get all our build blocks in these files</li>
<li>Line 11: Filter our build blocks to just the JavaScript</li>
<li>Line 12: Minify the JavaScript</li>
<li>Line 13: Revision the JavaScript</li>
<li>Line 14-15: Remove the filters, so we have access to all our build blocks again</li>
<li>Line 18: Filter our build blocks to just the CSS</li>
<li>Line 19-21: Minify the CSS removing any and all comments</li>
<li>Line 22: Revision CSS</li>
<li>Line 23-24: Remove the filters again</li>
<li>Line 26: Replace the commented, unprocessed build block in our cshtml files with the processed ones</li>
<li>Line 27-29: Add the revision number to the processed files (note we need to include cshtml files here)</li>
<li>Line 30-32: Replace the original cshtml files. We need to specify a destination here, and as we have views in multiple  folders we can use <a href="http://stackoverflow.com/a/29437418">this technique by </a><a href="http://stackoverflow.com/users/1212682/yiling">Yiling</a> to overwrite a file regardless of its location</li>
</ul>
<p>Phew, there&#8217;s a lot there! If you run this task each build block in our cshtml files will be replaced with a single, minified, revisioned file.</p>
<p>Before:</p>
<p><a href="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/09/gulp-concat-1.png?ssl=1"><img data-recalc-dims="1" decoding="async" loading="lazy" class="alignnone size-large wp-image-5287" src="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/09/gulp-concat-1.png?resize=1024%2C574&#038;ssl=1" alt="gulp-concat-1" width="1024" height="574" srcset="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/09/gulp-concat-1.png?resize=1024%2C574&amp;ssl=1 1024w, https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/09/gulp-concat-1.png?resize=300%2C168&amp;ssl=1 300w, https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/09/gulp-concat-1.png?w=1197&amp;ssl=1 1197w" sizes="auto, (max-width: 1000px) 100vw, 1000px" /></a></p>
<p>After:</p>
<p><a href="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/09/gulp-concat-2.png?ssl=1"><img data-recalc-dims="1" decoding="async" loading="lazy" class="alignnone size-large wp-image-5286" src="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/09/gulp-concat-2.png?resize=1024%2C575&#038;ssl=1" alt="gulp-concat-2" width="1024" height="575" srcset="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/09/gulp-concat-2.png?resize=1024%2C575&amp;ssl=1 1024w, https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/09/gulp-concat-2.png?resize=300%2C169&amp;ssl=1 300w, https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/09/gulp-concat-2.png?w=1200&amp;ssl=1 1200w" sizes="auto, (max-width: 1000px) 100vw, 1000px" /></a></p>
<h3>Running in Release mode</h3>
<p>We only want to run this task when we&#8217;re putting together a release, whether that&#8217;s manual or (much better!) <a href="https://www.cognim.co.uk/know-exactly-what-youve-released-with-git-teamcity-and-octopus/">automated</a>. To do this, add a PreBuildEvent that runs the Gulp task before a release build. Go to the project properties, then Build Events and add the following to &#8220;Pre-build event command line&#8221;:</p>
<pre class="lang:default decode:true ">if $(ConfigurationName) == Release (
   cd $(ProjectDir)
   npm install
   gulp minifyFilesForRelease
)</pre>
<p><a href="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/09/gulp-concat-4.png?ssl=1"><img data-recalc-dims="1" decoding="async" loading="lazy" class="size-large wp-image-5284 aligncenter" src="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/09/gulp-concat-4.png?resize=1024%2C571&#038;ssl=1" alt="gulp-concat-4" width="1024" height="571" srcset="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/09/gulp-concat-4.png?resize=1024%2C571&amp;ssl=1 1024w, https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/09/gulp-concat-4.png?resize=300%2C167&amp;ssl=1 300w, https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/09/gulp-concat-4.png?w=1136&amp;ssl=1 1136w" sizes="auto, (max-width: 1000px) 100vw, 1000px" /></a></p>
<p>This will then run our minifying task only on a Release build.</p>
<p>Lastly, as we are adding the minified files to a &#8220;dist&#8221; folder that doesn&#8217;t exist during development, we&#8217;ll need to add this folder after each build. Open up the csproj for the web project, and at the very end add the following:</p>
<pre class="lang:c# decode:true">&lt;Target Name="AfterBuild"&gt;
    &lt;ItemGroup&gt;
      &lt;Content Include="dist\*.*" /&gt;
    &lt;/ItemGroup&gt;
 &lt;/Target&gt;</pre>
<p><a href="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/09/gulp-concat-3.png?ssl=1"><img data-recalc-dims="1" decoding="async" loading="lazy" class="size-large wp-image-5285 aligncenter" src="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/09/gulp-concat-3.png?resize=1024%2C564&#038;ssl=1" alt="gulp-concat-3" width="1024" height="564" srcset="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/09/gulp-concat-3.png?resize=1024%2C564&amp;ssl=1 1024w, https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/09/gulp-concat-3.png?resize=300%2C165&amp;ssl=1 300w, https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/09/gulp-concat-3.png?w=1136&amp;ssl=1 1136w" sizes="auto, (max-width: 1000px) 100vw, 1000px" /></a></p>
<p>This will include the contents of our dist folder after each build.</p>
<h3>Wrapping up</h3>
<p>We now have an automated process for minifying and concenating files that doesn&#8217;t intefere with the development process. The commit for everything is <a href="https://github.com/edwardridge/Gulp-and-Visual-Studio/commit/a2a5eb8b4df4457db3c1025d2fb7162d39f0c1af" target="_blank">here</a>.</p>
<p>Happy Gulping!</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.cognim.co.uk/gulp-vs-minification/feed/</wfw:commentRss>
			<slash:comments>7</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">5268</post-id>	</item>
		<item>
		<title>Gulp and Visual Studio: Getting SASSy</title>
		<link>https://www.cognim.co.uk/gulp-and-visual-studio-sass/</link>
					<comments>https://www.cognim.co.uk/gulp-and-visual-studio-sass/#comments</comments>
		
		<dc:creator><![CDATA[Darren Hall]]></dc:creator>
		<pubDate>Fri, 04 Sep 2015 08:41:10 +0000</pubDate>
				<category><![CDATA[Gulp]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<guid isPermaLink="false">http://www.cognim.co.uk/?p=5230</guid>

					<description><![CDATA[Getting SASSy with Gulp in Visual Studio In my previous blog I showed you how to set up Visual Studio for use with Gulp. Now I want to show you how you can use it in everyday development, including processing SASS, running tests, linting your code and getting ready for deployment. In this series of [&#8230;]]]></description>
										<content:encoded><![CDATA[<h3>Getting SASSy with Gulp in Visual Studio</h3>
<p>In my <a href="https://www.cognim.co.uk/getting-started-with-gulp-and-vs/" target="_blank">previous blog</a> I showed you how to set up Visual Studio for use with Gulp. Now I want to show you how you can use it in everyday development, including processing SASS, running tests, linting your code and getting ready for deployment.</p>
<p>In this series of posts I&#8217;ll talk about how you can use Gulp with Visual Studio to run your common front end tasks:</p>
<ul>
<li><a href="https://www.cognim.co.uk/getting-started-with-gulp-and-vs/" target="_blank">Part 1: Setting up Gulp with Visual Studio</a></li>
<li><span style="color: #000000;"><a href="https://www.cognim.co.uk/gulp-and-visual-studio-sass/" target="_blank">Part 2: Getting SASSy</a></span></li>
<li><span style="color: #999999;">Part 3: Deployment: minification and concatenation</span></li>
<li><span style="color: #999999;">Part 4: Code quality: tests and linting</span></li>
<li><span style="color: #999999;">Part 5: Thoughts on Gulp</span></li>
</ul>
<p>The code I&#8217;ll be showing is based off a standard MVC 5 project. If you want the code I&#8217;ve created a GitHub project for it <a href="https://github.com/edwardridge/Gulp-and-Visual-Studio/">here.</a></p>
<h3>Basic Gulpfile + package.json</h3>
<p>Throughout these examples I&#8217;ll be using <a href="https://www.npmjs.com/package/gulp-load-plugins" target="_blank">gulp-load-plugins</a> &#8211; an awesome meta-plugin that takes all your Gulp plugins from your package.json and attaches them to an object. At the start, the package.json file looks like this:</p>
<pre class="lang:js decode:true" title="package.json">{
  "scripts": {"install": "echo Done"},
    
  "devDependencies": {
    "gulp": "~3.9.0",
    "gulp-load-plugins": "~0.10.0"
  } 
}
</pre>
<p>N.B. I like outputting something to the console after installing packages as the default is to not output anything, which can be a little confusing!</p>
<p>The basic gulpfile looks like this:</p>
<pre class="lang:js decode:true">var gulp = require('gulp');
var plugins = require('gulp-load-plugins')();

gulp.task('default', ['']);</pre>
<p>Now, any plugins we add to our package.json will immediately be available on the plugins object.</p>
<h3>Processing SASS</h3>
<p>I&#8217;m a big fan of <a href="http://sass-lang.com/" target="_blank">SASS</a> for developing CSS as it helps keep my CSS clean and <a href="https://en.wikipedia.org/wiki/Don't_repeat_yourself" target="_blank">DRY</a>. SASS files need processing, and Gulp can do this for you. As a bonus, we can add <a href="http://code.tutsplus.com/tutorials/source-maps-101--net-29173" target="_blank">sourcemaps</a> so that when we inspect the page in Firefox, Chrome or IE 11 we refer back to the original SASS rather than the processed CSS. As a double bonus, we can use <a href="http://livereload.com/" target="_blank">LiveReload</a> to reload the page and automatically see our changes whenever we make a change to the SASS (note with LiveReload on Windows you&#8217;ll need the <a href="https://chrome.google.com/webstore/detail/livereload/jnihajbhpnppcggbcgedagnkighmdlei?hl=en" target="_blank">Chrome extension</a> for the best experience).</p>
<p>First off, we add the SASS file. For this demo project, based on MVC 5, this is simple &#8211; rename the Site.css file to Site.scss. As SASS is a superset of CSS, all valid CSS is valid SASS.</p>
<p>Next, we add the plugins we&#8217;ll need to the package.json:</p>
<pre class="lang:js decode:true">{
  "scripts": { "install": "echo Done" },
    
  "devDependencies": {
    "gulp": "~3.9.0",
    "gulp-load-plugins": "~0.10.0",
    "gulp-sass": "~2.0.4",
    "gulp-sourcemaps": "~1.5.2",
    "gulp-autoprefixer": "~2.3.1",
    "gulp-livereload": "~3.8.0"
  } 
}</pre>
<p>Next, add the gulp tasks &#8211; one to process the SASS into CSS, and another to watch the SASS files and recompile whenever we make a change:</p>
<pre class="nums:true lang:js decode:true" title="gulpfile.js">var gulp = require('gulp');
var plugins = require('gulp-load-plugins')();

gulp.task('sass', function () {
    gulp.src('./Content/*.scss')
        .pipe(plugins.sourcemaps.init())
        .pipe(plugins.sass())
        .pipe(plugins.autoprefixer())
        .pipe(plugins.sourcemaps.write())
        .pipe(gulp.dest('./Content'))
        .pipe(plugins.livereload())
    ;
});

gulp.task('watch-sass', function () {
    plugins.livereload.listen();
    gulp.watch('./Content/*.scss', ['sass']);
});

gulp.task('default', ['watch-sass']);</pre>
<p>Here&#8217;s a line by line breakdown of what is happening within our &#8216;sass&#8217; task:</p>
<ul>
<li>Line 5: Grab all our SASS files from the Content folder. At the moment this is just the Site.scss file, but as we build this up we&#8217;ll want to add different SASS files for different parts of the project</li>
<li>Line 6: Initialise the sourcemaps. Note that <strong>this must be done before they get processed</strong></li>
<li>Line 7: Process the SASS to generate the CSS</li>
<li>Line 8: Use <a href="https://github.com/postcss/autoprefixer" target="_blank">autoprefixer</a> to add any vendor-specific prefixes to the CSS. The defaults for the <a href="https://www.npmjs.com/package/gulp-autoprefixer" target="_blank">plugin</a> target any browser with &gt;1% share, which is eminently sensible</li>
<li>Line 9: Insert the sourcemaps into the generated CSS</li>
<li>Line 10: Write the generated CSS back to the Content directory</li>
<li>Line 11: Notify LiveReload that we&#8217;ve made changes</li>
</ul>
<p>The &#8216;watch-sass&#8217; task simply tells LiveReload to start listening, watches our SASS files for any changes, and when they are changed runs our &#8216;sass&#8217; task. This watch has also been added to the default task, so will run automatically. Now, when we make a change to the Site.scss file the css will automatically get generated, and we get all the other goodness from our other plugins too.</p>
<h4>Sourcemaps</h4>
<p>Below I&#8217;ve changed the Site.scss file so that the text in the Jumbtron is blue, and have inspected it in Chrome. You&#8217;ll notice the red box in the inspector refers to the Site.scss file (not the generated Site.css file) , thanks to sourcemaps.</p>
<p><a href="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/gulp-process-files-1.png?ssl=1"><img data-recalc-dims="1" decoding="async" loading="lazy" class="alignnone size-large wp-image-5242" src="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/gulp-process-files-1.png?resize=910%2C1024&#038;ssl=1" alt="gulp-process-files-1" width="910" height="1024" srcset="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/gulp-process-files-1.png?resize=910%2C1024&amp;ssl=1 910w, https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/gulp-process-files-1.png?resize=267%2C300&amp;ssl=1 267w, https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/gulp-process-files-1.png?w=960&amp;ssl=1 960w" sizes="auto, (max-width: 910px) 100vw, 910px" /></a></p>
<h4>LiveReload</h4>
<p>If you open the site in Chrome and start the LiveReload extension, any time a change is made to the SASS the web page will automatically reload with the changes. Here the color of the jumbotron text is switching between red and blue, and automatically updating:</p>
<p><a href="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/gulp-live-reload.gif?ssl=1"><img data-recalc-dims="1" decoding="async" loading="lazy" class="alignnone size-full wp-image-5241" src="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/gulp-live-reload.gif?resize=800%2C378&#038;ssl=1" alt="gulp-live-reload" width="800" height="378" /></a></p>
<h3>Wrapping up</h3>
<p>So there we are! Automatic processing of SASS with Gulp, along with a few other goodies. The commit for eveything I&#8217;ve shown is <a href="https://github.com/edwardridge/Gulp-and-Visual-Studio/commit/8d00491f141298732887df2b87c36a569bc165de" target="_blank">here. </a></p>
<p>One thing to note is that in this task we didn&#8217;t do anything minification to the CSS &#8211; I&#8217;ll come on to that in my next post.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.cognim.co.uk/gulp-and-visual-studio-sass/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">5230</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>Power BI &#8211; Quick Tip. Percent of Total</title>
		<link>https://www.cognim.co.uk/power-bi-quick-tip-percent-of-total/</link>
					<comments>https://www.cognim.co.uk/power-bi-quick-tip-percent-of-total/#comments</comments>
		
		<dc:creator><![CDATA[Darren Hall]]></dc:creator>
		<pubDate>Tue, 18 Aug 2015 15:36:35 +0000</pubDate>
				<category><![CDATA[Power BI]]></category>
		<guid isPermaLink="false">http://www.cognim.co.uk/?p=5203</guid>

					<description><![CDATA[If you need to add &#8216;Percent of Total&#8217; to your charts in Power BI, here&#8217;s how.. Microsoft&#8217;s Power BI is excellent.  It is so easy to get up and running with data coming from a multitude of places. Out of the box you can easily show facts and figures related to your data.  One thing [&#8230;]]]></description>
										<content:encoded><![CDATA[<h3>If you need to add &#8216;Percent of Total&#8217; to your charts in Power BI, here&#8217;s how..</h3>
<p>Microsoft&#8217;s Power BI is excellent.  It is so easy to get up and running with data coming from a multitude of places. Out of the box you can easily show facts and figures related to your data.  One thing it currently misses though is a &#8216;percent of total&#8217; aggregation for measures.</p>
<p>Recently I wanted to show browser usage for visitors to a web based questionnaire. The client had asked to see the browsers ordered by popularity with their respective percentage share displayed.</p>
<p>The SQL Server table &#8216;Dim_Respondents&#8217; had the following columns available: LocalRespondentId (unique integer), Browser (text), DateStarted (Date) plus some foreign key references to other tables I could filter by such as Questionnaire Name, Questionnaire Status etc.  It was easy to get the browser count with a horizontal bar chart as follows</p>
<p><a href="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/SimpleBrowserChart.png?ssl=1"><img data-recalc-dims="1" decoding="async" loading="lazy" class="aligncenter wp-image-5215 size-full" src="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/SimpleBrowserChart.png?resize=800%2C870&#038;ssl=1" alt="Simple Power BI chart by count" width="800" height="870" srcset="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/SimpleBrowserChart.png?w=800&amp;ssl=1 800w, https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/SimpleBrowserChart.png?resize=276%2C300&amp;ssl=1 276w" sizes="auto, (max-width: 800px) 100vw, 800px" /></a></p>
<p>Notice how I have just added Browser to the Axis and &#8216;Count of LocalRespondentId&#8217; to the Value.  The difficulty comes in trying to get percentages because you can only aggregate your data by sum, average, minimum, maximum and count.  The closest you can come is a 100% stacked bar chart;</p>
<p><a href="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/BrowserStackedChart.png?ssl=1"><img data-recalc-dims="1" decoding="async" loading="lazy" class="aligncenter wp-image-5216 size-full" src="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/BrowserStackedChart.png?resize=800%2C870&#038;ssl=1" alt="Power BI stacked bar chart" width="800" height="870" srcset="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/BrowserStackedChart.png?w=800&amp;ssl=1 800w, https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/BrowserStackedChart.png?resize=276%2C300&amp;ssl=1 276w" sizes="auto, (max-width: 800px) 100vw, 800px" /></a></p>
<p>but with a lot of browsers that is not a workable option.  Luckily Power BI lets us create our own measures using DAX. To do so , you need to right-click on your data table and select &#8216;New Measure&#8217;.</p>
<p><a href="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/NewMeasure.png?ssl=1"><img data-recalc-dims="1" decoding="async" loading="lazy" class="aligncenter wp-image-5217 size-full" src="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/NewMeasure.png?resize=365%2C374&#038;ssl=1" alt="Power BI - Create a new measure" width="365" height="374" srcset="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/NewMeasure.png?w=365&amp;ssl=1 365w, https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/NewMeasure.png?resize=293%2C300&amp;ssl=1 293w" sizes="auto, (max-width: 365px) 100vw, 365px" /></a></p>
<p>You can then enter your measure name and a DAX expression. (<a href="https://support.powerbi.com/knowledgebase/articles/554619-dax-basics-in-power-bi-desktop">See &#8216;DAX basics in Power BI Desktop&#8217;</a> for basic DAX information). For our purposes we would like to know the number of respondents with a particular browser divided by the total number of respondents.  Before I create the measure though we need to consider that it is highly likely that this chart will have been further filtered &#8211; maybe by date or something else. Our calculation must take that into account.  The easiest way to express it is to say that we need the number of respondents for a particular browser taking into account all applied filters divided by the number of respondents for all browsers taking into account all applied filters (sorry, I know that is a long-winded statement, but bear with me).</p>
<p>In DAX we can write &#8216;<span class="lang:c# decode:true  crayon-inline ">COUNTA(Dim_Respondents[Browser])</span> &#8216; for the first part which is simple enough (basically counts the number of values in a column after all filters have been applied &#8211; and remember that we have Browser on an axis so we are effectively filtering by Browser for each chart position), but the second part is a little more tricky. We can solve it by using &#8216;<span class="lang:c# decode:true  crayon-inline ">CALCULATE(COUNTROWS(Dim_Respondents),ALL(Dim_Respondents[Browser]))</span> &#8216; which says calculate the first expression &#8216;COUNTROWS(Dim_Respondents)&#8217; for the second filtered data set &#8216;ALL(Dim_Respondents[Browser])&#8217;. The &#8216;ALL(..)&#8217; statement clears the filter for the mentioned column so in our case ignores the axis filter on Browser and gives us a total count. The whole expression is</p>
<pre class="lang:c# decode:true ">Browser % = COUNTA(Dim_Respondents[Browser]) / CALCULATE(COUNTROWS(Dim_Respondents),ALL(Dim_Respondents[Browser]))</pre>
<p>Note that I haven&#8217;t multiplied the answer by 100 because it is better to click your new measure and set its format type to &#8216;Percentage&#8217; in the Modeling tab.</p>
<p><a href="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/FormatAsPercentage.png?ssl=1"><img data-recalc-dims="1" decoding="async" loading="lazy" class="aligncenter wp-image-5218 size-full" src="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/FormatAsPercentage.png?resize=422%2C123&#038;ssl=1" alt="Power BI - Format measure as percentage" width="422" height="123" srcset="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/FormatAsPercentage.png?w=422&amp;ssl=1 422w, https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/FormatAsPercentage.png?resize=300%2C87&amp;ssl=1 300w" sizes="auto, (max-width: 422px) 100vw, 422px" /></a></p>
<p>You can now replace the count of LocalrespondentId directly with your new measure and set your chart to sort by the percentage;</p>
<p><a href="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/ChartByPercent.png?ssl=1"><img data-recalc-dims="1" decoding="async" loading="lazy" class="aligncenter wp-image-5219 size-full" src="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/ChartByPercent.png?resize=885%2C900&#038;ssl=1" alt="Power BI - Chart by Percentage" width="885" height="900" srcset="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/ChartByPercent.png?w=885&amp;ssl=1 885w, https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/ChartByPercent.png?resize=295%2C300&amp;ssl=1 295w" sizes="auto, (max-width: 885px) 100vw, 885px" /></a></p>
<p>One last nice touch is to put the percentages on the graph by setting Data Labels to &#8216;on&#8217;.</p>
<p><a href="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/ChartWithDataLabels.png?ssl=1"><img data-recalc-dims="1" decoding="async" loading="lazy" class="aligncenter wp-image-5220 size-full" src="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/ChartWithDataLabels.png?resize=885%2C900&#038;ssl=1" alt="Power BI - Chart with data labels" width="885" height="900" srcset="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/ChartWithDataLabels.png?w=885&amp;ssl=1 885w, https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/ChartWithDataLabels.png?resize=295%2C300&amp;ssl=1 295w" sizes="auto, (max-width: 885px) 100vw, 885px" /></a></p>
<p>Hope this helps!</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.cognim.co.uk/power-bi-quick-tip-percent-of-total/feed/</wfw:commentRss>
			<slash:comments>4</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">5203</post-id>	</item>
		<item>
		<title>Getting started with Gulp in Visual Studio 2013 and 2015</title>
		<link>https://www.cognim.co.uk/getting-started-with-gulp-and-vs/</link>
					<comments>https://www.cognim.co.uk/getting-started-with-gulp-and-vs/#comments</comments>
		
		<dc:creator><![CDATA[Darren Hall]]></dc:creator>
		<pubDate>Fri, 07 Aug 2015 09:56:50 +0000</pubDate>
				<category><![CDATA[Gulp]]></category>
		<category><![CDATA[Node]]></category>
		<category><![CDATA[NodeJs]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<guid isPermaLink="false">http://www.cognim.co.uk/?p=5148</guid>

					<description><![CDATA[In the last few years a rich set of front end development tools has emerged for building complex web applications. Gulp in particular has taken off in a huge way. However, .NET development is lagging when it comes to adoption of these tools. This is all set to change, especially with the release of ASP.NET 5 where Gulp will become [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>In the last few years a rich set of front end development tools has emerged for building complex web applications. Gulp in particular has taken off in a huge way. However, .NET development is lagging when it comes to adoption of these tools. This is all set to change, especially with the release of ASP.NET 5 where Gulp will become part of the standard project setup. But, what is Gulp, and how do you use it in Visual Studio?</p>
<h2>What is Gulp?</h2>
<p><a href="http://gulpjs.com/">Gulp</a> is a build process for front end development. Gulp automates all of the repetitive tasks you have to do to prepare your front end files (such as JavaScript and CSS) for development and deployment. Gulp uses small, simple, composable plugins to that let you define exactly what happens to the files in your build.</p>
<h4>Common tasks you can get Gulp to automate</h4>
<ul>
<li>Minifying JavaScript/CSS/images</li>
<li>Concatenating JavaScipt/CSS files</li>
<li>Running JavaScript lint tooling</li>
<li>Compiling your SASS/LESS</li>
<li>Compiling TypeScript/CoffeeScript</li>
<li>Running JavaScript tests (eg Karma, Jasmine, Mocha)</li>
<li>Transpiling ES6 into ES5</li>
<li>Minifying Angular without breaking Dependency Injection</li>
<li>&#8230;and many more</li>
</ul>
<p>To install and use Gulp, you&#8217;ll need npm. Which begs the question&#8230;</p>
<h4>What is npm?</h4>
<p>npm is the package manager for <span class="tooltips " style="" title="Node is a runtime environment built in JavaScript. It is somewhat equivalent to the .NET CLR - and for getting set up it is not necessary to know much more than that"><span style="text-decoration: underline;">Node</span></span>. It&#8217;s a front-end equivalent to NuGet &#8211; you can use it to install and update packages and their dependencies. We&#8217;ll be using it to install Gulp and all its plugins.</p>
<h2>How to set up Gulp in Visual Studio</h2>
<p>Currently you can set up Gulp in Visual Studio 2013 and 2015. If you have 2015, skip the first 3 points as they come with Visual Studio 2015. Note that the screenshots are taken using Visual Studio 2013 with a standard MVC 5 project template.</p>
<ol>
<li>
<h4>Install Node/npm.</h4>
<p>You can install Node <a href="https://nodejs.org/" target="_blank">from here</a>. What we&#8217;re really after here isn&#8217;t Node, it&#8217;s npm (which comes installed with Node).</li>
<li>
<h4>Install Gulp.</h4>
<p>After installing npm, open up a Console window, and enter:</p>
<blockquote><p>npm install gulp -g</p></blockquote>
<p>This will install Gulp. The &#8220;-g&#8221; option installs it globally, so you can run Gulp commands anywhere.</li>
<li>
<h4>Install the Grunt Launcher Visual Studio Extension.</h4>
<span class="tooltips " style="" title="Grunt is another build process for front end development. Grunt favours configuration, while Gulp favours code. I am not going to get into the merits of each here!"><a href="https://visualstudiogallery.msdn.microsoft.com/dcbc5325-79ef-4b72-960e-0a51ee33a0ff" target="_blank">Grunt Launcher</a></span> provides menu options to install npm packages and run Gulp tasks from within Visual Studio.</li>
<li>
<h4>Add Gulp to your project</h4>
<p>At the root of your web project, add a new JSON file called package.json with the following contents:</p>
<pre class="lang:js decode:true">{
    "devDependencies": {
        "gulp":  "3.9.0"
    }   
}
</pre>
<p><a href="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/gulp-blog-1.png?ssl=1"><img data-recalc-dims="1" decoding="async" loading="lazy" class="  wp-image-5173 aligncenter" src="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/gulp-blog-1.png?resize=889%2C420&#038;ssl=1" alt="gulp-blog-1" width="889" height="420" srcset="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/gulp-blog-1.png?resize=1024%2C484&amp;ssl=1 1024w, https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/gulp-blog-1.png?resize=300%2C142&amp;ssl=1 300w, https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/gulp-blog-1.png?w=1379&amp;ssl=1 1379w" sizes="auto, (max-width: 889px) 100vw, 889px" /></a> The <span class="tooltips " style="" title="Note a standard package.json will contain other information such as a description, author and a repository for the code"><span style="text-decoration: underline;">package.json</span></span> is a npm file we use to define metadata about our project. Here we are listing the (front end) dependencies for developing our project &#8211; this will include plugins for running Gulp tasks. For now, we just want to add Gulp to our project.</p>
<p>Now, right-click on the package.json file and click &#8220;NPM install packages&#8221; (if you&#8217;ve installed Grunt Launcher) to add it to our project.</p>
<p><a href="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/NPM-install-vid.gif?ssl=1"><img data-recalc-dims="1" decoding="async" loading="lazy" class=" size-full wp-image-5171 aligncenter" src="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/NPM-install-vid.gif?resize=784%2C600&#038;ssl=1" alt="NPM install vid" width="784" height="600" /></a></p>
<p>You can ignore those warnings for now &#8211; you can add the metadata it is complaining about later.</p>
<p>This will add a node_modules folder in your project folder, where all our npm packages will be kept. Within that will be Gulp.</p>
<p><a href="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/gulp-blog-3.png?ssl=1"><img data-recalc-dims="1" decoding="async" loading="lazy" class="alignnone size-full wp-image-5179" src="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/gulp-blog-3.png?resize=334%2C423&#038;ssl=1" alt="gulp-blog-3" width="334" height="423" srcset="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/gulp-blog-3.png?w=334&amp;ssl=1 334w, https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/gulp-blog-3.png?resize=237%2C300&amp;ssl=1 237w" sizes="auto, (max-width: 334px) 100vw, 334px" /></a></li>
<li>
<h4>Add a Gulpfile</h4>
<p>Next we want to add a Gulpfile, where we will define the steps for our build process. Add a JavaScript file called gulpfile.js to the root of the project, and add the following code:</p>
<pre class="striped:true lang:js decode:true">var gulp = require('gulp');

gulp.task('default', function () {
    console.log('Hello world!');
});
</pre>
<p>&nbsp;</p>
<p><a href="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/gulp-blog-2.png?ssl=1"><img data-recalc-dims="1" decoding="async" loading="lazy" class="alignnone  wp-image-5174" src="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/gulp-blog-2.png?resize=884%2C418&#038;ssl=1" alt="gulp-blog-2" width="884" height="418" srcset="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/gulp-blog-2.png?resize=1024%2C484&amp;ssl=1 1024w, https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/gulp-blog-2.png?resize=300%2C142&amp;ssl=1 300w, https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/gulp-blog-2.png?w=1379&amp;ssl=1 1379w" sizes="auto, (max-width: 884px) 100vw, 884px" /></a><br />
In line 1 we load Gulp. On line 3 we define a new Gulp task. A task is a step, or a set of steps, that Gulp will execute. A task takes a function that it will run &#8211; in this case we simply log to the console. A task also has a name &#8211; here it&#8217;s called &#8220;default&#8221; and as you might guess it runs automatically when we run Gulp.</p>
<p>We can now run this task by right-clicking on the gulpfile.js and clicking the &#8220;Gulp&#8221; menu item added by the Grunt Launcher extension.</p>
<p><a href="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/Run-Gulpfile-Vid.gif?ssl=1"><img data-recalc-dims="1" decoding="async" loading="lazy" class="alignnone size-full wp-image-5172" src="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/Run-Gulpfile-Vid.gif?resize=764%2C600&#038;ssl=1" alt="Run Gulpfile Vid" width="764" height="600" /></a></p>
<p>&nbsp;</p>
<p>Now Visual Studio is running our task, and outputting &#8220;Hello world!&#8221; to the output window. We&#8217;re done! Well, not quite&#8230;</li>
</ol>
<h2>Doing something actually useful</h2>
<p>Hello World is all well and good, but what about automating something useful? One common task is minifying CSS files, and that&#8217;s what we&#8217;ll do here.</p>
<ol>
<li>
<h4>Add the plugins</h4>
<p>Change your package.json file to the following:</p>
<pre class="striped:true lang:js decode:true">{
    "devDependencies": {
        "gulp": "3.9.0",
        "gulp-uglifycss": "1.0.4",
        "gulp-rename": "1.2.2"
    }
}
</pre>
<p>Here we&#8217;ve added two new packages, gulp-uglifycss (which minifies css) and gulp-rename (which renames files passed into it). We can now use these in our task.</li>
<li>
<h4>Modify the task</h4>
<p>Change the gulpfile.js to the following:</p>
<pre class="striped:true nums:true nums-toggle:true lang:js decode:true">var gulp = require('gulp'),
    uglifycss = require('gulp-uglifycss'),
    rename = require('gulp-rename');

gulp.task('default', function () {
    return 
         gulp.src(['./Content/*.css', '!./Content/*.min.css'])
        .pipe(uglifycss())
        .pipe(rename({
            suffix: ".min",
            extname: ".css"
        }))
        .pipe(gulp.dest('./Content'));
});
</pre>
<p>Here&#8217;s a line by line breakdown of what the task is doing:<br />
Line 1-3: Add references to the plugins we just added in our package.json<br />
Line 7: Get the CSS files from our Content directory (excluding any .min files)<br />
Line 8: Pipe (i.e. pass) the files to gulp-uglifycss, which minifies them<br />
Line 9-12:  Rename the minified files to include a .min suffix<br />
Line 13: Save the minified files back to our Content folder</p>
<p>Now, we can run this task to automatically minify all our CSS files.</p>
<p>And there we are! We now have a process that will save us from a repetitive boring task, and we can build on this to automate lots of other tasks.</li>
</ol>
<h2>Next steps</h2>
<p>Note that for brevity I have excluded everything that isn&#8217;t necessary for getting Gulp set up in Visual Studio. There are a few things you will want to do next to get fully set up:</p>
<ol>
<li>
<h4>Install the Task Runner Explorer extension</h4>
<p>You can install the <a href="https://visualstudiogallery.msdn.microsoft.com/8e1b4368-4afb-467a-bc13-9650572db708" target="_blank">Task Runner Explorer</a> Visual Studio extension to run tasks automatically on each build or every time the project opens.</li>
<li>
<h4>Install NPM Package Intellisense</h4>
<p><a href="https://visualstudiogallery.msdn.microsoft.com/65748cdb-4087-497e-a394-2e3449c8e61e" target="_blank">NPM Package Intellisense</a> gives you package intellisense when installing packages and plugins.</li>
<li>
<h4>Add more plugins</h4>
<p>Nearly any task you want to automate will <a href="http://gulpjs.com/plugins" target="_blank">have a plugin here</a> &#8211; there are over 1500 at time of writing.</li>
</ol>
<p>Happy Gulping!</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.cognim.co.uk/getting-started-with-gulp-and-vs/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">5148</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>5 Lesser Known Reasons To Upgrade To Visual Studio 2015</title>
		<link>https://www.cognim.co.uk/5-lesser-known-reasons-to-upgrade-to-visual-studio-2015/</link>
					<comments>https://www.cognim.co.uk/5-lesser-known-reasons-to-upgrade-to-visual-studio-2015/#respond</comments>
		
		<dc:creator><![CDATA[Darren Hall]]></dc:creator>
		<pubDate>Sat, 01 Aug 2015 14:00:10 +0000</pubDate>
				<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[Visual Studio 2015]]></category>
		<guid isPermaLink="false">http://www.cognim.co.uk/?p=5086</guid>

					<description><![CDATA[Searching the web there are plenty of articles about Visual Studio 2015 and all that it brings with it, but you may have to dig down to get to some of the new features that will be instantly of help in your everyday activities.  Here are the five lesser known ones that most interest me&#8230; [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>Searching the web there are plenty of articles about Visual Studio 2015 and all that it brings with it, but you may have to dig down to get to some of the new features that will be instantly of help in your everyday activities.  Here are the five lesser known ones that most interest me&#8230;</p>
<h3>Debugging Lambda expressions</h3>
<p>This has been a long time coming. Ever had to debug a long lambda expression only to find you can&#8217;t evaluate it in the Watch windows? Well now you can and more.  <a href="http://www.dirkstrauss.com/programming/debugging-lambda-expressions-in-visual-studio-2015" target="_blank">Dirk Strauss has written a good blog about it here.</a></p>
<p><a href="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/Debug-Lambda.png?ssl=1"><img data-recalc-dims="1" decoding="async" loading="lazy" class="aligncenter wp-image-5090 size-full" src="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/Debug-Lambda.png?resize=550%2C362&#038;ssl=1" alt="Debug Lambda Expressions" width="550" height="362" srcset="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/Debug-Lambda.png?w=550&amp;ssl=1 550w, https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/Debug-Lambda.png?resize=300%2C197&amp;ssl=1 300w" sizes="auto, (max-width: 550px) 100vw, 550px" /></a></p>
<h3>Javascript and HTML Intellisense and Usage Improvements</h3>
<p>Intellisense support has been added for Angular, BootStrap CSS and ARIA in the html editor as well as intellisense for ReactJS, AngularJS, RequireJS and ECMAScript 2015 (aka ECMAScript 6) in the javascript editor.  Oh, let&#8217;s throw in a Json editor too!</p>
<p><a href="http://webtooling.visualstudio.com/frameworks/client-side/" target="_blank">See VisualStudio.com&#8217;s article about the HTML editor intellisense here<br />
</a><br />
<a href="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/Angular-Intellisense.gif?ssl=1"><img data-recalc-dims="1" decoding="async" loading="lazy" class="aligncenter wp-image-5091 size-full" src="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/Angular-Intellisense.gif?resize=224%2C204&#038;ssl=1" alt="Angular Intellisense in the HTML Editor" width="224" height="204" /></a></p>
<p><a href="http://blogs.msdn.com/b/visualstudio/archive/2015/06/10/javascript-editor-improvements-in-visual-studio-2015.aspx" target="_blank">The Visual Studio blog has more about the javascript intellisense here<br />
</a><br />
<a href="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/ES2015-Intellisense.png?ssl=1"><img data-recalc-dims="1" decoding="async" loading="lazy" class="aligncenter wp-image-5092 size-full" src="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/ES2015-Intellisense.png?resize=501%2C180&#038;ssl=1" alt="ES2015 Intellisens in Visual Studio 2015" width="501" height="180" srcset="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/ES2015-Intellisense.png?w=501&amp;ssl=1 501w, https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/ES2015-Intellisense.png?resize=300%2C108&amp;ssl=1 300w" sizes="auto, (max-width: 501px) 100vw, 501px" /></a></p>
<p>Also, Bower and NPM intellisense, helped by the JSON editor. <a href="http://www.dotnetjalps.com/2015/01/intellisense--bower-and-npm-visualstudio2015.html" target="_blank">Jalpesh Vadgama writes it up in this blog article<br />
</a><br />
<a href="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/intellisense-for-bower.png?ssl=1"><img data-recalc-dims="1" decoding="async" loading="lazy" class="aligncenter wp-image-5093 size-full" src="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/intellisense-for-bower.png?resize=618%2C458&#038;ssl=1" alt="Bower intellisense in Visual Studio 2015" width="618" height="458" srcset="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/intellisense-for-bower.png?w=618&amp;ssl=1 618w, https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/intellisense-for-bower.png?resize=300%2C222&amp;ssl=1 300w" sizes="auto, (max-width: 618px) 100vw, 618px" /></a></p>
<h3>GIT support improvements and additions</h3>
<p>I tend to work primarily in Visual Studio now when it comes to source control, however I have to switch out occasionally when I need more info (we use <a href="https://www.atlassian.com/software/sourcetree/overview">Atlassian&#8217;s SourceTree</a>). With the new improvements in Visual Studio 2015, I can stay in VS. <a href="https://www.visualstudio.com/en-us/news/vs2015-vs.aspx#VersionControl">VisualStudio.com mention the main features here<br />
</a><br />
<a href="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/GIT-Branching.png?ssl=1"><img data-recalc-dims="1" decoding="async" loading="lazy" class="aligncenter wp-image-5095 size-full" src="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/GIT-Branching.png?resize=527%2C368&#038;ssl=1" alt="Visual Studio 2015 improves GIT support" width="527" height="368" srcset="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/GIT-Branching.png?w=527&amp;ssl=1 527w, https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/GIT-Branching.png?resize=300%2C209&amp;ssl=1 300w" sizes="auto, (max-width: 527px) 100vw, 527px" /></a></p>
<h3>Enterprise Single Sign On with Azure Active Directory</h3>
<p>If you are creating a website for users that are within your domain and you are using Azure Active Directory you can now add Enterprise Single Sign On at any point in your development by right-clicking on your application and selecting &#8216;Configure Azure AD Authentication&#8217;. This will bring up a wizard that will allow you to the specify the domain from a list of known domains.  The wizard will register your application with that Active Directory and configure your application to prompt for sign-in.</p>
<p><a href="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/Azure-AD-Sign-In-Wizard.png?ssl=1"><img data-recalc-dims="1" decoding="async" loading="lazy" class="aligncenter wp-image-5096 size-full" src="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/Azure-AD-Sign-In-Wizard.png?resize=804%2C551&#038;ssl=1" alt="Visual Studio 2015 Azure AD Sign In WIzard" width="804" height="551" srcset="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/Azure-AD-Sign-In-Wizard.png?w=804&amp;ssl=1 804w, https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/Azure-AD-Sign-In-Wizard.png?resize=300%2C206&amp;ssl=1 300w" sizes="auto, (max-width: 804px) 100vw, 804px" /></a></p>
<h3>Intellitest &#8211; if you have to support or refactor legacy code with no tests, this will help.</h3>
<p>I suspect this is going to be a bit of a love it or hate it addition. Personally I love it for the reasons below.<br />
Intellitest grew out of Pex, a Microsoft Research Project. It basically boils down to a way of automatically creating Unit Tests for your code that exercise every line (if it is actually possible to exercise every line!). It does this by auto constructing objects that are required parameters for the method under test and then calling that method with many variations of the parameters.  There seems to be a bit of an initial backlash from some quarters as it is definitely NOT a good way to quickly construct Unit Tests as a box ticking exercise for your shiny new project.  However its great strength lies in legacy projects that need to be refactored / upgraded / fiddled with in some way. I have inherited many of these over the years and trying to work out the behaviour of a particularly messy method is never easy.  Now I can point Intellitest at it and make sure my replacement method mimics the results. Note that this is otherwise known as <a href="https://en.wikipedia.org/wiki/Characterization_test">Characterisation Testing</a>.</p>
<p><a href="https://msdn.microsoft.com/en-us/library/dn823749.aspx">MSDN has an article about using Intellitest<br />
</a><br />
<a href="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/Intellitest.png?ssl=1"><img data-recalc-dims="1" decoding="async" loading="lazy" class="aligncenter wp-image-5097 size-full" src="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/Intellitest.png?resize=682%2C546&#038;ssl=1" alt="Intellistest in Visual Studio 2015 brings help for legacy software" width="682" height="546" srcset="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/Intellitest.png?w=682&amp;ssl=1 682w, https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/Intellitest.png?resize=300%2C240&amp;ssl=1 300w" sizes="auto, (max-width: 682px) 100vw, 682px" /></a></p>
<p>Overall a great set of features that should really help save time. <a href="https://www.cognim.co.uk/more-concise-more-readable-c-6-0-real-world-gains/">You can also see my blog about improvements that came with C# 6.0</a></p>
<p>Have fun!</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.cognim.co.uk/5-lesser-known-reasons-to-upgrade-to-visual-studio-2015/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">5086</post-id>	</item>
	</channel>
</rss>
