Why does the Nameof operator in VB.NET return the member name with the wrong case?

nameof is one of my favorite operators in C# 6 – it’s a little thing that makes life a little easier.  I use it a lot in Entity Framework 6 with the ForeignKey attribute and when throwing ArgumentExceptions so that I don’t have to have magic strings everywhere.

I discovered some interesting behavior regarding Nameof in VB.NET that I thought took VB.NET’s case insensitivity to the next level:

See the difference in outputs?  FirstName versus fIRsTnAMe?  I mean, c’mon, really?  The Nameof operator returns exactly what you type inside of it and not the actual properly cased member name??

This actually caused me a fair bit of grief the other night – I was using Nameof with the ForeignKey attribute in EF and kept getting these odd exceptions where it said it couldn’t find the member called Firstname – and all because I mistyped the casing for the property (FirstName.)

I’ve always had a soft spot for VB.NET – in fact I wrote a whole blog post about it a couple of years ago.  I don’t use it nearly as much anymore – I only have one client who has a VB.NET app.  I gotta say though, it’s weirdness like this that makes me not miss it much, cause that sure is a strange design decision.  It’s one of the very few times that a VB.NET feature is truly not on par with a similar C# one.

(See also: unexpected behavior when using VB.NET’s If() with nullable types: http://stackoverflow.com/questions/10699740/mystery-of-the-if-function-in-vb-net)

Follow schneidenbach

RESTful API Best Practices and Common Pitfalls

As a person who spends his day integrating systems, I’ve found that at least half of the APIs I use radically differ from REST semantics, make changes too often and too quickly, don’t validate enough, and/or don’t have proper documentation. There are tons of resources for making good RESTful APIs already, but I thought I’d add to the mix with some semantic rules and some technical ones that I see broken over and over.

Now, I’m not advocating that you should spend your time trying to implement a fully-compliant REST API — very few have and there’s not much benefit to doing so. I’m a believer in pragmatic REST — that is, you should do what makes sense and throw out what doesn’t. I’m being vague on purpose because it really comes down to your particular use case.

Honestly, good REST design practices could fill an entire book. For the sake of brevity, I’ve chosen ten– four related to technical implementation, six related to semantic. The examples are done using ASP.NET Web API, but the semantic stuff (and the technical, conceptually!) also applies to RESTful APIs made using other web frameworks and languages.

When it comes to RESTful API design, I have two main rules.

  1. Do what’s expected. No reason to get creative — a really creative API is probably a bad API. Follow established best practices.
  2. Be consistent. Use the same endpoint structure, HTTP status codes, HTTP verbs, etc. for your requests, for the same reasons. A poorly formed request should return 400, not 404.

Continue reading on Medium.

Paging in ASP.NET Web API

Paging is a useful concept in any API.  Here’s an example of one that I use pretty frequently when making APIs in ASP.NET Web API.

You can download an example project (complete with unit tests!) here: https://github.com/schneidenbach/AspNetPagingExample

The steps we’re going to take to complete this task:

  • Setup our paging model.
  • Define our entity and API models.
  • Create our easy-to-use paging method that will magically turn an IQueryable into a paged set of data.

This example in particular requires AutoMapper, which will allow us to easily map our entities to our returned API models.  I also use Entity Framework to store and retrieve data, though that is not the focus of this particular project.  For the record – you should ALWAYS use API models (or DTOs, if you prefer) to do work through controllers.  Taiseer Joudeh, a Microsoft MVP for ASP.NET, calls it the “model factory pattern” and that’s how I typically refer to it.  That, or just API models. (Another way to think of API models: they hold the same purpose as a view model, but they’re not called that cause there’s no views.)  It’s a little bit more code up front, but will keep your code clean and enforce separation of concerns in the long run.  This has several advantages:

  • Lets you control what data is returned to the client.
  • Helps avoid binding to undocumented properties on PUTs/POSTs, which can be a pretty big security concern.
  • Maintains a separation of concerns. (This object returns data to the client, this object is a database entity, etc.)

1. Create and define a paging model.

We have our PageNumber and PageSize, which should match exactly what you requested (if you requested page 1 and page size 10, you should have a PageNumber of 1 and a PageSize of 10. These fields are included in the event you don’t want to require a page number or page size in your paged API.)

You have some Results, which represents the actual objects being returned.

There is a TotalNumberOfRecords and TotalNumberOfPages, which returns totals for the returned objects. If there are 100 total records and you’re requesting 15 records per page, you should expect that TotalNumberOfPages will return 7 pages.

Finally, one of the most useful properties in this model is NextPageUrl. NextPageUrl makes it very easy to get the next page in the set by providing the URL to that next resource for you.

2. Define your entities and your API models (you do use separate models for returning data, right?)

Note that in this example we are using Entity Framework for data storage.

3. Map them together using AutoMapper.

AutoMapper allows us to easily create the EmployeeModel from the Employee without writing and maintaining factory methods. All properties with the same name from Employee will be set on EmployeeModel. A lot of awesomeness in one little library.

4. Create the paged set of data.

I like to use the following CreatePagedResults method below on my controller base class – it does all of the heavy lifting for you.

A couple of important things to note:

  • The Url.Link method assumes that you have the default Web API route called DefaultApi setup in your RouteConfig.  If you don’t, you might have to tweak this example to work for you.
  • This example uses an extension method called OrderByPropertyOrField which (if you haven’t guessed) orders the IQueryable by the specified property, with a boolean to determine whether or not the order by should be ascending or descending. This string points to a property or field name of the entity type represented by IQueryable. The extension method is below:

Download the completed project here: https://github.com/schneidenbach/AspNetPagingExample

Get table info for your entities in Entity Framework

I love Entity Framework.  It’s super useful and helps me be super productive.  However, in my heart I love SQL too and I don’t always like having so much of the database abstracted away from me.  To that end, I’ve had to Google for code on how to get table metadata for my Entity Framework entities on more than one occasion so that I could do some custom stuff like ETL.

Ok, so what do I mean by “table metadata”?  Table metadata consists of information about your entity as it relates to the SQL table that represents it, such as the name of the table, the names of any columns generated, etc.

In the past, I’ve used the EntityFramework.MappingAPI library on several occasions to provide this metadata.  However, the repo has not been maintained in nearly two years and there were a couple of show-stopping bugs that prevented me from using it.  So, I decided to fork the library and create my own: EntityFramework.Metadata.

Here’s a quick step-by-step on how to use it:

  1. Find a DbContext that contains tables you want to get metadata for.
  2. Call the .Db<>() extension method, passing in the type of the entity you want to get metadata for.
  3. Access all of the awesome information you need, such as TableName or SchemaName for information about the table.  Or go even further and get information about columns related to the properties of your entity.  The choices are endless!

And some quick sample code from the README:

View Code | Download via NuGet

Using AutoMapper with Attributes

AutoMapper is awesome.  For those of you who don’t know what it is, it’s this lovely little .NET library that allows you to easily map one type to another.  It sucks to write code where all you’re doing is setting properties from one object to another, like this:

Repeat for 10 more properties and you have yourself 13 lines of code, just to create a new object out of another.  Ugh!  However, there’s always hope.  With AutoMapper, that nonsense becomes:

And that’s it.  14 lines of code to 3 for the exact same result.  AutoMapper is so great.

However, being the software geek that I am, I wanted to take things a bit farther.  I use a lot of separate classes for API/view models in my ASP.NET work (using the highly recommended model factory pattern, with the factory being AutoMapper :), and I’ve at least once ended up with a single static method that calls Mapper.CreateMap() 100 or more times.  It was kinda ugly, plus sometimes I’d add a new view model class and forget to call CreateMap to map it to its “parent” object, which caused an exception at runtime when I tried to create the mapping.  (Calling Mapper.Map() before calling Mapper.CreateMap() on those objects’ types results in an exception.)

Finally, I wanted my code to be a little more self-documenting, and adding attributes that define a mapping helps myself and others remember exactly what a view model is for.

I like this way better:

To that end, I’ve written and released my first NuGet library, AutoMapper.Attributes.  The code is open source – you can find it on GitHub.  It allows you to add attributes to classes to define your mappings.  You can also use attributes to map properties to one another.  The property attributes support dot notation, so you can map a deeply nested source property to a destination property with ease.

I’ve added all of the documentation you’ll need, including code samples, to the README on GitHub.  Please enjoy and hit me up with any feedback you have!

View Code | Download via NuGet