Posts

Showing posts from 2012

Using Reflection to Get the Value of a Nested Property

I recently ran into a situation wherein I needed to use reflection to get the value of a nested property. We were returning a custom type that inherits from JsonResponse, but this custom type is private to the controller class that uses it (I'm not sure why -- since we're returning it from some action methods I'd have thought it could be public. But I digress).

When writing some unit tests for these methods, I wanted to check the value of the success property which just so happens to be nested within the Data property. So I wrote a little method to assist with this, as shown below (the method and class names have been changed to protect the innocent).

The steps to follow are:
Get the type of the object.Using the type, get the parent property of the nested property you want via Type.GetProperty(), specifying the name of the parent property as the parameter.Using the property, get its value using PropertyInfo.GetValue(), specifying the parent object and null as parameters.Get…

A Simple Method to Get an Object's Properties and Values at Runtime

I recently wrote some code to integrate with a WCF service authored by a different team and encountered an error, happening internal to the service, during my initial integration testing of one of the methods. I wanted to provide the developer on the other team with the parameters I passed into the method when the exception occurred, and one of those parameters was an object with more than a few properties. To that end, I wrote a quick method to provide the object's properties and their values so I could include it in the exception handling on my end and provide this info to the other developer to aid in debugging.

This method requires a using statements for System.Reflection and System.Text. It could also be expanded a bit (for example, in the way it represents the value for property values that are objects), but as a quickly-written method it gets the job done.

protectedstring GetObjectPropertiesAndValues(object target) {     StringBuilder output = newStringBuilder();     Propert…

Setting a log4net AdoNetAppender Connection String at Runtime

I recently implemented log4net in a project to log to a database using the log4net AdoNetAppender class. But I had a need to be able to specify the connection string at runtime. Here's how I was able to do it. Hopefully this will help out someone who has the same need. :)

protectedvoid SetLog4NetAppenderConnectionString(string connectionString) {     log4net.Repository.Hierarchy.Hierarchy hierarchy =         log4net.LogManager.GetLoggerRepository()              as log4net.Repository.Hierarchy.Hierarchy;     if (hierarchy != null)     {         log4net.Appender.AdoNetAppender appender             = (log4net.Appender.AdoNetAppender)hierarchy.GetAppenders()                 .Where(x => x.GetType() ==                      typeof(log4net.Appender.AdoNetAppender))                 .FirstOrDefault();         if (appender != null)         {             appender.ConnectionString = connectionString;             appender.ActivateOptions();         }     } }

The Cause and Solution for the "System.Runtime.Serialization.InvalidDataContractException: Type 'System.Threading.Tasks.Task`1[YourTypeHere]' cannot be serialized." Exception

Image
The other day I worked on some new code that ran fine locally, but when deployed to one of our internal web servers threw the following exception:

"System.Runtime.Serialization.InvalidDataContractException: Type 'System.Threading.Tasks.Task`1[NameOfTheOffendingType]' cannot be serialized."

This had me scratching my head -- after all, to use that old developer's saying, "it worked fine on my machine". Not only that, but the exception was occurring when I was calling a method that didn't use the type mentioned in the exception (according to the stack trace it looks like the exception was happening during one of the many calls made under the hood during the use of a proxy class method). But once I found the cause of the problem, it made total sense. In this case, I had added a new WCF service reference to the project, and the proxy class that was generated for it was including some new task-based asynchronous operations that are supported in .NET 4.5. …

Unit Testing with a Mock Entity Framework DbContext and Fake DbSets

I'm a big fan of the Repository pattern, and use it hand-in-hand with dependency injection and the Query Object pattern. Lately I've been developing with Entity Framework, and using dependency injection to pass the DbContext instances into my repository classes. But one of the issues I ran into while trying to unit test one of my repository classes is that I couldn't figure out how to mock the DbSets that my DbContext exposes. I could create a mock of the DbContext, but was having trouble setting it up to return fake collections of entities. One of the problems is that DbSet has no constructor (it's created via a factory method). After much research and scouring of the web, here are the steps I learned to accomplish this.

Step One: Create a Fake DbSet Class That Implements IDbSet
The DbContext exposes entities in DbSets. DbSet, in turn, implements the IDbSet interface. So we can create a class for use with our unit tests that, unlike DbSet, can be instantiated on its …

The Command Query Separation Principle

The other day I was making some additions to some legacy code that produces website order extracts which are sent to a third party system. I'd created an order in the test database and then wanted to step through a particular method that collects the data and creates an XML document from it. As I began to step through the code, I had to pause and wonder if this seemingly innocuous method would, over the course of retrieving the data and creating the extract file, also perhaps update the data. Which leads me to this post. The Command Query Separation principle (CQS for short) is a very simple one, but it's also very useful. In short, it states that any method that updates data or modifies state (a command) should not return a result, and any method that returns a result should not update data or modify state. This principle was introduced by Bertrand Meyer in his book "Object Oriented Software Construction". I find this to be a useful and worthwhile principal to fol…

A Very Simple ViewModel Example

Image
I'm currently working on a blog website app in ASP.NET MVC as a pet project. I'm not intending to use this new app instead of Blogger, but rather am doing it as a creative exercise.

During the course of this project, I found the need to make use of the MVVM (Model View ViewModel) pattern. In this particular scenario, my implementation of MVVM was very simple, but extremely useful. In this blog post, I'll explain why I needed it, and how it came in handy.

The App
As I mentioned, my blog app is being written in ASP.NET MVC. I have a BlogPostController class that is used to coordinate the creation, editing, deleting, and retrieving of blog posts. The actual data operations are performed by a repository class that the controller calls. And, of course, the data is displayed and collected via views.

The Data Model
I'm using a SQL Server database with an Entity Framework data model. Among the tables/entities in my data model are BlogPosts and Tags. Tags are descriptive labels t…

How to Mock an HttpContext for Unit Testing

I recently made some modifications to a class written by another programmer. When I went to write a unit test for my new additions, I found that the class made use of the statically accessible HttpContext.Current object. For my unit test, I wanted to be able to mock this out and use dependency injection to pass the mock in. Here are the steps I took to accomplish this.

First, a brief summary of the classes I worked with to get this done:
HttpContext: The original ASP.NET HttpContext. It has no base class and is not virtual, so it can't be mocked.HttpContextBase: Introduced in .NET 3.5 as a replacement to HttpContext. Abstract, and therefore mockable. This is the type to use as a parameter when injecting.HttpContextWrapper: Also introduced in .NET 3.5, it is an implementation of HttpContextBase. You can instantiate a new instance of this class from an HttpContext by passing the HttpContext into HttpContextWrapper's constructor (Example: new HttpContextWrapper(HttpContext.Current…

Troubleshooting Database Connectivity Issues When Unit Testing With MSTest

I was attempting to run some unit tests today for an ASP.NET MVC project I'm working on when I ran into the following fun little exception:

Test method BlogMVC.Tests.Controllers.HomeControllerTest.Index threw exception:
System.Data.EntityException: The underlying provider failed on Open. ---> System.Data.SqlClient.SqlException: An attempt to attach an auto-named database for file C:\Users\Alan\Documents\Visual Studio 2010\Projects\BlogMVC\TestResults\Alan_QUIGON 2012-05-15 16_54_57\Out\BlogMVC.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.

The issue is that each unit test is run in it's own individual directory, and in my case the unit tests needed my database files, which were not being deployed to the unit test directory.

Fortunately this is easy to correct. To fix this issue, do the following:

Right-click on the solution (not the project) and select "Add -> New Item".Choose "Test Settin…

Using a View From a Different Controller in ASP.NET MVC

I'm currently working on a pet project in ASP.NET MVC: an MVC blog engine. I don't plan on using it to host my blog, but rather as an exercise in ASP.NET MVC.

In my HomeController class, I want to retrieve the ten most recent blog posts and render them using the Index view for the BlogPost controller. This way, when a user navigates to the default page of the blog, they'll see a list of the most recent entires. But how could I use a BlogPost view (that isn't part of the Shared views folder) from within the HomeController class?

To achieve this, I did the following in the Index() method of my HomeController class -- notice the line in bold (this is in MVC 3):

publicActionResult Index() {     ViewBag.Message = "My MVC-Powered Blog!";     BlogRepository repo = newBlogRepository();     BlogRepository.BlogPostCriteria criteria =          newBlogRepository.BlogPostCriteria { NumberToRetrieve = 10 };                  var blogPosts = repo.GetBlogPosts(criteria);���…

Finding Tables in SQL Server That Contain a Certain Column Name

Here's a query you can run in SQL Server to find tables containing a certain column name -- just replace "UserId" in the WHERE clause below with the text of the column name you're searching for:

SELECT    t.name AS TableName,         SCHEMA_NAME(schema_id) AS SchemaName,         c.name AS ColumnName FROM    sys.tables AS t INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID WHERE    c.name LIKE '%UserId%' -- Replace UserId with what you're looking for ORDER BY SchemaName, TableName; 

Finding and Correcting jQuery Version Conflicts

I recently ran into an issue with some new client-side code I'd developed. While everything worked correctly in the dev environment, upon deployment to the test environment I found that some of the jQuery functions were no longer being recognized.

Going to the Console tab in Firebug, and entering "$().jquery" into the command prompt at the bottom, revealed the culprit: for some reason, despite my reference to jQuery 1.7.1, the page was now referencing version 1.4.2. The reason why was a part of the build process that occurs in our test environment and not our dev environment, which adds a reference to a minified 1.4.2 when built for the test environment (the pitfalls of differences between dev and test environments being a discussion for another time).

One possible solution to correct this was to simply update the version of jQuery being used to 1.7.1, but there was understandable concern that doing so would impact (read: break) things. So I needed a safer solution. The …

The "CTRL + ," Shortcut In Visual Studio 2010

Image
I'm currently working in a solution in Visual Studio 2010 that contains a whopping 46 projects, and even when I know where a certain file is located, it can often take awhile to just navigate to it. Fortunately, Visual Studio 2010 contains a great shortcut assist with this (it may also have been in earlier versions of Visual Studio, I'm not sure). Simply hit CTRL + , and Visual Studio will display a "Navigate To" window, which will allow you to enter text for what you're searching for (class name, file name, method name, etc) . Then, in the results list, double-click on the one you want to quickly navigate there. A huge time saver when you've got a lot of files in your project/solution.

Here's a very simple example screenshot (click to enlarge):

How to Get the Working Directory of a WCF Service

I was working on some code today in a WCF service that required me to know the directory containing the service itself. This is one of those things that by the next time I need to do it, I'll be asking myself "How did I do that last time?"

Well, here it is:

System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;