Shouldly is a open source assertion library for .NET which uses extension methods to simplify the assert syntax in Unit Tests.
It can help to improve the readability of test code because the tests read like humans speak.
Instead of asserting that one value satisfies the criteria of another we simply yet elegantly say such and succh value "should be" X criteria.
Take a look at the following examples:
Another nice feature of Shouldly is that it can work with just about any Unit Test Framework (NUnit, XUnit, MSTest).
Shouldly is easy to use and even simpler to install makes testing code much clearer.
It is available on GitHub and as a Nuget package.
For more details and advanced options please see the full Pluralsight course on the subject Better Unit Test Assertions with Shouldly.
October 19, 2015
April 2, 2015
MVC Action Filters and the Case of the Russian Dolls
MVC Action Filters are a great way to add functionality that will run on every request.
However they can be a little tricky and have some unwanted side affects when using child actions via Html.Action.
The problem is that Action Filters will run multiple times by default when called via Html.Action. Once for the original action and then another time for each of the child actions. To prevent this from happening you need to ensure that the action filter is only called for the original action and not for the subsequent child actions. You can detect this situation by checking the filterContext.IsChildAction property.
So to properly handle the situation first check if the action is a child action and if it is not then run your code as normal. If it is a child action then do not run your code. Here is a simple example:
However they can be a little tricky and have some unwanted side affects when using child actions via Html.Action.
The problem is that Action Filters will run multiple times by default when called via Html.Action. Once for the original action and then another time for each of the child actions. To prevent this from happening you need to ensure that the action filter is only called for the original action and not for the subsequent child actions. You can detect this situation by checking the filterContext.IsChildAction property.
So to properly handle the situation first check if the action is a child action and if it is not then run your code as normal. If it is a child action then do not run your code. Here is a simple example:
June 27, 2014
Taking Your ASP.NET Site Offline with App_Offline.htm
Have you ever wanted to display a friendly maintenance page
to users while updating or performing some sort of work on your website? It
could be that you are rolling out an upgrade to your site or maybe you are
tweaking some IIS settings or making some major changes to your database or
infrastructure.
ASP.NET 2.0 introduced a simple yet powerful feature that is
still available today. It is as simple as adding a single file to your website.
Basically, if you place a file with the name 'app_offline.htm' in
the root of your web application directory, ASP.NET will shut-down the
application, and stop processing any new incoming requests for that
application.
ASP.NET will also then respond to all requests for dynamic
pages in the application by sending back the content of the app_offline.htm
file (for example: you might want to have a “site under construction” or “down
for maintenance” message).
After the maintenance is complete just delete the App_Offline.htm
file and the site will return back to normal.
A few points to consider:
- Prevent Friendly Http Errors - Some browsers like to be helpful and display their own custom error pages for HTTP errors like 404 and 500. These errors are triggered when the page returned by the server is very short, typically less than 512 bytes. To prevent this make sure the size of the app_offline.htm file is greater than 512 bytes. Add some comments to the file to make sure the byte size is greater than 512 and it will work fine.
- CSS, Images & JavaScript - If you want your offline page to look nice, any CSS and JavaScript will have to be embedded in the page. In addition if you want images, you will have to use the Base-64 encode trick and include it using a data URI.
Sample Project - I created a sample MVC 4 project on GitHub called AppOfflineify to
demonstrate this feature.
To test it out copy the file App_Offline.htm in the Tools
folder to the root and run the project.
Generating
Maintenance Pages - If you would like to generate maintenance pages automatically
there is a cool site which will help
you do this.
Labels:
.Net,
C#,
Configuration,
MVC4
May 24, 2014
Effective Bug Reports Require Good Communication
"If I went back to college again, I'd concentrate on
two areas: learning to write and to speak before an audience. Nothing in life
is more important than the ability to communicate effectively."
Gerald R. Ford
With all of the advances in science and technology it seems
that one of the basic skills that many have difficulty with is communication.
This causes a serious challenge at the workplace because communication is a basic
building block required for just about everything we do.
For instance think about the last project you worked on.
Whether you were gathering the requirements with product owners, working with the
creative team designing the user experience or working with the technical team
building the architecture and code - this all required one common denominator: good
communication.
One area where poor communication causes a lot of problems
for a software project is bug reports. Good bug reports that communicate effectively
to a developer can make a big difference.
"It doesn't work."
How often have we looked at a bug report and the only information there is something
like "It doesn't work", or "it's broken". If you want to quickly drive your software
developers to Lovecraftian madness then please keep creating bug reports like
this. Poorly written bug reports kill productivity.
Think about it, if you were
to bring your car to a mechanic and say "it doesn't work" how would
they be able to diagnose the problem? You would need to tell the mechanic what
the problem is, details explaining how you observed the problem and what you
expect. In a similar way a good bug report should do exactly the same.
Therefore if you are pragmatic and want to improve in this
area then communicating well in bug reports is essential. So what makes a good
bug report? In simple terms one that clearly explains what the problem is, how
did it happen and what was expected to happen. If a bug report does not satisfy all of these criteria in a concise,
simple manner then it has failed. The
following is a check list for an effective bug report:
- Short Summary
- Steps To Reproduce
- Expected Behavior
- One bug per ticket
- Include Test Data
- Provide Screenshots / Screen Cast
Labels:
bugs,
communication
October 15, 2013
ServiceStack IOC Autowiring by Convention
A situation came up where we wanted to implement a convention to auto-wire many of our classes using ServiceStack IOC. Basically we wanted to eliminate the need to hard-code mappings over and over for every class in a bootstrap file.
For example we wanted to avoid this:
container.RegisterAutoWiredAs<MyType1,IMyType1>();
container.RegisterAutoWiredAs<MyType2,IMyType2>();
container.RegisterAutoWiredAs<MyType3,IMyType3>();
container.RegisterAutoWiredAs<MyType4,IMyType4>();
...
To achieve this we can use .net reflection to scan our assemblies and look for a special interface that represents classes we want to automatically inject. Then we can utilize the ServiceStack IOC method RegisterAutoWiredType to register the types during runtime.
Here's an example where IInjectable is the interface we use to identify which classes will be injected:
For example we wanted to avoid this:
container.RegisterAutoWiredAs<MyType1,IMyType1>();
container.RegisterAutoWiredAs<MyType2,IMyType2>();
container.RegisterAutoWiredAs<MyType3,IMyType3>();
container.RegisterAutoWiredAs<MyType4,IMyType4>();
...
To achieve this we can use .net reflection to scan our assemblies and look for a special interface that represents classes we want to automatically inject. Then we can utilize the ServiceStack IOC method RegisterAutoWiredType to register the types during runtime.
Here's an example where IInjectable is the interface we use to identify which classes will be injected:
Labels:
convention,
ioc,
reflection,
servicestack
June 7, 2013
Dependency Injection of Multiple Objects Same Interface using StructureMap
I have been reading Mark Seemann's excellent book on Dependency Injection & applying what I have been learning to StructureMap.
Often times I have multiple objects that implement the same interface. In the past I may have used an abstract factory to create the instance I needed at a given time based on some sort of key or identifier like so:
However I was interested in using an IOC container like StructureMap to get rid of the ugly switch statement with the factory object. I did so by registering each object in my container and giving it a name with the .Named() method like so:
If you would like to see more please check out a simple example project over at my GitHub called MultipleObjectDemo.
Labels:
.Net,
C#,
ioc,
structuremap
Fun With Strongly Typed Enums!
Nobody likes using plain old boring Enums in C# these days! So why not try using a cool strongly typed Enum instead.
May 2, 2013
CSS Font Shortcuts
Using multiple weights and styles
In CSS, you can specify font-weights other than normal and bold by using numeric font-weight values. Here is a list of which numeric values most frequently correspond to which weights:
- 100 = thin
- 200 = extra-light
- 300 = light
- 400 = normal, book
- 500 = medium
- 600 = demi-bold
- 700 = bold
- 800 = heavy
- 900 = black
Labels:
CSS
December 31, 2012
Using PetaPoco with SQL Server Stored Procedures
For quite a while now I've been using PetaPoco for almost all of my data access needs in .Net, and it's been a great experience. For those who may not be familiar with PetaPoco, it is a light weight micro object relational mapper which helps you work with a database and map the results to your own POCO objects.
The big advantage of PetaPoco and other micro ORM's is that they are very simple compared to other "heavier" products like NHibernate or EntityFramework. Of course there is nothing wrong with NHibernate or EntityFramework, however, there is a much bigger learning curve with these technologies and many things you can do with them you can also accomplish much easier with a micro ORM. Some other micro ORM's that I have had success with are Simple.Data and Service Stack ORM Lite.
PetaPoco works great and the examples are excellent when you are working with SQL that you generate in your C# classes. However when you start to work with stored procedures it can get a little tricky figuring out the exact syntax that PetaPoco requires. Therefore I put together a few GISTS to demonstrate how to call SQL Server stored procedures from PetaPoco:
Using PetaPoco to call a SQL Server stored procedure and return 1 result to your poco object:
Using PetaPoco to call a SQL Server stored procedure and return a list of strings:
Using PetaPoco and calling a SQL Server stored procedure that returns a value with return statements in TSQL:
The big advantage of PetaPoco and other micro ORM's is that they are very simple compared to other "heavier" products like NHibernate or EntityFramework. Of course there is nothing wrong with NHibernate or EntityFramework, however, there is a much bigger learning curve with these technologies and many things you can do with them you can also accomplish much easier with a micro ORM. Some other micro ORM's that I have had success with are Simple.Data and Service Stack ORM Lite.
PetaPoco works great and the examples are excellent when you are working with SQL that you generate in your C# classes. However when you start to work with stored procedures it can get a little tricky figuring out the exact syntax that PetaPoco requires. Therefore I put together a few GISTS to demonstrate how to call SQL Server stored procedures from PetaPoco:
Using PetaPoco to call a SQL Server stored procedure and return 1 result to your poco object:
Using PetaPoco to call a SQL Server stored procedure and return a list of strings:
Using PetaPoco and calling a SQL Server stored procedure that returns a value with return statements in TSQL:
Labels:
C#,
ORM,
PetaPoco,
SQL Server,
StoredProcedure
April 12, 2012
Inject Cool Stuff Into an HTML Head Tag with ASP.Net HttpModule
Have you ever wanted to inject some dynamic text into all of the ASP.NET Web Form pages in your site whether or not they use a master page?
This sample project shows how to do just that: inject some dynamic text into all of the web page head tags in an ASP.NET Web Forms project.
It will work for pages that use master pages to generate their header and for pages that do not.
To accomplish this we create an ASP.Net HttpModule which takes advantage of the ASP.NET pipeline and runs our code to create the custom header information responding to the correct page life-cycle event.
More details to come...
This sample project shows how to do just that: inject some dynamic text into all of the web page head tags in an ASP.NET Web Forms project.
It will work for pages that use master pages to generate their header and for pages that do not.
To accomplish this we create an ASP.Net HttpModule which takes advantage of the ASP.NET pipeline and runs our code to create the custom header information responding to the correct page life-cycle event.
More details to come...
April 9, 2012
Conditional Builder Design Pattern
Have you ever wanted to use the Builder design pattern to create a really cool fluent interface for building objects but you wanted to add conditions to the building? The good news is that you can do something like so:
Notice how in this contrived example a ninja only gets the "hide in shadows" skill after reaching 6th level? To handle a conditional builder take a look at the following code:
For a complete sample project check it out on my GitHub account!
Notice how in this contrived example a ninja only gets the "hide in shadows" skill after reaching 6th level? To handle a conditional builder take a look at the following code:
For a complete sample project check it out on my GitHub account!
Labels:
.Net,
builder,
C#,
design pattern
August 10, 2011
The Decorator Pattern with Ninject
The Decorator Pattern is an excellent way to add functionality to existing objects at run time while honoring the open/closed principle. I decided to put together a sample project demonstrating this pattern in C# along with the DI container Ninject.
August 3, 2011
July 28, 2011
Git Cheatsheet 1.1
Rob Conery created an excellent Git Cheatsheet as a part of his Mastering Git video series on his training site TekPub. I decided to tweak this cheat sheet (just a touch) with a few handy git commands:
March 26, 2011
Using a Connection String Name with Log4Net AdoNetAppender
Log4Net is a great tool to quickly add logging to a .Net application. However one feature that has been missing is the ability to provide a connection string name in the configuration for the AdoNetAppender. Currently out of the box you have to provide the full connection string in the AdoNetAppender configuration settings. This can violate the DRY principle if the same connection string is already set up in the connectionStrings section of the configuration.
So the question is: How can we enhance the Log4Net AdoNetAppender to have the ability to refer to an already existing connection string defined in the connectionStrings section of the configuration?
So the question is: How can we enhance the Log4Net AdoNetAppender to have the ability to refer to an already existing connection string defined in the connectionStrings section of the configuration?
March 25, 2011
ASP.Net MVC 3 Logging
Some useful links to implement ELMAH & Log4Net in an ASP.Net MVC 3 app:
Logging Errors with ELMAH in ASP.NET MVC 3
Logging in MVC
Logging Errors with ELMAH in ASP.NET MVC 3
Logging in MVC
January 13, 2011
Well Sometimes You Need Configuration
This post describes how to use configSource in .Net to split up config file settings for developers. This allows us to have standard common config settings in the main web.config or app.config and then have developer specific values in another file.
Subscribe to:
Posts (Atom)

