Tuesday, October 30, 2018

Find a Stored Procedure By Searching Its Contents

Today I had to do something for the first time in a while and it took me a moment to remember the syntax so I figured I'd better write a post about it so that doesn't happen again. In SQL Server you can search the contents of a stored procedure. This is useful when you're trying to figure out which stored procedure(s) update(s) a particular field, for example. I'm sure there are other uses, but I want to keep this as short as possible.

Basically what you can do is use the built-in sys tables to search the text (contents) of a stored procedure. It's pretty straightforward so I'll just get right to the code. This simple SQL statement will get the names of any stored procedures that use the field "CurrentMarriageStatus".
SELECT DISTINCT so.[name] FROM sysobjects so INNER JOIN syscomments sc ON so.id = sc.id WHERE sc.[text] LIKE '%CurrentMarriageStatus%'


That's it! Then you can take the results and go through them one at a time to see how they're using the field you searched for.

Friday, October 5, 2018

Git: Forcing Local to Match Remote

Every now and then I've found myself making changes directly on a branch that can't be updated from local to remote. Let's say we have the "master" branch and from that we create the "working" branch. It is impossible (by rules) to update "master" directly. Instead, we must create a pull request so that our code may be reviewed. But sometimes I've already done the work on "master", committed my changes locally on "master" and tried to push them to the remote repository. That, of course, leads to an error message along the lines of "Pushes to this branch are not permitted; you must use a pull request to update this branch." That's exactly the error message we want to see, but now I'm stuck with code in the wrong branch and my "master" doesn't match the remote "master". Here's the super easy way to fix that.

git fetch --prune
git checkout -b new-branch-with-my-changes
git push --set-upstream origin new-branch-with-my-changes
git checkout master
git reset --hard origin/master

These simple steps will 1) create a new branch called new-branch-with-my-changes on the local and remote repositories, and 2) overwrite the local master branch to match the remote master branch.

Super simple, but I always have to Google it so now it's here for future me to find it more easily next time.

Tuesday, July 17, 2018

Angular Error: Illegal state: Could not load the summary for directive SomeComponent

Apparently I had encountered this issue before, but it came up again and I had to research it again (I only know I came across it before because the link to the answer on SO was purple).

When your tests fail with this message, make sure you're including the component under test (SomeComponent) in the declarations of the TestBed. It's super simple, but apparently it's bitten me at least twice.

Wednesday, July 11, 2018

Angular Tests: Error during cleanup of component

I've come across this error quite a few times and it always takes me a few minutes to remember how to overcome it so I figured I should write about it.

This error typically arises for me when I subscribe to an observable in my ngOnInit, but then don't unsubscribe in ngOnDestroy. That's it. If you (or Future Me) start seeing this error - followed by a ton of text written to the console - you may want to check if you've added a .subscribe in ngOnInit and then unsubscribe in your ngOnDestroy.

Monday, June 11, 2018

C# Substring Extensions

Most of the time when I'm using Substring for something, what I'm actually trying to achieve is getting the contents of the string between two other well-known parts. For example, in a query string I might have something like this: http://mysite.com/page?user=mickey&location=Disney&bestie=Donald. If I want to get the location from that string (and yes, I know there are utilities specifically designed to get values out of query strings, but this is the best example I could come up with on short notice so get over it) I'd have to find "location" in the string, then find the next & and then get the contents between them.

Unfortunately, the out-of-the-box versions of Substring only allow us to specify the beginning index or the beginning index and a length. If I don't know the length then I have to do some mucking about with the contents and... you know what, you've probably dealt with this before. I finally decided to write some extension methods for Substring (well, for strings) that take the string I'm searching for and give me back what I want.
   1:  public static class StringExtensions
   2:  {
   3:      public static string Substring(this string input, string searchText, StringComparison comparisonType = StringComparison.InvariantCultureIgnoreCase)
   4:      {
   5:          // find the first occurrence of the search text
   6:          var index = input.IndexOf(searchText, comparisonType);
   7:  
   8:          // either return null or the entire string that comes after the search text
   9:          // append the length of the search string to the index so the search string isn't included in the result
  10:          return index == -1 ? null : input.Substring(index + searchText.Length);
  11:      }
  12:  
  13:      public static string Substring(this string input, string primarySearchText, string secondarySearchText,
  14:          StringComparison comparisonType = StringComparison.InvariantCultureIgnoreCase)
  15:      {
  16:          // find the first occurrence of the primary search text
  17:          var index = input.IndexOf(primarySearchText, comparisonType);
  18:  
  19:          if (index == -1)
  20:          {
  21:              // if the primary search text doesn't exist in the string, just return null
  22:          }
  23:  
  24:          // append the length of the primary search string to the index so the search string isn't included in the result
  25:          index += primarySearchText.Length;
  26:  
  27:          // find the first occurrence of the secondary search text
  28:          var searchUntilIndex = input.IndexOf(secondarySearchText, index, comparisonType);
  29:          // if the secondary search text doesn't exist in the string (after the primary search text occurs),
  30:          // return the entire string that comes after the primary search text
  31:          // if the secondary search text does exist in the string after the primary search text occurs,
  32:          // return whatever is between the primary search text and the secondary search text
  33:          var length = searchUntilIndex == -1 ? input.Length - index : searchUntilIndex - index;
  34:  
  35:          return input.Substring(index, length);
  36:      }
  37:  }

These new methods let me do this:
var location = input.Substring("location=", "&");

and what I'll get back from that call is "Disney" (without the quotes, of course).

I've probably written some form of this over a dozen times. At least now I've saved it for future reference so I can copy/paste it next time I need it.

Friday, June 8, 2018

Swashbuckle for Swagger (Markdown in XML Comments and Protecting the Documentation)

I just introduced Swashbuckle to a project I've been working on. If you're not familiar with Swashbuckle and/or Swagger UI, you can check them out here and here respectively. They work together to provide really simple out of the box documentation, which you can configure in a number of ways.

In my case I wanted to allow markdown in my XML comments that would then be displayed to my user. I also wanted to be able to control access to my API documentation. That may seem counter-intuitive (why document it if you're going to restrict access?) so you'll just have to trust me that it was necessary.

Both of these requirements proved to be pretty simple once I found the right posts and put them all together. I figured I'd centralize them so next time I have to do this I have all the information in one place.

Before we get into configuration and tweaking, you'll need to actually install Swagger, which can be done by adding the Swashbuckle.AspNetCore package from NuGet. If you want to follow these instructions, you'll also need to install the Microsoft.Extensions.PlatformAbstractions.

For the markdown in my XML, I had to take the following steps:
  1. Configure my project to generate XML comment documentation
  2. Configure Swagger UI to use the generated XML document
  3. Create an operation filter to format comments as markdown
  4. Set Swagger UI to use the new filter
Configuring the project to generate XML comment documentation is pretty easy. Right-click on your project and choose Properties. On the Build tab, check "XML documentation file" and in the textbox enter the name and path you want your file to be generated into. For this post I used "bin\Debug\net461\my-awesome-comments.xml" (without the quotes of course).

Assuming you go with the out-of-the-box, most-simple usage of Swagger UI to get started, your startup.cs includes something like this:

   1:  public void ConfigureServices(IServiceCollection services)
   2:  {
   3:      ...snip...
   4:      services.AddSwaggerGen(c =>
   5:      {
   6:          c.SwaggerDoc("v1", new Info {Title = "Identity Server", Version = "v1"});
   7:      });
   8:      ...snip...
   9:  }

 To configure Swagger UI to use the generated XML document you have to two lines to your AddSwaggerGen invocation. After our changes we have this:
   1:  public void ConfigureServices(IServiceCollection services)
   2:  {
   3:      ...snip...
   4:      services.AddSwaggerGen(c =>
   5:      {
   6:          c.SwaggerDoc("v1", new Info {Title = "Identity Server", Version = "v1"});
   7:  
   8:          var filePath = Path.Combine(PlatformServices.Default.Application.ApplicationBasePath, "my-awesome-comments.xml");
   9:          c.IncludeXmlComments(filePath);
  10:      });
  11:      ...snip...
  12:  }

That's it. Our Swagger UI now uses our XML comments. We're not able to use markdown yet, but we're getting there.

I'm not super up to speed on operation filters, but I found this solution in an answer to an issue someone opened on the Github repo for Swashbuckle. Scroll down to the answer on April 23, 2015 from user geokaps. I like having everything separated in folder structures, but you don't necessarily have to do it that way. In my case, I created a folder called Filters and created a new file in that folder called FormatXmlCommentSwaggerFilter.cs. Here are the contents of that file:
   1:  public class FormatXmlCommentSwaggerFilter : IOperationFilter
   2:  {
   3:      public void Apply(Operation operation, OperationFilterContext context)
   4:      {
   5:          operation.Description = Formatted(operation.Description);
   6:          operation.Summary = Formatted(operation.Summary);
   7:      }
   8:  
   9:      private string Formatted(string text)
  10:      {
  11:          if (text == null) return null;
  12:  
  13:          // Strip out the whitespace that messes up the markdown in the xml comments.
  14:          // but don't touch the whitespace in <code> blocks. Those get fixed below.
  15:          string resultString = Regex.Replace(text, @"(^[ \t]+)(?![^<]*>|[^>]*<\/)", "", RegexOptions.Multiline);
  16:          resultString = Regex.Replace(resultString, @"<code[^>]*>", "<pre>", RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Multiline);
  17:          resultString = Regex.Replace(resultString, @"</code[^>]*>", "</pre>", RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Multiline);
  18:          resultString = Regex.Replace(resultString, @"<!--", "", RegexOptions.Multiline);
  19:          resultString = Regex.Replace(resultString, @"-->", "", RegexOptions.Multiline);
  20:  
  21:          try
  22:          {
  23:              string pattern = @"<pre\b[^>]*>(.*?)</pre>";
  24:  
  25:              foreach (Match match in Regex.Matches(resultString, pattern, RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Multiline))
  26:              {
  27:                  var formattedPreBlock = FormatPreBlock(match.Value);
  28:                  resultString = resultString.Replace(match.Value, formattedPreBlock);
  29:              }
  30:              return resultString;
  31:          }
  32:          catch
  33:          {
  34:              // Something went wrong so just return the original resultString
  35:              return resultString;
  36:          }
  37:      }
  38:  
  39:      private string FormatPreBlock(string preBlock)
  40:      {
  41:          // Split the <pre> block into multiple lines
  42:          var linesArray = preBlock.Split('\n');
  43:          if (linesArray.Length < 2)
  44:          {
  45:              return preBlock;
  46:          }
  47:          else
  48:          {
  49:              // Get the 1st line after the <pre>
  50:              string line = linesArray[1];
  51:              int lineLength = line.Length;
  52:              string formattedLine = line.TrimStart(' ', '\t');
  53:              int paddingLength = lineLength - formattedLine.Length;
  54:  
  55:              // Remove the padding from all of the lines in the <pre> block
  56:              for (int i = 1; i < linesArray.Length - 1; i++)
  57:              {
  58:                  linesArray[i] = linesArray[i].Substring(paddingLength);
  59:              }
  60:  
  61:              var formattedPreBlock = string.Join("", linesArray);
  62:              return formattedPreBlock;
  63:          }
  64:      }
  65:  }

Once I had that filter created I just had to modify my Swagger UI configuration to use it. After these changes here's my whole Swagger UI configuration in startup.cs:
   1:  public void ConfigureServices(IServiceCollection services)
   2:  {
   3:      ...snip...
   4:      services.AddSwaggerGen(c =>
   5:      {
   6:          c.SwaggerDoc("v1", new Info {Title = "Identity Server", Version = "v1"});
   7:  
   8:          var filePath = Path.Combine(PlatformServices.Default.Application.ApplicationBasePath, "my-awesome-comments.xml");
   9:          c.IncludeXmlComments(filePath);
  10:          c.OperationFilter<FormatXmlCommentSwaggerFilter>();
  11:      });
  12:      ...snip...
  13:  }

That's all I had to do to enable markdown in my XML comments and it works pretty well I have to say. The next part was a little bit trickier because I wanted to lock down my entire Swagger instance so that only authorized users (with a particular permission) would be able to access it. To do this, I took the following steps:

  1. Create Swagger authorization middleware
  2. Create an extension method to use the middleware
  3. Use extension method to wire up the middleware
In my particular scenario I'm using Swagger to document our Identity Server API so I already had the ability to secure my other endpoints. On the surface it should have been just as straightforward to secure my Swagger endpoints. But I didn't want just anyone to be able to authenticate with our Identity Server and then view my APIs. I wanted to keep those private so only certain people (developers in my organization) could see the APIs after they're authenticated. To do that I created the following middleware to validate that the user is authenticated (logged in) and also should be able to access Swagger:
   1:  public class SwaggerAuthorizedMiddleware
   2:  {
   3:      private readonly RequestDelegate _next;
   4:  
   5:      public SwaggerAuthorizedMiddleware(RequestDelegate next)
   6:      {
   7:          _next = next;
   8:      }
   9:  
  10:      public async Task Invoke(HttpContext context)
  11:      {
  12:          // if the request is for the /swagger check for authentication
  13:          if (context.Request.Path.Equals("/swagger/index.html")
  14:              && (!context.User.Identity.IsAuthenticated || context.User.Claims.All(c => c.Type != "can_access_swagger") ||
  15:                  context.User.Claims.First(c => c.Type == "can_access_swagger").Value != "true"))
  16:          {
  17:              // the user is trying to access /swagger.index.html, but is either not authenticated (logged in) or
  18:              // is authenticated, but does not have access to Swagger, so redirect them to the login page
  19:              await context.ChallengeAsync();
  20:              return;
  21:          }
  22:  
  23:          // either the user was not trying to access /swagger/index.html or the user is authenticated and allowed
  24:          // so carry on to the next middleware process
  25:          await _next.Invoke(context);
  26:      }
  27:  }

That's all the middleware has to do. Now, keep in mind that we already had our authentication setup and I'm just plugging into that existing authentication and checking whether the user is authenticated and has access. If you don't already have that setup (i.e. your API is not already secured) then securing your Swagger UI is going to be more complicated. Even if that's the case, hopefully this helps steer you in the right direction.
Now that I have the middleware, I want to create a really simple extension method so I can use the middleware in my startup class
   1:  public static class SwaggerAuthorizeExtensions
   2:  {
   3:      public static IApplicationBuilder UseSwaggerAuthorized(this IApplicationBuilder builder)
   4:      {
   5:          return builder.UseMiddleware<SwaggerAuthorizedMiddleware>();
   6:      }
   7:  }

Then once I have that extension method it's just a matter of wiring it up. In startup.cs I have a Configure method. In there, after the UseMvc invocation, I want to add UseSwaggerAuthorized:
app.UseSwaggerAuthorized();


That's it! My Swagger UI is now protected with my pre-existing authentication process with an added check for whether the user should be able to access my Swagger documentation. Hope this helps someone!

Thursday, June 7, 2018

Covariance and Contravariance in C#

Covariance and Contravariance are two crazy terms that I've only ever really seen come up with Resharper tells me I'm doing something questionable. But then I was on an interview and somebody assumed - based on my other answers - that I knew what they were, but I didn't. So I figured I should probably learn.

Let me start off by saying that I've found this fantastic answer on Stack Overflow (I seriously probably spend too much time there). StuartLC goes into the right amount of detail on a really good explanation of what Covariance and Contravariance are and how and when to use them. I'm going to copy parts of his answer here just in case something ever happens to that post on SO and I can't go back and reference it.

Microsoft actually has an answer that's pretty good, if you can get past the big words and whatnot: "In C#, covariance and contravariance enable implicit reference conversion for array types, delegate types, and generic type arguments. Covariance preserves assignment compatibility and contravariance reverses it." Well, it's a good answer until that last part (at least for me) when it mentions that Covariance preserves assignment compatibility and Contravariance reverses it. I read that sentence a hundred times and still had no idea what it meant.

So let me break it down as simply as I can. Covariance enables collections (such as arrays), delegate types, and generic type arguments of a more-derived type to a collection, delegate type, and generic type argument of a less-derived type. Let's say we have the following classes:
   1:  public class LifeForm { }
   2:  public class Animal : LifeForm { }
   3:  public class Giraffe : Animal { }
   4:  public class Zebra : Animal { }

Animal is a more-derived type than LifeForm (because Animal inherits LifeForm) while Zebra and Giraffe are more-derived types than Animal (becuase they inherit Animal).

If we then have the following interface with a generic type argument:
public interface IDoStuff<T> { }
and the following class that implements that interface:
public class StuffDoer<T> : IDoStuff<T> { }
we can't do this:
   1:  static void Main(string[] args)
   2:  {
   3:      IDoStuff<LifeForm> animal = new StuffDoer<Animal>();
   4:  }

That doesn't work because Animal is a more derived type than LifeForm and right now IDoStuff is Invariant and not Covariant. By making a small change our code will work. In our IDoStuff interface we just have to enable Covariance by adding the out keyword, like this:
public interface IDoStuff<out T> { }

Now that we've established what Covariance is and means (enabling implicit conversion from a more-derived type to a less-derived type) what is it good for? That brings me back to the SO answer I linked at the beginning of this post. StuartLC writes "Covariance is widely used with immutable collections (i.e. where new elements cannot be added or removed from a collection)". It's simple, but it's worth diving more into.

Consider the use of IList, which is Invariant. We have a method that accepts an IList of type LifeForm:
   1:  public void PrintLifeForms(IList<LifeForm> lifeForms)
   2:  {
   3:      foreach (var lifeForm in lifeForms)
   4:      {
   5:          Console.WriteLine(lifeForm.GetType().ToString());
   6:      }
   7:  }

We should be (and are) able to pass in a "heterogeneous collection" (i.e. a collection of objects that are derived from LifeForm, but aren't necessarily LifeForm itself), so this would work:
   1:  IList<LifeForm> animals = new List<LifeForm>
   2:  {
   3:      new Giraffe();
   4:      new Zebra();
   5:      new Animal();
   6:  };
   7:  
   8:  PrintLifeForms(animals);
but this would fail:
   1:  IList<Giraffe> giraffes = new List<Giraffe>
   2:  {
   3:      new Giraffe();
   4:      new Giraffe();
   5:      new Giraffe();
   6:  };
   7:  
   8:  PrintLifeForms(giraffes);

I know for me at least, this doesn't seem right. It seems like as a collection of a derived type I should be able to pass it to a parameter accepting a collection of a less-derived type. But I can't. Not when I'm using an IList anyway, because IList is invariant. Now, my ah-ha moment was in the next part of the SO answer when he wrote "If I maliciously change the method implementation of PrintLifeForms (but leave the same method signature), the reason why the compiler prevents passing List becomes obvious:"

   1:  public void PrintLifeForms(IList<LifeForm> lifeForms)
   2:  {
   3:      lifeForms.Add(new Zebra());
   4:  }

As soon as I saw that code sample, it clicked. As long as my IList is LifeForm objects I can add a zebra no problem, but if I pass in an IList of giraffes then I can't add a zebra to my list because a zebra is not a giraffe.

In this particular case, implementations of IList are allowed to have items added to them so we want IList to be invariant. In other words we don't want to accidentally expect implicit conversion from a list of Giraffes to a list of LifeForms because then we'd break if we added a zebra. If we want to be able to pass in a List of Giraffe objects then we should modify our parameter to accept an IEnumerable of LifeForm objects because IEnumerable uses a covariant generic type:
   1:  public void PrintLifeForms(IEnumerable<LifeForm> lifeForms)
   2:  {
   3:      foreach (var lifeForm in lifeForms)
   4:      {
   5:          Console.WriteLine(lifeForm.GetType().ToString());
   6:      }
   7:  }

And just like that we can now pass in our List of Giraffe objects without a problem.

That was all to explain Covariance, but the other half of this post is about Contravariance so I guess we should get to that. Contravariance is the inverse of Covariance. That is, while Covariance enables a more-derived type to be provided when a less-derived type is expected, Contravariance enables a less-derived type to be provided when a more-derived type is expected. But, what does that mean?

Let's say we have this method:
   1:  public void DoSomething(IDoStuff<Zebra> doer)
   2:  {
   3:      doer.WriteMessage($"{doer.GetType()} was passed");
   4:  }

We can pass an instance of IDoStuff of type Zebra to the method... I guess that's obvious. But we can't pass an instance of IDoStuff of type Animal or Giraffe or LifeForm. That's because right now IDoStuff is Invariant (I reverted it from earlier) and it looks like this:
   1:  public interface IDoStuff<T>
   2:  {
   3:      void WriteMessage(string message);
   4:  }
and it's implemented in StuffDoer like this:
   1:  public class StuffDoer<T> : IDoStuff<T>
   2:  {
   3:      void WriteMessage(string message)
   4:      {
   5:          Console.WriteLine(message);
   6:      }
   7:  }

Right now, this would work:
DoSomething(new StuffDoer<Zebra>());
but this wouldn't:
DoSomething(new StuffDoer<Animal>());

If we want the second call to work we need to enable Contravariance on IDoStuff. We can do that by using the in keyword, like this:
   1:  public interface IDoStuff<in T>
   2:  {
   3:      void WriteMessage(string message);
   4:  }

Now we can pass an instance of DoerStuff to PerformZebraAction. Why would we do this? What would be the purpose of enabling Contravariance? Going back to StuartLC's answer we see "Contravariance is frequently used when functions are passed as parameters." He uses Action to explain the point. Using our example with giraffes and zebras (which is actually his example) it makes a little bit more sense. Consider this method:

   1:  public void PerformZebraAction(Action<Zebra> zebraAction)
   2:  {
   3:      var zebra = new Zebra();
   4:      zebraAction(zebra);
   5:  }

We can see that passing in an instance of Action would be perfectly acceptable, but we can also pass in an instance of Action. Both of these work:
   1:  var zebraAction = new Action<Zebra> (z => Console.WriteLine("I'm a zebra!"));
   2:  PerformZebraAction(zebraAction);
   3:  
   4:  var animalAction = new Action<Animal> (z => Console.WriteLine("I'm an animal!"));
   5:  PerformZebraAction(animalAction);

but this won't work:
   1:  var giraffeAction = new Action<Giraffe> (z => Console.WriteLine("I'm a giraffe!"));
   2:  PerformZebraAction(giraffeAction);

If we just think about what we're asking for here, we're saying we want the giraffe to do zebra stuff. That doesn't make sense. But we could ask a generic animal to do zebra stuff.


At the end of the day, in 12+ years of writing C# I've never really had to worry about Covariance or Contravariance. But now at least I understand what they mean and do so I'm a bit better informed. Hopefully I remember I wrote this post so I can reference it if I ever get confused again.