Category Archives: CodeProject

Post navigation

Select method is used to project each element of a sequence into a new form, i.e. it can be used to map a collection of one type to a collection of another type. In this article I’ll show you a simple approach that will allow you to reuse the code used in the Select method.

Solution 2 – Creating a generic ObjectMapper object

The previous solution solves the code reusability problem, but there’s still a tight coupling between components. Abstractions should be used to implement loose coupling between components – in this case, to abstract the mapping code.

Step 1: define a contract (interface) with a method that converts one object of type TSource to an object of type TDestination:

Final thoughts

In this article you learned how to reuse the code used in the Select method, and how you can use that code to map single objects. But writing mapping code is tedious and time consuming. There are mapping tools out there that can make your life easier – AutoMapper is one of them. I’ve used it in the past and I definitely recommend it. So, why use Automapper? Quoting their website:

“What makes AutoMapper interesting is that it provides some interesting conventions to take the dirty work out of figuring out how to map type A to type B. As long as type B follows AutoMapper’s established convention, almost zero configuration is needed to map two types”

“Mapping code is boring. Testing mapping code is even more boring. AutoMapper provides simple configuration of types, as well as simple testing of mappings”

This is the first of a 2 series articles about how to perform bulk inserts in your .NET applications, using a SQL Server database.

In this article I’ll show how to create a wrapper object for SqlBulkCopy that can do a bulk insert for a collection of objects. In the second article I’ll show how that wrapper can be easily integrated with Entity Framework (creating extension methods for DbContext and ObjectContext).

The problem

I am working in an application that parses Excel files and creates an object for each line. After some validations and properties mapping the objects are then being inserted in a database table, one by one. At the beggining this wasn’t a big problem because the number of objects to insert in the database was small, but now there can be files with thousands of rows, so using Entity Framework isn’t the best way to do it (currently Entity Framework has no support for bulk insert operations).

The solution

I decided to use the object SqlBulkCopy because it seemed the best and easiest option for performing a bulk insert in a SQL Server database. I created a wrapper for SqlBulkCopy – BulkCopy.cs. This class works the same way as SqlBulkCopy but has some extra features.

The following properties are available:

DestinationTableName: Name of the destination table on the server

BatchSize (optional): Number of rows in each batch. At the end of each batch, the rows in the batch are sent to the server

The problem

I am working on a set of extension methods to perform a bulk insert using Entity Framework, using internally the SqlBulkCopy object. One of the steps involved is to get the mapped table name from an entity. After some google searching, I found a post on StackOverflow that led me to the solution.

The solution

The trick is to use the method ObjectQuery.ToTraceString to generate a SQL Select statement for an entity, and then extract the table name from that statement.

Let’s assume that you have an entity named Album corresponding to a table named dbo.Albums.

SELECT
[Extent1].[AlbumId] AS [AlbumId],
[Extent1].[GenreId] AS [GenreId],
[Extent1].[ArtistId] AS [ArtistId],
[Extent1].[Title] AS [Title],
[Extent1].[Price] AS [Price],
[Extent1].[AlbumArtUrl] AS [AlbumArtUrl]
FROM [dbo].[Albums] AS [Extent1]

So, all we need to do is to parse the SELECT statement to get the table name. This is the approach used in the post above but it has some limitations – that code will work only for tables that are in the default SQL Server schema (dbo.{tableName}). I made some changes to that code and I’m extracting the full table name using regular expressions.

Step 1: Setting up the container in Global.asax

The first step is to setup Unity Container in Global.asax file. This is a good place to do it because it can be accessed either by web pages or by web services.
The CreateContainer() method is the place where the dependencies are specified.

GetHashCode() overview

A hash code is a numeric value that is used to identify an object during equality testing, and it can also serve as an index for an object in a collection, such as a List, Dictionary or HashTable.

The problem is that the default .NET implementation of GetHashCode() does not guarantee unique values for different values, so you should override this method and provide your own implementation.

Some rules for implementing GetHashCode() are:

If two objects compare as equal, the GetHashCode method for each object must return the same value. However, if two objects do not compare as equal, the GetHashCode methods for the two object do not have to return different values.

The GetHashCode method for an object must consistently return the same hash code as long as there is no modification to the object state

For the best performance, a hash function must generate a random distribution for all input

Implementations of the GetHashCode method must not result in circular references (it can lead to a StackOverflowException).

Implementing GetHashCode()

I found a great post on StackOverflow on this topic. Jon Skeet has provided a good and simple implementation. Basically, you need to use prime numbers like 17, 23, 29, 31 in the hash code calculation. I decided to include also the type of the object in the calculation, because two objects with identical properties/values can return the same hash code.

Using T4 templates to generate GetHashCode()

T4 is a code generator built right into Visual Studio. You can generate any text file using T4 templates: C#, javascript, HTML, XML and many others. If you’ve never heard about it, this is a good place to start:

I’ve been reading lately some stuff about HTML5 , and one of the things that I really liked was microdata. I’ve been googling and I was surprised that I almost couldn’t find any information about how to use it in ASP.NET, that’s why I’ve decided to write this article.

HTML5 Microdata Overview

The HTML5 microdata specification is a way to label content to describe a specific type of information—for example, reviews, person information, or events. Each information type describes a specific type of item, such as a person, and event, or a review. For example, an event has the properties venue, starting time, name, and category.

A common HTML code block:

<div>My name is Bob Smith but people call me Smithy. Here is my home page:
<a href="http://www.example.com">www.example.com</a>
I live in Albuquerque, NM and work as an engineer at ACME Corp.</div>

Using microdata:

<div itemscope itemtype="http://data-vocabulary.org/Person">
My name is <span itemprop="name">Bob Smith</span>
but people call me <span itemprop="nickname">Smithy</span>.
Here is my home page:
<a href="http://www.example.com" itemprop="url">www.example.com</a>
I live in Albuquerque, NM and work as an <span itemprop="title">engineer</span>
at <span itemprop="affiliation">ACME Corp</span>.
</div>

Creating a Microdata Metadata Provider

1. Create a custom attribute for microdata

This attribute is used to “decorate” model properties with microdata. It can be used directly in the model properties, or it can be used in a MetadataType class, exactly the same way that DataAnnotations are used.

Composing specifications

Existing specifications can be combined to form more complex ones. Using these extension methods it’s easy to create composite specifications (see this article to understand how to combine lambda expressions):

Using T4 to generate Specification Objects

T4 is a code generator built right into Visual Studio. You can generate any text file using T4 templates: C#, javascript, HTML, XML and many others. If you’ve never heard about it, this is a good place to start:

I’ve created a T4 template that generates automatically all the Specification Objects, one for each entity in our model. All the generated objects have all the public properties of their respective entities, including association properties. All objects were marked with the [Serializable] attribute, so you can easily serialize it if you need.

In a previous article I’ve created query objects for Entity Framework, I’m generating exactly the same properties in this template. You can see a complete description of the generated properties here.

When you save the template file or you rebuild the project the code will be regenerated. If you don’t want to generate the code, remove the value of the Custom Tool property in the property browser of the template file (by default the value is TextTemplatingFileGenerator).

Overriding ASP.NET MVC custom templates

The Add View dialog perform code generation that use T4 templates behind the scenes. These templates can be modified to customize the generated code from these tools. You can also add custom templates.

Basically you have to copy the default templates to your project. This is the path:

Understanding .resx file format

The .resx resource file format consists of XML entries, which specify objects and strings inside XML tags. One advantage of a .resx file is that when opened with a text editor (such as Notepad or Microsoft Word) it can be written to, parsed, and manipulated.(…) Each entry is described as a name/value pair.(…) When a string is added to a .resx file, the name of the string is embedded in a <data> tag, and the value is enclosed in a <value> tag

For a resource file like this:
You have the corresponding XML:
I created a custom template that generates the resource file in the specified format.

I’ve read some stuff about T4 templates in the last 2-3 years, but only recently I decided to give it a try. My first attempt was to generate Query Objects for Entity Framework, that’s what I’ll talk about in this article – what’s their purpose and how to use them.

In part 2 I’ll create a demo ASP.NET MVC application that uses query objects created with this template. I already have another T4 template that creates javascript objects for my entities, and I’m developing a custom ASP.NET view template for those objects.

What is a Query Object?

A Query Object is an interpreter [Gang of Four], that is, a structure of objects that can form itself into a SQL query. You can create this query by referring to classes and fields rather than tables and columns. In this way those who write the queries can do so independently of the database schema and changes to the schema can be localized in a single place.