.NET Development

Although I've been a Mac user for a couple of years, I recently switched over fulltime to a Mac as my primary development machine at work. There are a lot of things I can get away with on a personal machine that I can't on a work machine (e.g., walking away from my laptop with the screen unlocked).

I was shocked how long it took for me to piece all of the little bits from various Google searches to create a simple keyboard shortcut that allows users to quickly lock their screen, so I thought I would compile it in one [hopefully] simple post.

The following shell command will return the current user to the login screen.

For those of you that missed it, Rob Conery offered a challenge a couple nights ago to build an API for Tekpub. In response to this, a few different developers took the opportunity to propose their solution to the requirements. One of those developers, John Sheehan, offered his solution entitled, Don’t build the best REST API, build the best HTTP API and tweeted that the title might be a bit linkbaitish. I understood the point he was trying to make and I think he did a fine job. Building an API should be about building the best API for the job. If you're following an architectural pattern like REST for the sake of following an architectural pattern, I suggest you stop and consider what it is you want your end results to be. For this, I can't argue with John because I agree with him. Having said that, I felt John missed an opportunity to demonstrate HATEOAS principles in a simple post that could have cleared some confusion among newcomers to REST that don't understand what hypermedia really is. John disagreed with me --it's ok, I don't hate him for it. The purpose of his post was to demonstrate how one could build the best API based on Rob specific requirements.

The purpose of this post is to pick up on what I feel is an otherwise great post. Credit goes entirely to John for the original API and JSON results returned from his proposed API.

Wikipedia says, "Hypermedia is a computer-based information retrieval system that enables a user to gain or provide access to texts, audio and video recordings, photographs and computer graphics related to a particular subject." I feel that's rather confusing and not very informative. I'd rather say, "Hypermedia is the embedding of links within responses, which will indicate to a consumer the available resources and state transitions", but even that's confusing. Let's try to explain this with some actual data.

Below is a JSON snip (including a tiny bit of API documentation) from John's blog:

// Request

GET /api/productions/PRCS

// Response

Content-Type: text/json

{

"id" : "PRRD",

"name" : "RavenDB",

"author" : "Oren Eini",

"last_updated" : 1356976799,

"episode_count" : 5,

"channels" : [ "Databases" ],

"episodes" : [

{

"id" : "EP100",

"title" : "Why You Should Care About RavenDB",

"duration" : 1200,

"release_date" : 1356976799

},

{

"id" : "EP101",

"title" : "Understanding Document Names",

"duration" : 300,

"release_date" : 1356976799

},

... truncated ...

]

}

As was previously stated, I believe this is a good start, but I wanted to show what this result could have looked like if we added some hypermedia bits to it.

The first thing that should jump out to you if you wanted to consume this data is it requires some working knowledge of the API in order to get additional details about the data. For example, what if you wanted to get an episode document by its unique identifier? You could go to the documentation and hope somebody remembered to add details about where to perform this action. Maybe you'd get lucky and find that information, but what if it moves in the future? The point is, you shouldn't have to worry about these details. The API should be robust and flexible enough to allow consumers to follow "links", much the same as hyperlinks, to the detail it is requesting rather than relying on hard-coded strings to URIs where the resources shouldbe.

Following is an update to the JSON that includes some potential hypermedia bits:

// Request

GET /api/productions/PRCS

// Response

Content-Type: text/json

{

"id" : "PRRD",

"author" : {

"name": "RavenDB",

"url": "/api/authors/Oren%20Eini"

},

"last_updated" : 1356976799,

"episode_count" : 5,

"channels" : [ { "url": "/api/channels/Databases" } ],

"episodes" : [

{

"id" : { "url": "/api/episodes/EP100" },

"title" : "Why You Should Care About RavenDB",

"duration" : 1200,

"release_date" : 1356976799

},

{

"id" : { "url": "/api/episodes/EP101" },

"title" : "Understanding Document Names",

"duration" : 300,

"release_date" : 1356976799

},

... truncated ...

]

}

And's pretty much it (I made bold the parts I updated)! As you can see, the data provides a URI from which to locate additional details about specific resource types. If those URIs change, the API developer(s) can simply update the URIs with their new location and any consumers can be blissfully unaware of any updates (from a programmatic perspective) because the data explains where to find the additional details.

Often times, without much effort, application developers can improve the future-proof-ness of their API by following simple guidelines. My intent of this post was to demonstrate that with little effort, we are able to add hypermedia bits to a JSON result and extend a simple Web API to do just that. Hopefully, somebody finds it useful.

I attended MIX11 a couple of weeks ago and had the opportunity to meet up with Glen Block at one of the open source festival booths where he was demoing MEF (Managed Extensibility Framework). During his demonstration, he showed a very cool (in my opinion) feature of MEF that allows you to export a concrete class that may or may not implement some predefined interface. This is done through the magic of the C# 4.0 dynamic keyword, which allows the compiler to bypass static type checking during compilation.

Notice the above code does not implement any particular interface. How would we import it and pass it as a parameter to, for example, another classes constructor? As previously mentioned, through the magic of the C# 4.0 dynamic feature

And that’s it! Notice the messagePart parameter is dynamic. MEF still imports the concrete type that exports the contract (in this case with the name Message). As with all dynamic types in C#, the static type checking is done at runtime.

For copying and pasting source from Visual Studio into my blog posts, I have found CopySourceAsHtml to be very helpful. For those that are not familiar with it, CopySourceAsHtml integrates nicely with Visual Studio by adding a context menu item, which allows you to easily copy source code from your source files. All of the HTML formatting is handled by the add in.

As far as I’m aware, there is currently no official release of CopySourceAsHtml for Visual Studio 2010. The good news, however, is that I was able to modify the associated .Addin file to make it work. This is not an official “workaround” from the CopySourceAsHtml developers; I just happened to find that it worked. Thus far, I have not encountered any issues with using CopySourceAsHtml within Visual Studio 2010 (at the time of this posting, I’m using the Visual Studio 2010 beta 2 release).

The initial release of Entity Framework came with a great deal of criticism. To make matters worse, there was a large uproar when it was rumored that Microsoft would be abandoning LINQ to SQL, in favor of Entity Framework. This was because, at the time, many developers felt Entity Framework was an inferior technology to LINQ to SQL. To set things right, Microsoft proactively moved forward with improving Entity Framework, in time for the 4.0 release of the .NET Framework. This is good news because my initial impressions, so far, have been nothing but positive.

One of the concerns that many developers had with the initial Entity Framework release was the difficulty in building a repository. Having said that, the first thing I did upon opening Visual Studio 2010 was to build one. Soon into my test project, I noticed some interesting things. The first thing that really caught my attention was the IObjectSet interface, which provides the ability to modify data objects. Every bit as important, the ObjectContext class now has a generic CreateObjectSet<TEntity>() method. As soon as I saw these two things, I realized the potential, not only for creating a repository, but for creating a generic repository. That’s right, one generic class that can perform all of the CRUD operations for your entire application.

To start out, I built a generic interface for our repository. Notice that with the exception of the two SaveChanges() methods, every method either takes an object of type T as a parameter, or returns an object (either a collection or a single entity), also of type T.

publicinterfaceIRepository<T> : IDisposablewhere T : class

{

IQueryable<T> Fetch();

IEnumerable<T> GetAll();

IEnumerable<T> Find(Func<T, bool> predicate);

T Single(Func<T, bool> predicate);

T First(Func<T, bool> predicate);

void Add(T entity);

void Delete(T entity);

void Attach(T entity);

void SaveChanges();

void SaveChanges(SaveOptions options);

}

Moving onward, implementing the interface was a breeze. Take note of the constructor and the call to CreateObjectSet() off of the global _context variable. This is the magic that makes the generic repository possible.

To use it, you need only instantiate the generic repository of whichever entity type you wish to query. For example, using Adventure Works, you could bind to a GridView on an ASP.NET web form, with the following:

To change the table that you wish to query, simply change the type instantiated.

Conclusion

Hopefully, you have gotten a little insight into the power that the new Entity Framework has to offer. I really believe that Microsoft has made great progress in this release. For those that were turned off by eariler versions, I urge you to give Entity Framework another go with the 4.0 release.

When sending emails to users of your system, it’s important that clients be able to read your messages. Even with modern technology advancements, not all email clients support HTML –some users actually prefer text messages. For this reason, it is important that we deliver content that a standard email (non-HTML) client can read. One way of doing this is by delivering a multi-part MIME message with alternate body parts –one part being a standard email, and another being an HTML message. It is then up to the email client to display the richest part that it can render.

Starting with 2.0, the .NET Framework includes an AlternateView class, exactly for this purpose. Following is the code necessary to send a multi-part MIME message containing both standard and HTML parts:

C# 3.0 brought with it a plethora of great additions, such as LINQ, lambda expressions and anonymous types. With the inclusion of LINQ, Microsoft decided that it was often difficult to determine the return type from a LINQ expressions. As such, they opted to include the var keyword, which is used to implicitly define a type. The type is determined by the compiler at compile time, making it strongly typed, so it is not analogous to the Visual Basic variant type. While this has some value in aiding in building LINQ expressions, I often find the use of the var keyword to be unclear (in my opinion) when used to define variables. In C# 3.0, for example, the following code is completely legit:

static void Main()
{var myInt = 10;
}

The code above defines an integer named myInt. While this particular example may be clear, I have found other situations where the use of the var keyword has made code less readable.

static void Main()
{var myEmployee = newEmployee();
}

Still not terribly unclear because the type is on the same line. But we’re starting to get unclear because my eyes start at the left to determine the type. But what if the type isn’t on the same line? What if it’s the return value of some method in another class?

What does the type above return? We could argue that the name GetSomethig() isn’t explicit enough. That’s a valid argument, but are all methods inherently named explicitly enough to determine the type returned? Absolutely not. As a result, I find myself having to reach for the mouse to hover over the the method to see a tooltip that I can use to make that determination. It slows me down. Is it that difficult to explicitly declare the type of your variable ahead of time? It makes maintenance and readability a lot easier.

If you're trying to impersonate a Windows identity in an Excel Services UDF, make sure to configure the Excel Service access mode to delegation, rather than the Trusted Subsystem model (default). This can be done with the following commands:

This next post might be rather obvious to most of you, but I figured I wasn't the only one that didn't know how to do this. I was recently working with a new ASP.NET MVC project and got tired of typing out the fully qualified class names. This seems like something that would be rather common, but a quick Google search didn't turn up anything useful. I figured that there had to be a way to import a namespace, so intellisense to the rescue, I noticed that there was an <%Import %> directive. Sure enough, that did the trick.