]]>https://www.rhyous.com/2018/02/15/i-just-hit-4000-points-on-stackoverflow/feed/039515Understanding async and await vs. Task.WaitAll vs. Task.Run vs. parallelismhttps://www.rhyous.com/2018/01/17/understanding-async-and-await-vs-task-waitall-vs-task-run-vs-parallelism/
https://www.rhyous.com/2018/01/17/understanding-async-and-await-vs-task-waitall-vs-task-run-vs-parallelism/#respondWed, 17 Jan 2018 21:29:36 +0000http://www.rhyous.com/?p=39502Ok. You are probably new to async and await or maybe you aren’t new but you’ve never deep dived into it. You may not understand some simple truths:

aync/await does NOT give you parallelism for free.

Tasks are not necessary parallel. They can be if you code them to be.

The recommendation “You should always use await” is not really true when you want parallelism, but is still sort of true.

Task.WhenAll is both parallel and async.

Task.WaitAll only parallel.

Here is a sample project that will help you learn.

There is more to learn in the comments.
There is more to learn by running this.

Note: I used Visual Studio 2017 and compiled with .Net 7.1, which required that I go to the project properties | Build | Advanced | Language Version and set the language to C# 7.1 or C# latest minor version.

]]>https://www.rhyous.com/2018/01/17/understanding-async-and-await-vs-task-waitall-vs-task-run-vs-parallelism/feed/039502Excluding Integration and other tests when running Unit Tests locally in Visual Studiohttps://www.rhyous.com/2018/01/10/excluding-integration-and-other-tests-when-running-unit-tests-locally-in-visual-studio/
https://www.rhyous.com/2018/01/10/excluding-integration-and-other-tests-when-running-unit-tests-locally-in-visual-studio/#respondWed, 10 Jan 2018 20:00:50 +0000http://www.rhyous.com/?p=39489Often, a solution may have both Unit Tests and Integration Tests. Unit Tests should be highly specific, and should be testing one class object. Integration Test could be vastly more complex and could use Selenium, or require a real database server, etc. Even if a solution doesn’t have Integration Tests, it may have slow Unit Tests. For example, I have a test that takes about 2 minutes to run because it is testing that when creating 10 million random strings, the character distribution is pretty equal.

I don’t want to either slow Unit Tests or Integration Tests to run every single time I build on my local dev box. I do have an automated build system and builds kick off on check-in. At that time, these slow tests will run every time. But locally, it is just an unnecessary delay.

Usually I am writing in a specific project and that project has specific tests and I can easily choose to only run tests in my current project. But what if I am updating a library that many projects use. I want to know quickly if anything is broke, so I need to run most of the tests in the entire solution.

Visual Studio allows for tests to be tagged with a TestCategoryAttribute.

You can mark different tests with different names: [TestCategory(“Slow”)], [TestCategory(“Integration”)], [TestCategory(“Performance”)], [TestCategory(“Selenium”)]

All other tests are left without a test category. Now, if you want to run all tests that aren’t slow, you can do this in Visual Studio Test Explorer by grouping tests using the “Traits” selection option.
Once you have marked all tests with an appropriate TestCategoryAttribute, you can sort by Trait. Now it is simple to click-to-highlight the No Traits group and click Run | Selected Tests.

]]>https://www.rhyous.com/2018/01/10/excluding-integration-and-other-tests-when-running-unit-tests-locally-in-visual-studio/feed/039489Avoiding Dependency Injection’s Constructor Injection Hell by Using the Custom or Default Patternhttps://www.rhyous.com/2017/11/08/avoiding-dependency-injections-constructor-injection-hell-by-using-the-custom-or-default-pattern/
https://www.rhyous.com/2017/11/08/avoiding-dependency-injections-constructor-injection-hell-by-using-the-custom-or-default-pattern/#commentsWed, 08 Nov 2017 14:15:42 +0000http://www.rhyous.com/?p=39466Dependency Injection makes the claim that a concrete implementation of an interface is going to change. The problem is that theory rarely meets reality. In reality, there usually exists one single concrete implementation of most interfaces. Usually there exists one Test implementation. Other than those two concrete interfaces, a second production implementation of an interface almost never exists. When there are multiple concrete implementations of an interface, it is usually in a plugin situation and is handled differently, using plugin loading technology. So we can exclude plugin scenarios, whether UI or other, and focus on day-to-day dependency injection.

In some projects, 100% of the objects have a single production implementation and a single test implementation. Other projects, you may see 90%/10%, but again, rarely are their multiple.

In other projects, you will find a second production concrete implementation, but it is replaces the previous implementation, not running alongside it.

So why are we not coding to the common case?

Construction Injection

Constructor Injection assumes a few things:

Your class should not even instantiate without something injected into the constructor.

It sounds great in theory, but in practice, it usually leads to constructor injection hell. If you are wondering what Constructor Injection hell is, have a look at this previous post: Constructor Injection Hell.

Property Injection Issues

Property Injection or Method injection are also assuming a few statements are true.

Your class can be instantiated without something injected into the constructor.

Your methods should throw exceptions if a required property has not yet been injected.

Dependency Injection Problems

Should You Stop Using Dependency Injection

So now that you’ve been educated on the truth that theory and reality never mix, and most of Dependency Injection is a waste of time, let me tell you: Keep doing it because you still will benefit from Dependency Injection.

Don’t stop doing it, but instead add to it a simple pattern. The Custom or Default pattern.

Custom or Default Pattern

This pattern is so simple that I cannot even find it mentioned in any list of software development patterns. It is so simple and obvious, that nobody talks about it. But let’s talk about it anyway.

Make everything have a default value/implementation. If a custom implementation is supplied use it, otherwise use the default.

It is a simple pattern where all the Dependency Injection rules are simplified into two:

Your class should instantiate without something injected into the constructor.

However, you didn’t solve Constructor Injection hell. You could solve that with a Service Locator. Here is the same pattern with a Service Locator. I’ll only do one Service Locator example, though it could be done a few ways.

Many developers will immediately react and say that both example result in coupled code. SomeObjectWithDependencies becomes coupled to DefaultDoer or ServiceLocator.

Well, in theory, this is coupling. Your code will never compile, the earth will stop moving, you will rue the day you made this coupling, and your children will be cursed for generations, blah, blah, blah. Again, theory and reality aren’t friends. The code always compiles. The coupling is very light. Remember, it is only coupled to a default. You have now implemented the Custom or Default pattern. With one line of code, you solved a serious problem: With regular Dependency Injection, your code doesn’t work without an injected dependency.

Guess what, you had coupling anyway. Usually you had to spin up some third library, a controller or starter of some sort, that hosted your dependency injection container, and then you had to couple the two objects of code together and now you have an entire third library just to keep two classes from being friends.

The above is still very loose coupling. It is only coupling a default. It still allows for a non-default concrete implementation to be injected.

Property Injection with the Custom or Default Pattern (Preferred)

This pattern could be implemented with Property Injection. However, this pattern suddenly becomes extremely awesome. It is no longer just a standard property. It becomes a Lazy Injectable Property.

A Lazy Injectable Property becomes key to solving most of your Constructor Injection hell.
Since it is very rare that a implementation other than the default is ever used, it is extremely rare that a Dependency Injection container is ever really needed to inject a dependency. You will find yourself doing Dependency Injection with a container.

]]>https://www.rhyous.com/2017/11/08/avoiding-dependency-injections-constructor-injection-hell-by-using-the-custom-or-default-pattern/feed/239466Eliminating Cylclomatic Complexity by replacing switch/case with a method or a Dictionary<TKey, func<>>https://www.rhyous.com/2017/10/19/eliminating-cylclomatic-complexity-by-replacing-switchcase-with-a-method-or-a-dictionary/
https://www.rhyous.com/2017/10/19/eliminating-cylclomatic-complexity-by-replacing-switchcase-with-a-method-or-a-dictionary/#respondThu, 19 Oct 2017 12:15:00 +0000http://www.rhyous.com/?p=39457Cyclomatic Complexity is a measurement of how many paths your code could traverse. Switch/case statements are often immediate Cyclomatic Complexity concerns.

The dictionary is dynamic, based on the passed in parameters, so we have to build it dynamically.

The parameters are dynamic so we call the method with reflection to allow for dynamic parameters.

The dictionary still completely eliminates Cyclomatic Complexity. Notice all the Cyclomatic Complexity is gone. This code never branches. There is very little to test.

There is the overhead of creating a Dictionary and the overhead of reflection, but again, unless you plan to use this for looping through large data sets, the performance difference is negligible.

Dictionary<TKey, Func<>>

Sometimes there isn’t much common at all. Sometimes, the complexities very greatly.

// ... code here

Imagine the code that goes there is vastly different. Imagine you just can’t find much common ground. In these situations, you can use Dictionary<TKey, Func<>>. The pattern is to put the dictionary in its own class file. Then the object that uses it can have an injectable IDictionary<TKey, Func<>>. Injection options are: Constructor injection, Method injection, property injection. I lean toward a property injection variation called a Lazy Injectable Property.

Question: What generic paramaters should be used for the Dictionary?
Answer: The TKey is clearly the type of the val property, which in the example is an int.

Question: What generic parameters should be used for the Func<>?
Answer: Well, you need to think through to get this answer. First, you need to find the Lowest Common Parameter Set. Second you need to check the return type.

Finding the Lowest Common Parameter Set

If you look at one of the above methods, you can easily get the lowest common parameter set by writing down each and every parameter pass in. Remember this one from above?

In all the previous methods, we resolved Cyclomatic Complexity by taking a method with 8 branches, and reducing that 1 method to 0 branches. We can also get 100% code coverage with 1 unit test.

1, Methods
0, Cyclomatic Complexity

In this final Dictionary<TKey, Func<>> example, we end up with 8 methods that need testing.

8, Methods
0, Cyclomatic Complexity

The reason is that we still have to test all 8 methods in the FuncDictionary. However, when that work was in the switch/case statement, those were harder to isolate for unit tests. Now, all eight methods are isolated and unit tests are simplified.

Model classes have properties and nothing more.
Note: Properties are basically getter and setter methods. In languages without properties, getters and setters are the equivalent. Do not use getter or setter methods as methods for anything more complex than default instantiation of the type. Example: You can make sure a List is not null in a getter and lazy load it, but don’t do much more. Or a calculated property might have minor logic but it is all internal to the model.

Any class with methods can reference primitives, collections and lists, interfaces, and model classes. Do not referencing a class with methods directly from any other class.

10/100 Rule (Slightly bendable rule). No method should have more than 10 lines of code, including curly braces and comments. No Class should be more than 100 lines of code, including curly braces and comments.

Look, there is S.O.L.I.D., there is D.R.Y, there is S.R.P., and many other rules. There are design patterns, including the gang of four patterns, and many others. There are architectures, MVC, MVVM, etc. But if you, as a software developer, follow the above three rules, you will automatically end up following most of the other rules. Design patterns will naturally be used in your code, even if you don’t know them, though I recommend you still learn and know about them.

]]>https://www.rhyous.com/2017/07/10/three-most-basic-rules-every-software-development-should-follow/feed/239433Back up and restore a single table with foreign keys using SQL Serverhttps://www.rhyous.com/2017/03/14/back-up-and-restore-a-single-table-with-foreign-keys-using-sql-server/
https://www.rhyous.com/2017/03/14/back-up-and-restore-a-single-table-with-foreign-keys-using-sql-server/#commentsTue, 14 Mar 2017 17:58:09 +0000http://www.rhyous.com/?p=39411Today I needed to backup a single database table, then test a change to the data, then if the change failed, restore the original data.

Below is how I did this.

What I used

I used SQL Server Management Studio to do all of the following steps.
I performed the steps on a database running on a SQL 2012 database server.

Part 1 – Backup the table

SELECT *
INTO MyTable_Bak
FROM MyTable;

Note: This will work usually, however, it won’t work if you have a calculated column. If you have a calculated column, create the table first, then specify the columns you are inserting. I didn’t have a calculated column, so I didn’t take time to figure this out.

Conclusion

Observations

This is a simple process for a table with only a few foriegn key constraints but could be difficult if you have dozens of foreign key constraints.

Also, this process might not work perfectly with calculated columns without changes to the above process.

It should be easier to do this.

If you know of a better way that doesn’t require $oftware, let me know.

]]>https://www.rhyous.com/2017/03/14/back-up-and-restore-a-single-table-with-foreign-keys-using-sql-server/feed/539411Cleaning a customer folder in Visual Studio projecthttps://www.rhyous.com/2016/11/29/cleaning-a-customer-folder-in-visual-studio-project/
https://www.rhyous.com/2016/11/29/cleaning-a-customer-folder-in-visual-studio-project/#commentsWed, 30 Nov 2016 00:19:43 +0000http://www.rhyous.com/?p=39345I have a Plugins directory in a Visual Studio project. I would like to delete all files from it when I clean.

Here is how I did this:

Edit the .csproj file.

Add the following to the very bottom of the .csproj file, just above the terminating </Project> tag.

Update 12/14/2016:
You should be aware that when doing a custom clean, that in Visual Studio choosing Clean and then Build in two steps is not the same as doing Rebuild.

Clean
]]>

https://www.rhyous.com/2016/11/29/cleaning-a-customer-folder-in-visual-studio-project/feed/539345Constructor Injection Hellhttps://www.rhyous.com/2016/09/27/constructor-injection-hell/
https://www.rhyous.com/2016/09/27/constructor-injection-hell/#respondTue, 27 Sep 2016 22:17:50 +0000http://www.rhyous.com/?p=39291So I am a fan of dependency injection (DI), inversion of control (IoC), and the way DI and IoC allow for simplistic methods and Unit Tests. With DI, you can do method injection, property injection, or constructor injection. I don’t care which one a project uses, as long as they keep it simple.

Constructor Injection

This article is focussing on constructor injection. Constructor injection seems to be very popular, if not the most popular method of DI. Constructor Injection is considered to have a benefit because it requires the instantiator to provide all the dependencies an object needs in order to create an instance of it.

An Example of Constructor Injection Hell

Recently, I started working with NopCommerce, which uses DI heavily. They use Autofac and register objects with Autofac so it can provide concrete instances of any interfaces.

I am going to use NopCommerce as an example of what not to do. Now before I do this, I want to explain that NopCommerce overall has a very good architecture. Better than most. Finding something that I consider a “what not to do” in a project should not steer you away from NopCommerce. In fact, their plugin model and architecture works quite well.

Below is an example of constructor injection gone wrong from the OrderProcessingService.cs file in NopCommerce.

Problems in the Constructor Injection Implementation

So what is wrong with the above constructor? Well, a lot. Look, this is just bad code. While constructor injection is a good idea, taking it to this extreme is not a good idea. In fact, it is a terrible idea.

The Constructor breaks the 10/100 rule. The constructor, with comments, method parameters, and method body is 126 lines of code. The method itself is far more than 10 lines of code, it is 39 lines of parameters and 39 more lines of member assignments, and is 80 lines of code.

The Constructor breaks the keep it super simple (KISS) principle. Having to new up 39 concrete instances of the parameters in order to create an object is not simple. Imagine mocking 39 interface parameters in a Unit Test. Ugh!

This constructor is a hint that the entire class is doing too much. The class is 3099 lines and clearly breaks the single responsibility principle. It is not the OrderProcessingService’s responsibility to store 39 dependent services.

The constructor breaks the Don’t Repeat Yourself (DRY) principle. Almost all other classes in NopCommerce use constructor injection to access services.

Options for Refactoring

Option 1 – Container object

You could create a container that has all of these dependecies, a dependency model object for the OrderProcessingService. This object would house the 39 dependent services and settings. But Option 2 would be better.

Option 2 – Accessor objects

Looking at this from the Single Responsibility Principle, shouldn’t there be one class and interface, a ServiceAccessor : IServiceAccessor that allows one to access any dependent service? Instead of passing in 30 services, wouldn’t it make more sense to pass in a single object called a ServiceAccessor that implements IServiceAccessor? Should there be a ServiceAccessor of some sort? Turns out there is a static: EngineContext.Current.Resolve(). Since it is a static, maybe you could wrap it in a ServiceAccessor : IServiceAccessor object.

There are also a lot of “settings” objects passed into the constructor? Shouldn’t there be a SettingsService? Well, there is. One can pass in the ISettingsService and then call _settingService.LoadSetting().

Instead of passing in 39 parameters, methods with a single responsibility to fetch a service should be used.

Option 3 – Refactor the class

Since the class is 3099 lines. If the class were broken into logical pieces, naturally, the constructor for each smaller piece would have less parameters.

]]>https://www.rhyous.com/2016/09/27/constructor-injection-hell/feed/039291How to convert a string to an enum in C#?https://www.rhyous.com/2016/08/23/how-to-convert-a-string-to-an-enum-in-csharp/
https://www.rhyous.com/2016/08/23/how-to-convert-a-string-to-an-enum-in-csharp/#respondTue, 23 Aug 2016 21:17:12 +0000http://www.rhyous.com/?p=39273Use this extension method: