Unit Testing IDbSet with InMemoryDbSet

Unit testing code near of your data access layer is not always easy. However, if you work design pattern like Unit of work or have at least regrouped your unit of DbSet in a centralized place, your unit tests can be not too hard to test. This is quite easy in fact if you are returning the IDbSet than you are in lock because you can Mock the DbSet and even use a nice Nuget’s package called FakeDbSet which has a InMemoryDbSet.

You can install in your unit of test the FakeDbSet with this Nuget’s command.

Install-Package FakeDbSet

Here is a real example of a unit test that is intended to verify that when we call the repository that we get specific entity. The repository has in fact a filter — Entity Framework where clause — that return only stock that is with the status Waiting. This test verify that the Linq to Entity is really filtering correctly. The stockOrderSet is the fake.

//Configuration in the constructor of the test machine
this.stockOrderSet = new InMemoryDbSet<StockOrder>(true);
this.UnitOfWork.Setup(d => d.Set<StockOrder>()).Returns(stockOrderSet);
this.realTimeRepository = new RealTimeValuesRepository(base.UnitOfWork.Object);
//...
[TestMethod]
public void GivenStocksSymbolToRefresh_WhenOrderActiveWithStockExpired_ThenGetOneToRefresh()
{
	// Arrange
	this.stockOrderSet.Add(new StockOrder(){StockSymbol = "A", OrderStatus = OrderStatusType.Waiting});
	this.stockOrderSet.Add(new StockOrder(){StockSymbol = "B", OrderStatus = OrderStatusType.Executed});

	// Act
	var stocks = realTimeRepository.GetStocksSymbolToRefresh();

	// Assert
	Assert.AreEqual(1, stocks.Count());
	Assert.AreEqual("A", stocks.First());
}

The initialization of the fake DbSet is set by specifying that we do not want to retain any value set between tests. The Linq is executed as it would with a DbSet connected to entity framework. As you can see, I am using a mocking framework to specify that every time the unit of work class’s DbSet for the StockOrder is used to use the fake DbSet. You can do the same if your repository has directly the the DbSet but these would require to be virtual to mock them. Everything is easy testable because of different pattern. Because we are injecting the unit of work (which contains the DbSet) into the repository, than it is easy to mock the unit of work to return the fake DbSet.

The code of the FakeDbSet is available on GitHub (https://github.com/a-h/FakeDbSet).

C# Async Example

Async is a keyword that has been introduced since some time in the .Net framework. It got more popular with C# 5.0, about 4 years ago and recently, during the last year, we can see default templates using Async almost everywhere. Async is useful to have threads that are not waiting for nothing. The concept of asynchronous allows you to have multiple operations simultaneously. What make the async keywords powerful is that you do not have to play with callbacks and thread — the framework handles everything for you. Asynchronous code is very interesting when you have network requests, disk accesses or tasks that process for a long time. Async frees up the thread that is executing the task, which allows to framework to reuse it for something else. The framework optimizes the resources and give an easy way to do parallelism in your code without affecting too much your design. However, as you will note by using the async keyword, this one must be spread from the first call to the end. You will not be able to use half asynchronous code with half synchronous code — or not asynchronous.

Let’s start a Console application to do something simple. Doing a console application is interesting because Console applications are not async. They start in a single process – in a single thread. This is the nature of the console to do sequential tasks. Creating a new Web Api project or a new Web project with the latest framework, would have been more natural because Asp.Net framework include all async from the reception of the request and beyond. Therefore, let’s take the hard way to understand more what is going on. First, two keywords must be used : await and async. Second, by convention, method that are async must be prefixed by “Async” string. For example, we are going to create an async method that write into the console a string and wait few milliseconds to simulate an intensive I/O (input / output) task. Since we are going to make it async, it will be named with its name followed by “Async” : GiveMeAStringAsync.

private static async Task<string> GiveMeAStringAsync(string suffixe, int millisecondTaskTake)
{
	Console.WriteLine("Begin GiveMeAString:" + suffixe + " for " + millisecondTaskTake);
	await Task.Delay(millisecondTaskTake);
	Console.WriteLine("End GiveMeAString:" + suffixe + " for " + millisecondTaskTake);
	return "GiveMeString execute " + suffixe;
}

The method is like any other method but as before the return type the keyword async. The second difference is the return type. In a nutshell, the return type must be of type Task or its generic version Task. It can be also void for the case of “fire-and-forget”. In that latest case, we will never get any news about the task. Most of the time, we should not return void and we want to handle the answer from the task. The task is a king of bookmark that will tell the to thread some information about the task that it must execute. Any async method return a task that is automatically returned, without any delay until this one is awaited. In the code posted above this paragraph, we have a Task.Delay method that return a Task. We could have set the return of this method into a Task object.

var myTask = Task.Delay(millisecondTaskTake);
//Do something else here
await myTask;

As you can see, dividing the task into a variable allows you to do something else without executing the whole concrete task, in this example, the delay. When the task, myTask, hits the await keyword, this one wait the completion of the task. In the example, the delay. Let’s see a more complete example that use our async method.

var allStrings = new List<Task<string>>();
Console.WriteLine("Start");
Console.WriteLine("Add First");
allStrings.Add(GiveMeAStringAsync("First", 1000));
Console.WriteLine("Add Second");
allStrings.Add(GiveMeAStringAsync("Second", 500));

Console.WriteLine("Add Third");
allStrings.Add(GiveMeAStringAsync("Third", 3000));
string thirdTask = "Default Third String";
//thirdTask = await allStrings.Last();
Console.WriteLine("Add Forth");
allStrings.Add(GiveMeAStringAsync("Forth" + thirdTask, 200));

Console.WriteLine("Wait All");
var task = allStrings.ToList();
var allAwaitedTask = await Task.WhenAll(task);
foreach (var s in allAwaitedTask)
{
	Console.WriteLine("->" + s);
}
Console.WriteLine("Finish");

This code is huge but cover a lot of interesting scenarios. First, we create a collection of Task. This mean that we expect multiple methods that will return a string. This could have been your own class. It does not need to be a primitive type. In the example, I put several Console.WriteLine to display in the console to order of the code. Then, I am adding to the collection a first method with a delay of 1 second, following by a second with a delay of half a second, a third one of 3 seconds and the last one with 200 milliseconds. They are all added to the list and are executed. The execution takes the time specified in the parameter because they are delayed by the method that simulate I/O tasks — with the use of Task.Delay. After adding all the tasks, and executing them, I have used the method Task.WhenAll(listOfTaskHere). This indicate to the thread to wait every tasks to be completed before continuing. We do it because we want to display the result of each of these methods.
AsyncExample1
The output shows that all methods started in the order of their calls. From the first to the forth. After, we see that we are waiting. The console displays from the long running task – GiveMeAStringAsync – that the execution ends respectively in concordance of the delay specified which mean that the forth task, even if started last, is the first to finish. However, sine we are waiting all tasks to be completed before displaying the return value, we can see that we display them all in the order added. We can do a little change that prove that everything is executed when they are added into the collection by adding to the main thread a Sleep between the second and third task. If the sleep is big enough, the first and second task, even if more time consuming should end before the third and forth task.

var allStrings = new List<Task<string>>();
Console.WriteLine("Start");
Console.WriteLine("Add First");
allStrings.Add(GiveMeAStringAsync("First", 1000));
Console.WriteLine("Add Second");
allStrings.Add(GiveMeAStringAsync("Second", 500));
Thread.Sleep(5000);
Console.WriteLine("Add Third");
allStrings.Add(GiveMeAStringAsync("Third", 3000));
string thirdTask = "Default Third String";
//thirdTask = await allStrings.Last();
Console.WriteLine("Add Forth");
allStrings.Add(GiveMeAStringAsync("Forth" + thirdTask, 200));

Console.WriteLine("Wait All");
var task = allStrings.ToList();
var allAwaitedTask = await Task.WhenAll(task);
foreach (var s in allAwaitedTask)
{
	Console.WriteLine("->" + s);
}
Console.WriteLine("Finish");

AsyncExample2
This second example shows that the first two tasks end before even adding the third one.

Another example would be that a task depends on a previous task. For example, let’s make the forth task use the third one result. That mean that the third task must be completed before the forth one to allow the forth task to use the result of the third one.

var allStrings = new List<Task<string>>();
Console.WriteLine("Start");
Console.WriteLine("Add First");
allStrings.Add(GiveMeAStringAsync("First", 1000));
Console.WriteLine("Add Second");
allStrings.Add(GiveMeAStringAsync("Second", 500));
//Thread.Sleep(5000);
Console.WriteLine("Add Third");
allStrings.Add(GiveMeAStringAsync("Third", 3000));
string thirdTask = "Default Third String";
thirdTask = await allStrings.Last(); //We are awaiting the third task here to use the string into the forth's task
Console.WriteLine("Add Forth");
allStrings.Add(GiveMeAStringAsync("Forth" + thirdTask, 200));

Console.WriteLine("Wait All");
var task = allStrings.ToList();
var allAwaitedTask = await Task.WhenAll(task);
foreach (var s in allAwaitedTask)
{
	Console.WriteLine("->" + s);
}
Console.WriteLine("Finish");

To make the forth task use the result of the third task, we need to await the third task before the call of the forth’s one.AsyncExample3
As you can see in the output, the first three tasks ends before the forth one start. In fact, only the third one is awaited but since the first two have a lower delay than the third one, these two also finish.

If you want to try this into a console by copy-pasting the code in this article, you will get into some problem. The reason is as stated at the beginning, console does not support async code. We need to create from the console a async task that will handle all the async code. This can be done by using Task.Run(async()=>{/*You code here*/});
That mean that we would do:

static void Main(string[] args)
{

    Task.Run(async() =>
    {
        var allStrings = new List<Task<string>>();
        Console.WriteLine("Start");
        Console.WriteLine("Add First");
        allStrings.Add(GiveMeAStringAsync("First", 1000));
        Console.WriteLine("Add Second");
        allStrings.Add(GiveMeAStringAsync("Second", 500));
        //Thread.Sleep(5000);
        Console.WriteLine("Add Third");
        allStrings.Add(GiveMeAStringAsync("Third", 3000));
        string thirdTask = "Default Third String";
        thirdTask = await allStrings.Last();
        Console.WriteLine("Add Forth");
        allStrings.Add(GiveMeAStringAsync("Forth" + thirdTask, 200));

        Console.WriteLine("Wait All");
        var task = allStrings.ToList();
        var allAwaitedTask = await Task.WhenAll(task);
        foreach (var s in allAwaitedTask)
        {
            Console.WriteLine("->" + s);
        }
        Console.WriteLine("Finish");

    }).Wait();
    Console.WriteLine("Press Any Keys to stop");
    Console.ReadLine();
}

private static async Task<string> GiveMeAStringAsync(string suffixe, int millisecondTaskTake)
{
    Console.WriteLine("Begin GiveMeAString:" + suffixe +" for " + millisecondTaskTake);

    await Task.Delay(millisecondTaskTake);

    Console.WriteLine("End GiveMeAString:" + suffixe + " for " + millisecondTaskTake);
    return "GiveMeString execute " + suffixe;
}

Async works with await. Every time a code calls an asynchronous method, the code is executed until it reaches a task that is await. When the code is awaited, the thread is released and the flow continues on the caller code until it reaches another await call. In the example, every time we were calling the GiveMeAStringAsync method, the console was writting that it begins and then wait. From this wait, the code was going back to the caller — the Main method — and continue its way until it reaches and other await. This is why we were able to see all “Begin GiveMeAString” message at the beginning because the code was never stopping until it reaches the Task.WhenAll which was also in an await but this time was the last because it was running into a Task.Run with a Wait. Programming with asynchronous requires a new mind set. It is not easy, and I am not used to work this way too. Since the first 10 years with .Net we had to work in a more sequential ways or to use thread to create parallelism. Now, the syntax is clean, the superfluous of handling threads is abstracted with the await and async keyword. Working with async improves the resource of your system and is something that must be considered more and more in the future of high depend website and service to lower your cost and increase the performance of your system.

You can find this code on GitHub : https://github.com/MrDesjardins/AsyncTaskExperience

How to Moq a Portion of a Class and Test the Other Part of it

Unit testing against an interface is something that we do often with the help of Mock’s framework. This allow to not execute code that we are not testing – to concentrate on the real code to test. However, what happen if you want to test a concrete class and only test a portion of it – you want to mock the other inherited method of that interface. Let’s say that that we have a simple class that inherit an interface with two methods. If one method call the other and that we do not want to test this other method than we want to mock. For example, if you have one method that does some logic, call the second method that is slow because it goes into the file system, the web or has other logic that you do not want to tests, than you are in this scenario. Here is some code that we will use to demonstrate how to test only a portion of a class whilst having the rest Moq.

public interface IMyInterface
{
    void TransformationA();
    void TransformationB();
}

public class MyConcreteImplementation : IMyInterface
{
    public MyConcreteImplementation(int counter)
    {
        Counter = counter;
    }

    public int Counter { get; set; }
    public void TransformationA()
    {
        Counter++;
        TransformationB();
        Counter++;
    }

    public void TransformationB()
    {
        Thread.Sleep(25000);
    }
}

We have a class named MyConcreteImplementation that implements the IMyInterface. The purpose of the test would me to test the method TransformationA. This mean that we want to Mock TransformationB. This is problematic because we cannot mock the whole concrete instance of MyConcreteImplementation because the test will be against the mock and not the instance. However, we can mock the method we want to test to execute the real concrete implementation and keep the mock on the other method. The unit test should looks like:

[TestClass]
public class TransformationATest
{
    [TestMethod]
    public void MyTest()
    {
        //Arrange
        var whatWeWantToTest = new MyConcreteImplementation(100);
        var mock = new Mock<IMyInterface>();
        mock.Setup(d => d.TransformationA()).Callback(whatWeWantToTest.TransformationA);
        // -- We do nothing for B --

        // Act
        mock.Object.TransformationA();

        //Assert
        Assert.AreEqual(102, whatWeWantToTest.Counter);

    }
}

The code is creating a mock and use the mocking’s framework to do a callback on the real implementation that we want to test. The test occurs on the mock which act as a proxy for the concrete implementation. This way, the mocking framework is acting as it should for all methods excepted the one we want to test.

MyTestGreen

You can find this example on GitHub : https://github.com/MrDesjardins/MockingPortionOfCode. It uses Moq as Mocking’s framework but any others would do the same.

If you want to do the samething with a method that return a result, instead of using the Callback method, use the Returns method of your mocking framework.

Edit (2016-08-09):
It’s also possible to do it pretty easily if the method tested is virtual. Here is a real example where we mock a concrete class by supplying all parameters like we would do normally. The setup take out the method you do not want to execute of the tested class. This is the one the need to be public and virtual. The assertion can check that method to see if it’s been touched.

// Arrange
var mock = new Mock<PortefolioAccessor>(this.runningContest.Object, this.unitOfWork.Object, this.UnitOfWorkDapper.Object, this.portefolioRepository.Object, this.cache.Object);
mock.Setup(d => d.SetPortefolioInCache(It.IsAny<Portefolio>(), false));

// Act
mock.Object.SaveInterDayStatistics(contest);

// Assert
mock.Verify(d=>d.SetPortefolioInCache(It.IsAny<Portefolio>(), false), Times.Exactly(1)); 

Nancy Unit Debugging Routing Error Details

Unit tests are something that are easier than ever with the Owin standard because everything is modular which make mocking easily. However, some basic output may be not as intuitive as we are used to be. For example, during unit testing routing I stumble into an error which say that the Http Status was to 500 instead of 200. No exception was provided. How do you get the exception that thrown the Http Status Code 500? The solution is to get the output of the Html and see the error.

First, if you are unit testing routing, you should use the Nancy.Testing Nuget’s package. This one give you a Browser object that allows to simulate an Http query. You can execute the path that you want to test by using the Get method. This return a BrowserResponse. Getting the status code is available by verifying the StatusCode.

// Arrange
var browser = new Browser(bootstrapper);
            
// Act
var result = browser.Get("/", with => with.HttpRequest());

// Assert
Assert.AreEqual(HttpStatusCode.OK, result.StatusCode);

The problem is when the assert fail. You do not have any indication of why the Nancy Routing failed. If you are debugging and that you check the BrowserResponse object, you will see a Body property but it is of type Byte[]. This type is not humanely understandable. The trick is to use the extension method AsString() to get the Html output and read the error message.

var html = result.Body.AsString();

That say, most of the time is that the app.config does not have the reference to Razor page. You just need to include the Nancy.ViewEngines.Razor and be sure that the app.config has the Razor configuration and you will be able to have a HttpStatus of 200.


  <system.web.webPages.razor>
    <pages pageBaseType="Nancy.ViewEngines.Razor.NancyRazorViewBase">
      <namespaces>
        <add namespace="Nancy.ViewEngines.Razor" />
      </namespaces>
    </pages>
  </system.web.webPages.razor>

Nancy FX’s Content Folder remains Routed

You created your brand new web application with Nancy (MVC Katana for Microsoft OWIN) and you want to use BootStrap. Nuget is working like all .Net project so you can get BootStrap. However, every time one of your page want to get BootStrap’s stylesheet you have this one routed into your NancyModule. This is wrong because Nancy default behavior is to not route any file from the content folder. The problem is that Nuget added BootStrap in the content folder BUT has not set the property to copy the file when compiling. The reaction of Nancy is that it cannot find the file, so it try to route it.

To fix this issue of not having BootStrap or any other content file routed, right click the files inside the content folder and click properties. Choose from the Copy To Output Directory the option named Copy Always. Recompile your application, launch the web project and you should be all fine.

CopyAlwaysContent

Asp.Net MVC, How to Simplify your Testing with a Running Contextual Class

A good practice is to inject a running context class and a class that has information about the current user. This can be injected by your favorite injector of control container. I like dividing one for the running context and one for the current user. The first one get information about the running context and use the second one. In fact, the running context has many advantages. It allows you to easily separate from any of your code all information about how to get the user and also about the time. The time issue can become a nightmare if you are using directly DateTime.Now all over the place in your code. The problem is that you may have different timezone and you may want to facade the logic that handle it. This is often the cause if you have severs around the world. It is also the simplest way to unit test. If you want to test something about the current date, using the running context to set the “current time” is easier. It allows you to test all different paths. Here is an example in code of both interface.

public interface IRunningContext
{
        string GetUserId();
        string GetUserDisplayName();
        DateTime GetCurrentTime();
        string GetDomainNameWithPort();
}

public interface ICurrentUserInformation
{
        string GetCurrentUserName();
        string GetCurrentUserId();
        string GetCurrentEmail();
}

The concrete representation of these interfaces could be one for Http that use the HttpContext for the user and the current DateTime for the time.

public class HttpContextCurrentUserInformation : ICurrentUserInformation
{
        public string GetCurrentUserName()
        {
            return HttpContext.Current.User.Identity.Name;
        }

        public string GetCurrentUserId()
        {
            return HttpContext.Current.User.Identity.GetUserId();
        }

        public string GetCurrentEmail()
        {
            return "";
        }
}

public class HttpRunningContext:IRunningContext 
{
        private readonly ICurrentUserInformation currentUserInformation;
        public HttpRunningContext(ICurrentUserInformation principal)
        {
            currentUserInformation = principal;
        }

        public string GetUserId()
        {
            return currentUserInformation.GetCurrentUserId();
        }

        public string GetUserDisplayName()
        {
            return currentUserInformation.GetCurrentUserName();
        }

        public DateTime GetCurrentTime()
        {
            return DateTime.Now;
        }

        public string GetDomainNameWithPort()
        {
            var stringDomain = HttpContext.Current.Request.Url.Authority;
            return stringDomain;
        }
}

Having these interface allows to easily mock those interfaces. You can have in your code initialization something that setup your running context. Here is a code with Moq Mocking Framework.

protected Mock<IRunningContext> runningContext;
//...
[TestInitialize]
public void InitializeBetweenTest()
{
   runningContext = new Mock<IRunningContext>();
   runningContext.Setup(d => d.GetCurrentTime()).Returns(new DateTime(2014, 03, 02));
   runningContext.Setup(d => d.GetUserId()).Returns(ApplicationUser.SYSTEM_TEST_USER_ID);
}

With few line of code, you can test code for different users but also different time without having to do a lots of gymnastic. For example, if you have code that must be executed only between a specific time frame, if you need to test this condition without that pattern, you are almost screw. However, having this interface being mockable allows you to modify the return’s value of the GetCurrentTime’s method and you are set.

Lambda Utilities to get nested property name and value

It is handy to develop code that does not use directly the string name of a property when creating method to work against dynamic code. In the past, we would wrote code like that:

bool isNotNull = MyMethod(myObjectToVerify, "propertyToVerify");

The problem with code that specify string method’s name is that error occurs. You can mistype, you can forgot to rename the string when refactoring or you can simply not know about that string when during a replace this one got changed without you even knowing. This is why, since Microsoft .Net has introduced Lambda, you should use an expression. The result is strongly typed and it looks like this:

bool isNotNull = LambdaUtilities.VerifyNotNull( ()=>myObjectToVerify.propertyToVerify );

The code to verify the value is very simple. It consists of compiling the expression and invoking the property. If this one return null, return false, otherwise, return true. I am not going to show you how to create that simple true/false condition but how to get the value.

public static object GetValue<T>(Expression<Func<T>> selector)
{
    var method = selector.Compile();
    var value= method.Invoke();
    return value;
}

The method works for nested property. So you can use these variants when using it:

var x =  GetValue(()=>yourObject.Property);
var x2 = GetValue(()=>yourObject.Property.NestedProperty);
var x3 = GetValue(()=>yourObject.Property.NestedProperty.AndSoOn);

Getting the name of the property require more code. The code come from one of my project and if my memory is good, come almost all from a StackOverflow post.

public static string GetPropertyName<T>(Expression<Func<T>> expression)
{
	var stack = new Stack<string>();
	Expression expression1 = expression.Body;
	while (expression1 != null)
	{
		if (expression1.NodeType == ExpressionType.Call)
		{
			var methodCallExpression = (MethodCallExpression)expression1;
			if (IsSingleArgumentIndexer(methodCallExpression))
			{
				stack.Push(string.Empty);
				expression1 = methodCallExpression.Object;
			}
			else
				break;
		}
		else if (expression1.NodeType == ExpressionType.ArrayIndex)
		{
			var binaryExpression = (BinaryExpression)expression1;
			stack.Push(string.Empty);
			expression1 = binaryExpression.Left;
		}
		else if (expression1.NodeType == ExpressionType.MemberAccess)
		{
			var memberExpression = (MemberExpression)expression1;
			stack.Push("." + memberExpression.Member.Name);
			expression1 = memberExpression.Expression;
		}
		else if (expression1.NodeType == ExpressionType.Parameter)
		{
			stack.Push(string.Empty);
			expression1 = null;
		}
		else if (expression1.NodeType == ExpressionType.Convert)
		{
			var memberExp = ((UnaryExpression)expression1).Operand as MemberExpression;
			stack.Push("." + memberExp.Member.Name);
			expression1 = memberExp.Expression;
		}
		else
			break;
	}
	if (stack.Count > 0 && string.Equals(stack.Peek(), ".model", StringComparison.OrdinalIgnoreCase))
		stack.Pop();
	if (stack.Count <= 0)
		return string.Empty;
	return (stack).Aggregate(((left, right) => left + right)).TrimStart(new[] { '.' });
}

private static bool IsSingleArgumentIndexer(Expression expression)
{
	var methodExpression = expression as MethodCallExpression;
	if (methodExpression == null || methodExpression.Arguments.Count != 1)
		return false;
	return (methodExpression.Method.DeclaringType.GetDefaultMembers()).OfType<PropertyInfo>().Any((p => p.GetGetMethod() == methodExpression.Method));
}

To get the name of the property, you have to call it like the one to get the value. This one support as well nested properties.

var x =  GetPropertyName(()=>yourObject.Property);
var x2 = GetPropertyName(()=>yourObject.Property.NestedProperty);
var x3 = GetPropertyName(()=>yourObject.Property.NestedProperty.AndSoOn);

With these two methods, you should be in business to get the value and the name of properties from Lambda. Avoiding the use of string is interesting for your maintainability and it allows you to modify without fearing to forget a string somewhere.

How to Access Group by Name Instead of Index with Regex in C#

When you are searching with a Regex Expression you may have multiple groups and you may do not one to rely on the position to have access to the information. The good news is that Regex allows to name every group directly into the Regex Expression. This is done by adding inside the group parentheses a question mark followed by the less greater sign, the name and closing the name with the greater sign.

const string PATTERN_WITHOUT_NAME = @"(parser)\((.*?)\)"; //This has 3 groups
const string PATTERN_WITH_NAME= @"(parser)\((?<parameterName>.*?)\)"; //This also has 3 groups

This code is searching for every thing inside the parse method. For example: “This is parser(abc) and it is awesome”. This would result to get “abc”. This is also working for multiple instances of parser method.

var regex = new Regex(PATTERN_WITH_NAME, RegexOptions.IgnoreCase);

var matches = regex.Matches(stringToSearch);
foreach (Match match in matches)
{
	var url = match.Groups["parameterName"].Value;
}

Something that can be also interesting is to replace the named group from your Regex. This can be done with the MatchEvaluator delegate function that the Regex’ Replace method use. This deletage is called every time a match is found. From here, you must return what you want to do.

transformedString = regex.Replace(originalContent, match =>
{
	var group = match.Groups["parameterName"];
	if (group != null)
	{
		var parameter = match.Groups["parameterName"].Value;
		//Do your transformation logic here
		return string.Format("parser({0})", transformedParameter);
	}
	return match.ToString();
});

In this example, every time the Regex pattern match, the delegate is called. We get the parameter and could do something with like and return the whole match string. This is important to understand that you cannot return only a single group. For example, if you desired to just modify the parameterName and not the whole parser method this cannot be done.

This article shows you how to use Regex to match and to replace a part of a string even if the logic of replacement is complex. The MatchEvaluator allows you to have a lot of flexibility about how to figure out how to handle group within the match.

Could not load file or assembly WebGrease Update with Nuget

I decided to update all my Nuget’s packages and one more time, WebGrease could not update correctly. The solution’s projects compile but when executing them website on IIS an error message raises.

Could not load file or assembly ‘WebGrease, Version=1.6.5135.21930, Culture=neutral, PublicKeyToken=31bf3856ad364e35’ or one of its dependencies

WebGreasePage
The web.config seems legit:

<dependentAssembly>
    <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
    <bindingRedirect oldVersion="0.0.0.0-1.6.5135.21930" newVersion="1.6.5135.21930" />
</dependentAssembly>

The .dll in the project is also with the version 1.6.5135.21930.
WebGreaseDllVersion

So why does the project does not want to execute? The problem was that the Global Assembly Cache had a version that was taking over. You can go into the GAC’s folders, C:\Windows\Microsoft.NET\assembly\ or %windir%\Microsoft.NET\assembly and see 3 folders. One for GAC_32, GAC_64 and GAC_MSIL. After deleting the WebGrease folder ones in those folders and then be sure that none of WebGrease is into the Asp.Net Temporary folders. To be also sure that the cache of Asp is not having the wrong DLL, be sure to clear C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\.