Quantcast
Channel: OdeToCode by K. Scott Allen
Viewing all 513 articles
Browse latest View live

Evolution of the Entity Framework: Lesson 1

$
0
0

Looking back over the history of the Entity Framework provides some interesting lessons.

Microsoft released the first version of the Entity Framework in August of 2008. One month later, the investment bank of Lehman Brothers filed the largest bankruptcy case in the history of the United States, and thus began the worst global economic downturn since the great depression.

Dow Jones Industrial Average 2007-2009

Coincidence?

Probably.

Although the Entity Framework first appeared in 2008, the story begins much earlier. Microsoft has a long history of inventing and re-inventing data-oriented developer tools and frameworks. Applications like FoxPro and Access are long-standing examples, while Visual Studio LightSwitch is a modern specimen. FoxPro and Access were both successful products, and LightSwitch, while still new, shares the same practical attitude to working with data. All these products allow you to build a data centric application with little architectural fuss.

For .NET developers working in C# and Visual Basic, there were several times when we thought we would also see a focused, practical, no-nonsense approach to working with data. While the .NET framework has always provided abstractions like the DataSet and DataTable, these abstractions essentially represented in-memory databases complete with rows, relationships, and views. However, since C# and Visual Basic are both object-oriented programming languages, it would seem natural to take data from a database and place the data into strongly-typed objects with both properties (state) and methods (behavior). One solution we thought was coming from Microsoft was a framework named ObjectSpaces.

ObjectSpaces

ObjectSpaces was described as an object/relational mapping framework, and like all ORM frameworks ObjectSpaces focused on two goals. Goal #1 was to take data retrieved from SQL Server and map the data into objects. Goal #2 was to track changes on objects in memory so when the application asked to save all the changes, the framework could take data from the objects and insert, update, or delete data in the database. In “A First Look at ObjectSpaces in Visual Studio 2005”, Dino Esposito used the above diagram to illustrate these capabilities.

Unfortunately, ObjectSpaces never saw the light of day.

ORMs in the Stratosphere

In the spring of 2004, Microsoft announced a delay for ObjectSpaces in order to roll the technology into a larger framework named WinFS. WinFS was one of the original pillars of Longhorn (the now infamous codename for Window Vista), and WinFS promised a much larger feature set compared to ObjectSpaces.

The idea behind WinFS was to provide an abstraction over all sorts of data – relational data, structured data, and semi-structured data. WinFS would allow you to search data inside of Microsoft Money just as easily as tables in SQL Server, calendars in Exchange Server or images on the file system, as well as provide notification, synchronization, and access control services for all data sources, everywhere.

Although some of these ideas had been around since the early 1990s (the Object File System of Microsoft’s Cairo operating system), WinFS was hoping to deliver the vision and offer a quantum leap forward in the way you develop with information.

At the 2005 Professional Developers Conference, Microsoft used the following diagram in WinFS talks. When compared to the previous ObjectSpaces diagram, this diagram is more theoretical and focuses on concepts (Schemas and Services) instead of actions (moving objects from SQL Server and back).

WinFS

Despite all the talks about quantum leaps in working with data, Microsoft decided it would not ship WinFS as part of Windows Vista, and on June 23, 2006, Microsoft announced that WinFS would not be delivered as a product. Perhaps this was due to the overly ambitious goals of being all things to anything data related, or perhaps it was due to a heavy focus on architectural issues and not enough focus on the practical and mundane. Matt Warren provides an insider’s view in his post “The Origin of LINQ to SQL”.

We on the outside used to refer to WinFS as the black hole, forever growing, sucking up all available resources, letting nothing escape and in the end producing nothing except possibly a gateway to an alternate reality.

From the outside it looks like WinFS was a classic case of taking a specific problem (I need to access a data) and over-generalizing to the point where the original problem gets lost in the solution. Joel Spolsky wrote about this problem in a post entitled “Don’t Let Architecture Astronauts Scare You”.

The Architecture Astronauts will say things like: "Can you imagine a program like Napster where you can download anything, not just songs?" Then they'll build applications like Groove that they think are more general than Napster, but which seem to have neglected that wee little feature that lets you type the name of a song and then listen to it -- the feature we wanted in the first place. Talk about missing the point. If Napster wasn't peer-to-peer but it did let you type the name of a song and then listen to it, it would have been just as popular.

In retrospect, this was a dark time for Microsoft systems and frameworks. Windows Vista delayed shipping until 2007. WPF (aka Avalon) is today not capable of writing genuine Windows 8 applications. WCF (aka Indigo) is under pressure from lightweight frameworks that embrace HTTP, like the ASP.NET Web API. Windows Workflow was subsequently rewritten from scratch after its initial release, and Windows CardSpace is now defunct.

Lesson 1: Don’t Let The Astronauts Solve The Customer’s Problem

ObjectSpaces failed because it was hauled into a larger vision that was excessively ambitious and over generalized. We’ve seen over the years that the best frameworks start by solving a specific problem, solving it well, and then evolving into something bigger (the shining example being Ruby on Rails). The spirit of agile and lean software development has taught us to continuously deliver something of value, and apply YAGNI ruthlessly. Iteration and shipping bits were not a priority for the WinFS project.

However, you can’t fault Microsoft for thinking big and trying to innovate. Innovation often involves stepping away, trying something different, trying something big, and sometimes failing. Failure, and learning from failure, can lead to new directions and better inventions.

When Microsoft announced the end of WinFS as a product, it also promised to deliver some of the features and ideas encompassed in WinFS through new and different products. One of these products would be the Entity Framework. Would the Entity Framework learn from past mistakes? We’ll take a look in the next post.


Geolocation, Geocoding, and jQuery Promises

$
0
0

If you want to use the customer’s hardware to find their exact address, one approach is to combine the HTML 5 Geolocation APIs with a Geocoding web service (like Google).

For Google, you can still get in without an API key (for a limited number of calls) using the Google Maps JavaScript library (just reference http://maps.google.com/maps/api/js in a script tag).

With the library in place, the code is straightforward (particularly the following code, which doesn’t have any error handling, but is a good skeleton of the calls you’ll need to make).

(function () {

    var getPosition = function (options) {
        navigator.geolocation.getCurrentPosition(
            lookupCountry,
            null,
            options);
    };

    var lookupCountry = function (position) {
        console.log(position);
        var latlng = new google.maps.LatLng(
                            position.coords.latitude,
                            position.coords.longitude);
        
        var geoCoder = new google.maps.Geocoder();
        geoCoder.geocode({ location: latlng }, displayResults);
    };

    var displayResults = function (results, status) {
        // here you can look through results ...
        $("body").append("<div>").text(results[0].formatted_address);      
    };

    $(function () {
        getPosition();
    });

} ());

 

Making Promises

Adding some jQuery deferred objects makes the code a little longer, but also a little more robust, as the individual pieces of work are no longer responsible for knowing what to do next and we can invert control of the execution flow. In other words, if you return promises from getPosition and lookupCountry:

var getPosition = function (options) {
    var deferred = $.Deferred();

    navigator.geolocation.getCurrentPosition(
        deferred.resolve,
        deferred.reject,
        options);

    return deferred.promise();
};

var lookupCountry = function (position) {
    var deferred = $.Deferred();

    var latlng = new google.maps.LatLng(
                        position.coords.latitude,
                        position.coords.longitude);
    var geoCoder = new google.maps.Geocoder();
    geoCoder.geocode({ location: latlng }, deferred.resolve);

    return deferred.promise();
};

Then the control logic reads pretty well:

$(function () {
    $.when(getPosition())
     .pipe(lookupCountry)
     .then(displayResults);
});

Note that pipe is different than then because pipe gives back a new promise.

Try it out on jsFiddle.

Evolution of the Entity Framework: Lesson 2

$
0
0

The first version of the Entity Framework appeared in the second half of 2008 with an API derived from WinFS and a heavy theoretical focus on entity-relationship modeling. While other object relational mapping frameworks viewed mapping as a (sometimes) necessary evil, entity mapping was a centerpiece of the Entity Framework.

The Entity Framework vision was to create a conceptual data model representing entities and their relationships. The conceptual model would be the ideal model for application developers. You didn’t have to think about database tables or normalization when building the conceptual model. Instead, you were supposed to focus on the important business objects and concepts. Once the model was in place, the Entity Framework could use the model to generate code for programming against the conceptual model inside an application, as well as generate database structures to persist data represented in the model into a relational database. The theory and math behind was the mapping was spelled out in an impressive piece of academic work titled “Compiling Mappings to Bridge Applications and Databases”.

But the Entity Framework vision went beyond just traditional application development and relational databases. It was thought that the conceptual entity data model could be the canonical data model for an entire enterprise, and drive not only line of business applications but also reporting, synchronization services, web services, and data analysis.

Entity Framework Vision

Unfortunately, the Entity Framework, like its predecessor, set out to solve a broad set of problems in enterprise IT and missed the opportunity to solve a specific, common problem in a way that would make developers happy. By the time the framework officially shipped with a Visual Studio service pack, the developer community had already highlighted a number of shortcomings for accessing a relational database from the Entity Framework, which included (but was not limited to):

  • · Unimplemented LINQ operators
  • · No capability for model-first design
  • · No support for complex types
  • · No support for enum types or unsigned integers
  • · No implicit loading of relationships
  • · Limited stored procedure support
  • · Unnecessarily complexity in generated SQL code
  • · Unnecessary complexity and dependencies in generated C# code
  • · Performance

Since developers love to benchmark software, it was the last bullet, performance, that generated many blog posts comparing the Entity Framework to other object relational mapping frameworks like nHibernate and LINQ to SQL. LINQ to SQL ironically was never intended to see the light of day but did ship earlier than the Entity Framework and was gaining in popularity because it was simple to understand and solved the ORM problem in a straightforward fashion. Because LINQ to SQL has fewer architectural layers, it outperformed the Entity Framework in almost every scenario.

Entity Framework Benchmarks

Developers looked to the Entity Framework to solve one specific problem, but the framework lagged other frameworks in almost every area. When you look around at successful products, you’ll typically find they solve at least one problem extremely well. Dropbox, for example, has a minimalistic feature set compared to other file synchronization applications. But, Dropbox is hugely successful because Dropbox does file synchronization extremely well. In fact, the success of Dropbox was the topic for a question on Quora.

Well, let's take a step back and think about the sync problem and what the ideal solution for it would do:

· There would be a folder.

· You'd put your stuff in it.

· It would sync.

They built that.

Why didn't anyone else build that? I have no idea.

"But," you may ask, "so much more you could do! What about task management, calendaring, customized dashboards, virtual white boarding. More than just folders and files!"

No, shut up. People don't use that crap. They just want a folder. A folder that syncs.

Lesson 2: Solve At Least One Customer Problem Well

Early frustrations around the Entity Framework primarily arose because the framework didn’t solve a specific problem well. In turn, this led to negative reviews.

As the pressure mounted on the Entity Framework, another learning opportunity arose which we’ll look at in a future post.

Parallel Work in Async MVC Actions

$
0
0

One of the samples in the ASP.NET MVC 4 release notes is an example of using an async controller action.

public async Task<ActionResult> Index(string city)
{
var newsService = new NewsService();
var sportsService = new SportsService();

return View("Common",
new PortalViewModel
{
NewsHeadlines = await newsService.GetHeadlinesAsync(),
SportsScores = await sportsService.GetScoresAsync()
});
}

At first glance, it might seem like getting the headlines and getting the sports scores are two operations that happen in parallel, but the way the code is structured this can’t happen. It’s easier to see if you add some async methods to the controller and watch the different threads at work in the debugger.

public async Task<ActionResult> Index(string city)
{
return View("Common",
new PortalViewModel
{
NewsHeadlines = await GetHeadlinesAsync(),
SportsScores = await GetScoresAsync()
});
}
async Task<IEnumerable<Score>> GetScoresAsync()
{
await Task.Delay(3000);
// return some scores ...
}

async Task<IEnumerable<Headline>> GetHeadlinesAsync()
{
await Task.Delay(3000);
// return some news
}

In the methods I’ve introduced a delay using Task.Delay (which returns a Task you can await and thereby free the calling thread, unlike Thread.Sleep which will block). The total time to render the view will be at least 6,000 milliseconds, because the Index action awaits the result of GetHeadlinesAsync. Awating will suspend execution before GetScoresAsync has a chance to start.
If you want the headlines and scores to work in parallel, you can kick off both async calls before awaiting the first result.
public async Task<ActionResult> Index(string city)
{
var newsService = new NewsService();
var sportsService = new SportsService();

var newsTask = newsService.GetHeadlinesAsync();
var sportsTask = sportsService.GetScoresAsync();

return View("Common",
new PortalViewModel
{

NewsHeadlines = await newsTask,
SportsScores = await sportsTask
});
}

Trouble, Trouble, A Quintuple of Double

$
0
0
Func<double, double, double, double, double> distance = 
(x1, y1, x2, y2) =>
Math.Sqrt(Math.Pow(x2 - x1, 2) + Math.Pow(y2 - y1, 2));

A lady once asked me if this code was perfectible
if the Quintuple Of Double was somehow susceptible
to replacing with code still likeminded yet loveable
for the Quintuple Of Double offered feelings of trouble.

delegate double TwoPointOperation(double x1, double y1, 
double x2, double y2);

TwoPointOperation distance =
(x1, x2, y1, y2) =>
Math.Sqrt(Math.Pow(x2 - x1, 2) + Math.Pow(y2 - y1, 2));
I told her the code was still quite correctable 
a delegate type would make her worries reversible
and the one thing worse than a Quintuple Of Double
is the Sextuplet Of Object, then you know you’re in trouble.

Evolution of the Entity Framework: Lesson 3

$
0
0

To combat the negativity surrounding the first release of the Entity Framework, Microsoft launched a messaging campaign and repeatedly told us that the EF is not an ORM.

Often, people categorize Entity Framework as an Object/Relational Mapper and try to compare it to other O/R Mappers. I dare say that’s an apples-to-oranges kind of comparison. While Entity Framework does have ORM capabilities, that is only a fraction of its functionality, and more importantly, those ORM capabilities are achieved through a fundamentally different approach compared to typical O/R Mappers … Entity Framework is much bigger than a mere O/R Mapper. It is a conceptual-level development platform, and its ORM capabilities are an interface for applications to interact with conceptual models.

As part of the effort, Danny Simmons wrote a post titled “Why Use The Entity Framework”.

The big difference between the EF and nHibernate is around the Entity Data Model (EDM) and the long-term vision for the data platform we are building around it. The EF was specifically structured to separate the process of mapping queries/shaping results from building objects and tracking changes. This makes it easier to create a conceptual model which is how you want to think about your data and then reuse that conceptual model for a number of other services besides just building objects.

Instead of propelling the Entity Framework forward, the messaging spread more confusion. The first version of the Entity Framework could only do one thing: reverse engineer a database and generate code to access the database. Yet, we were supposed to think of the Entity Framework as more than an ORM and see capabilities that didn’t exist. The Entity Framework walked like a duck, and talked like a duck, but we were told to think of the framework as a golden goose.

Golden Goose

Marketing can change the perception of a product but developers can always detect missing features. No one was sure when the features would arrive. Given the recent history at the time, we didn’t expect a quick turn around for the next release. Promising features in the far off future is like asking developers to take on a debt. “Use our framework today, and we’ll pay you back in two years”. This is a tough promise to accept given the fast changing technology landscape and how quickly Microsoft abandons frameworks.

Lesson 3: Don’t Ask Your Customer For A Long Term Loan

 

The second release of the Entity Framework bumped the version number to 4.0 and arrived with Visual Studio 2010. Although many new features were added, some were superficial and in hindsight, offered another lesson.

To be continued…

Using requestAnimationFrame in JavaScript

$
0
0

There are a few different techniques you can use to animate objects in a web browser. The easiest animations are declarative animations with CSS 3 transitions. With CSS you can tell the browser to apply property changes over time instead of instantaneously, and even add some easing to make the animation appear natural. See David Rousset’s Introduction to CSS3 Animations and David Catuhe’s Transitions Puzzle for some clever examples.

Other types of animation require custom algorithms. Verlet integration, as you’ll see in a future post, can produce some enjoyable effects, but also requires custom logic in script code and a timer tick to manually update the screen at regular intervals. Script code traditionally implemented the periodic screen updates using setTimeout or setInterval,  but the future is requestAnimationFrame.

RAF in 17 Syllables

One way to think about requestAnimationFrame (RAF for short), is to contemplate the following poem, which I wrote while waiting for a dish of Yakisoba topped with red peppers and sesame seeds to arrive.

game loop request
electron salvation
render springtime on my screen

To express RAF in more straightforward prose is to say that RAF allows you to setup a loop by repeatedly telling the browser you want to draw a frame on the screen. Since the browser knows when the best time is to update the screen, it can optimize calls into your drawing code and synchronize with all the other painting and drawing. The optimization can lead to faster performance, improved CPU utilization, and extended battery life for portable devices. RAF is already supported in Chrome, Firefox, and IE 10. If a browser doesn’t support RAF natively, you can always fallback to setTimeout.

Example

To use RAF you need to invoke the RAF method and pass a callback. The callback is the function with your code to paint the illusion of motion, and you’ll keep calling RAF from within the paint method to set up an endless loop. Here is a simple example with a crude calculation for frames per second. The code will output the FPS measurement to a div.

<div id="frameRate"></div>

<script>

 

$(document).ready(function () {

var framesPerSecond = 0;
var output = $("#frameRate");
var lastRun = new Date().getTime();

var loop = function () {
requestAnimationFrame(loop);
framesPerSecond = 1 / ((new Date().getTime() - lastRun) / 1000);
lastRun = new Date().getTime();
output.text(Math.round(framesPerSecond));
};



loop();



});

</script>


Typically you would move objects or refresh and draw in a canvas element during the loop. We’ll look at simulating a swinging rope with verlet integration in a future post.

Evolution Of The Entity Framework: Lesson 4

$
0
0

The first version of the Entity Framework could create an entity data model by reverse engineering a database, and then generating code from the resulting conceptual data model. One of the enhancements in the second release of the framework was to make the code generation extensible through T4 templates. You could download a template provided by Microsoft, customize an existing template, or create a template from scratch to tweak the code generation strategy.

EF 4 T4 Templates

T4 templates provided a nice extensibility point for teams who wanted to change the generated code. Unfortunately, one of the templates provided by Microsoft was the “POCO Entity Generator”. The POCO Entity Generator came about because many people disliked the default code generation strategy. The default strategy forced all the entities to derive from an Entity Framework base class (EntityObject), and included a large number of partial methods and serialization attributes. Many developers asked for the Entity Framework to work with POCOs (plain old C# objects) instead – but why?

Objects of Desire

The word POCO came from the word POJO (plain old Java object), a term coined around the year 2000 to describe simple Java objects that were not encumbered by framework requirements. The Manning Book “POJOs In Action” is an interesting read about why POJOs came into existence. To summarize - programmers were frustrated trying to solve business problems because the application frameworks required boilerplate infrastructure code in every class. The boilerplate code was noisy, the components were difficult to test, the software was slow to build and deploy, and the overall architecture guided developers towards implementing procedural code and transaction scripts.

POJOs were about making object-oriented development easier, because a programmer didn’t have to think about business logic, persistence, and transactions all at once. POJOs let the developers drive the software design using business requirements instead of framework requirements. In short, POJOs let the developers control the code.

My Generation

The Entity Framework POCO template technically generates plain old C# objects, because the objects don’t derive from a framework base class, and don’t include partial methods and serialization attributes. However, the true spirit of code ownership through POCOs is lost in code generation. The true spirit of POJO and POCO programming is in owning the code from the start and building a core model of the business problem to solve. Like a gardener who cares about seedlings – the developer wants to grow the classes with a hands-on approach. With EF 4, the code generator still owns the POCO classes, and the POCO template does not address one of the early criticisms against the Entity Framework expressed in the Entity Framework Vote Of No Confidence.

The Entity Framework encourages the Anemic Domain Model anti-pattern by discouraging the inclusion of business logic in the entity classes. While it is possible for the business logic to be written in partial classes, this adds some awkwardness to the code as the entity data and the entity business rules and logic live in separate knowledge and user experience contexts.

Using code generation to create a set of POCO objects is backwards, but I’ve met many teams and developers who feel good about using generated POCOs because the word “POCO” covers them in the amorphous blanket of software best practices. They don’t use test-driven development, hexagonal architectures, break away from procedural transaction scripts, or try to use any of the advantages true POCO development could provide.

The POCO template, by virtue of its name, tricked many developers into cargo cult programming.

Cargo Cult Plane

This leads us to the lesson for this entry:

Lesson 4: Understand Your Customer’s Problem

The developers who wanted to work with POCOs didn’t technically want POCOs – they wanted to own the code and build applications starting with an inner core of domain logic. Code generation couldn’t solve this problem, and the POCO template was a misleading solution.

In a future post, we’ll learn one last lesson from the evolution of the Entity Framework.


Evolution of the Entity Framework: Lesson 5

$
0
0

Imagine you are in control of a large company who specializes in building tools for developers. Your staff is full of developers with tool building expertise. They write lexers during lunch breaks and WYSIWYG designers on weekends.

Next, imagine someone asks you to select the perfect serialization format for your tools. Of course you’d pick XML, right? XML is easy to parse when you need to load data into your tool, and easy to create when your tool saves some output.  Building tools with XML is like having your cake and eating it, too.

XML cake

But wait, did anyone ask the customer if XML makes their job easier?

An Ocean of Angle Brackets

XML appears in everything from configuration files to form builders these days. In some scenarios XML is a good choice, but quite often developers have to read, write, and modify the XML created by tools, or we have to understand what a tool is producing, or we need to see the differences between two versions of the tool’s output to track down a bug in our software. None of these scenarios are pleasant to deal with. Tool vendors like to use XML because XML is convenient for the tools, but contrast this justification for XML against the design philosophy for Ruby put forth by Matz:

I hope to see Ruby help every programmer in the world to be productive, and to enjoy programming, and to be happy. That is the primary purpose of Ruby language.

When is the last time you felt productive and happy with XML?

Of course, the idea is to work only inside the tool and never look at the XML output. It’s easy to stay in a tool when a tool is a word processor, but developer tools are different.

Here are a few examples.

The first two versions of the Entity Framework used a visual designer to generate an .edmx file with all of the model metadata required for the Entity Framework to function. The .edmx file was an XML file. It was possible to do some work in the designer only to discover a build error during the next compiler run. A build error like the following:

Problem in Mapping Fragments starting at lines 6, 69: Non-Primary-Key column(s) CalendarID are being mapped in both fragments to different conceptual side properties - data inconsistency is possible because the corresponding conceptual side properties can be independently modified.

After you get past the initial shock of the foreign vocabulary being presented you’ll realize the error message is pointing you to lines of code inside the XML contents of the .edmx file. Woe to those who open the .edmx file with an XML editor and wade through the ocean of angle brackets. The entity data model inside the file requires more XML than you might expect if you’ve previously done any ORM mapping with XML files.

It was also possible, particularly in V1, to run into a scenario the entity data model designer didn’t support. To implement table-per-hierarchy inheritance, for example, required wading through several hundred lines of XML just to figure out the important bits that make the inheritance approach work.

Which leads us to the 5th and final lesson derived from the evolution of the Entity Framework:

Lesson 5: Have Empathy For Your Customer

When you sit down to design a software framework or tool, something you should keep in mind is the user experience. How will they interact with your software? How will they use your software to perform a job? What sort of jobs will the user need to do? Will they be happy, and productive, and enjoy programming?

There were a number of difficult aspects to the Entity Framework that all appear to derive from design decisions that benefited the Entity Framework instead of the customer. The non-standard connection strings, the lack of implicit lazy loading, the difficult API for working with object graphs, the visual designer that couldn’t scale up to model complex domains, and of course the mountains of XML, to name just a few.

In a future post we’ll take a more positive attitude and see how the more recent versions of the Entity Framework have addressed the 5 lessons we’ve looked at over this series of posts.

Swinging on a Canvas

$
0
0

verlet with JavaScriptBuilding on top of requestAnimationFrame from earlier this week, I put together a simple example of using basic verlet integration to simulate a swinging rope in an HTML 5 canvas. You can pull the source from github, or try the sample on jsFiddle.

It’s amazing what you can do just by adding numbers together in a certain fashion. To make things interesting, there is also an option to let the rope leave a trail of pixels behind as it swings, which can make for interesting patterns (as shown in the image in this post).

MVC 4 Video Outtakes

$
0
0

I recently finished an ASP.NET MVC 4 course for Pluralsight.

Making a set of tech videos is not an easy job for me. Every video needs careful editing to remove moments of despair, frustration, and delusion. Not to mention the workplace hazards.

I put together 90 seconds of outtakes from the MVC 4 videos to share with you. I hope you can laugh at the painful parts (direct link):

Configuration Tips For ASP.NET MVC 4 on a Windows Azure Website

$
0
0

The new Windows Azure Website feature is easy to use. You can deploy an application by publishing from  Visual Studio or by pushing code with git. There are a few extra configuration steps I’ve found useful.

Using HTTP PUT and DELETE with the ASP.NET WebAPI

Using PUT and DELETE with Azure (or IIS, or IIS Express for that matter) requires some extra configuration before the server will allow messages with these methods into the processing pipeline. By default, IIS will only allow GET, HEAD, POST, and DEBUG. The following configuration section goes inside of <system.webserver>, and will tell IIS to process PUT and DELETE, too.

Note: the final release version of ASP.NET MVC 4 will include this configuration in web.config by default when you create a new project*, but it is still handy for upgrades and to generally know why it exists.

<handlers>
<remove name="ExtensionlessUrl-Integrated-4.0" />
<add name="ExtensionlessUrl-Integrated-4.0"
path="*."
verb="GET,HEAD,POST,DEBUG,DELETE,PUT"
type="System.Web.Handlers.TransferRequestHandler"
preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>

The Usual HTML 5 Media Types

Before IIS will serve a static file it needs to know the media type associated with the file. Video and SVG files were refusing to work until I added the following (also in the <system.webserver> section of web.config):

<staticContent>
<remove fileExtension=".mp4"/>
<remove fileExtension=".ogv"/>
<remove fileExtension=".webm"/>
<remove fileExtension=".svg"/>
<mimeMap fileExtension=".mp4" mimeType="video/mp4" />
<mimeMap fileExtension=".ogv" mimeType="video/ogg" />
<mimeMap fileExtension=".webm" mimeType="video/webm" />
<mimeMap fileExtension=".svg" mimeType="image/svg+xml"/>
</staticContent>

The <remove> entries will allow the configuration to work even on local servers that already have the media types configured (you’ll have a runtime error if you add a duplicate entry, but there is no error if you remove an entry that doesn’t exist).

Automatic Migrations

Finally, if you are using Code First Entity Framework migrations you can have them execute automatically after a release push by adding  to the Web.Release.config file. Web.config transformations even work with git deployments to Azure.

<entityFramework>
<contexts xdt:Transform="Insert">
<context type="EmployeeApp.EmployeeDb, MvcApplication10">
<databaseInitializer
type="System.Data.Entity.MigrateDatabaseToLatestVersion`2[
[EmployeeApp.EmployeeDb,MvcApplication10],
[MvcApplication10.Migrations.Configuration, MvcApplication10]
], EntityFramework"
/>
</context>
</contexts>
</entityFramework>

Of course you’ll need to substitute your own DbContext and Configuration types as the generic type parameters to MigrateDatabaseToLatestVersion. See EF 4.3 Configuration File Settings for more details (yes, it works with EF 5.0, too).

* MVC 4 will also configure ExtensionlessUrlHandler-ISAPI-4.0_32bit and ExtensionlessUrlHandler-ISAPI-4.0_64bit.

A Troubleshooting Guide for Entity Framework Connections & Migrations

$
0
0

The Entity Framework DbContext class uses a convention over configuration approach to development. When everything is working correctly, you can generate and populate a database just by writing a little bit of code and running “enable-migrations” and “update-database” from the Package Manager Console window in Visual Studio. No XML mapping or configuration files are required, see EF Code-Based Migrations Walkthrough for more details.

When things do not work, the conventions are frustrating because they form an impenetrable fog of mystery. Of course, having everything explicitly configured isn’t always clearer or easier to troubleshoot, but here are some common problems I’ve observed with EF 4.1 – EF 5.0, and some steps you can take to avoid the problems.

Cannot Connect to a Database

A couple popular errors you might run across include:

“System.Data.ProviderIncompatibleException: An error occurred while getting provider information from the database”

And the timeless message:

“System.Data.SqlClient.SqlException: A network-related or instance-specific error occurred while establishing a connection to SQL Server.

These messages can happen at any stage, from enable-migrations, to update-database, to running the application. The key to getting past one of these messages is figuring out which database the framework is trying to reach, and then making that database available (or pointing the framework somewhere else).

The first step I would recommend is trying to determine what connection string the framework is using, because the exception doesn’t tell you the connection string, and the connection string can be controlled by a variety of conventions, configurations, and code.

To find out the connection string, I’d add some logging to a default constructor in my DbContext derived class.

public class DepartmentDb : DbContext 
{
public DepartmentDb()
{
Debug.Write(Database.Connection.ConnectionString);
}

public DbSet<Person> People { get; set; }
}

Run the application with the debugger and watch the Visual Studio Output window. Or, set a breakpoint and observe the ConnectionString property as you go somewhere in the application that tries to make a database connection.

Chances are you’ll see something like the following:

Data Source=.\SQLEXPRESS;Initial Catalog=SomeNamespace.DepartmentDb;Integrated Security=True;

When there is no other configuration or code in place, the Entity Framework will try to connect to the local SQL Server Express database (.\SQLEXPRESS). Visual Studio 2010 will install SQL Server Express by default, so if you are not establishing a connection you might have customized the installation, shut down SQL Server Express, or did one of a thousand other things you might possibly do to make the database unavailable (like change the network protocols). One way to see what SQL services are available on your machine is to go to the Package Manager Console in Visual Studio and execute the following command (also showing the output below):

PM> Get-Service | Where-Object {$_.Name -like '*SQL*'}

Status   Name               DisplayName                          
------   ----               -----------                          
Stopped  MSSQLFDLauncher    SQL Full-text Filter Daemon Launche...
Stopped  MSSQLSERVER        SQL Server (MSSQLSERVER)             
Stopped  SQLBrowser         SQL Server Browser                   
Stopped  SQLSERVERAGENT     SQL Server Agent (MSSQLSERVER)       
Running  SQLWriter          SQL Server VSS Writer                

In the above output you can see I do not have a default SQLEXPRESS instance available (it would list itself as MSSQL$SQLEXPRESS), but I do have a default SQL Server instance installed (MSSQLSERVER – but it is not running). I’d have to start the service and give the Entity Framework an explicit connection string for this scenario to work (see Controlling Connections below).

EF 5 and Visual Studio 2012

Visual Studio 2012 installs SQL Server LocalDb by default. LocalDb is the new SQL Express with some notable differences from SQL Express 2008. A LocalDb instance runs as a user process, requires a different connection string, and stores the system databases under your hidden AppData directory.

Since LocalDb is a user process and not a service, you won’t see it listed in the output of the Get-Service command above. You can, however, run SqlLocalDb.exe from the package manager console (or the command line) to see if LocalDb is installed.

PM> SqlLocalDb info
v11.0

If the executable isn’t found, chances are you do not have LocalDb installed. In the above output, I can see I have LocalDb v11.0 installed. EF 5 will use LocalDb if it doesn’t detect SQL Express running, so when you look at the Database.Connection.ConnectionString property in the constructor, like we did earlier, you might  see the following instead:

Data Source=(localdb)\v11.0;Initial Catalog=SomeNamespace.DepartmentDb;Integrated Security=True;

(localdb)\v11.0 is the LocalDb connection string, and if you are not connecting to LocalDb then you might need to reinstall (here is a link that will eventually take you to the MSI file).

Connection Factories

How does the framework know to use LocalDb instead of Express? It’s done through configuration. If you open your application’s config file, you should see the following inside:

<entityFramework>
<defaultConnectionFactory
type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory,
EntityFramework"
>
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
</entityFramework>

Using the LocalDbConnectionFactory means you’ll no longer try to connect to SQL Express by default. There is also a connection factory for SQL Compact. You’ll find this factory in your config file if you install the EF SQL Compact NuGet package.

Insufficient Permissions

Another common problem I’ve seen popping up when using Code First migrations is typically realized with one of the following exceptions:

System.Data.SqlClient.SqlException: Login failed for user ‘[Your account here]'.

... and ...

System.Data.SqlClient.SqlException (0x80131904): CREATE DATABASE permission denied in database 'master'.

These permission issues can be hard to fix. The first thing I’d do is add some debugging code to verify the connection string being used by the Entity Framework (the debugging code demonstrated earlier). Once you know the server the Entity Framework is trying to reach you should try to login to the server with a management tool (like SQL Management Studio, which also works with LocalDb), if you can. The problem is you might not be able to login with your account.

Even if you are an administrator on your local machine you might find yourself with limited privileges in your own, local SQL Server. One scenario where this can happen is when SQL Server or SQL Server Express is installed onto your machine by a different user, or you installed the software using a different account, or perhaps your machine was built from a cloned image file. As of SQL 2008, just being an administrator in Windows doesn’t make you a sysadmin in SQL Server.

To fix the permission issues you can try to login to the server using the sa account, but of course you must know the password and the sa account must be enabled. You can also try to login to your machine using the Windows account used for the software installation. Once logged in with high privileges you’ll need to add your Windows login to the list of SQL Server logins and (ideally) put yourself in the sysadmin server role

When all else fails, you can try to regain control of SQL Server by starting the server in single user mode (see Connect to SQL Server When System Administrators Are Locked Out). The SQL Express blog also published a script to automate this process (see How to take ownership of your local SQL Server), which should also work with SQL 2012. The nuclear option, if you don’t care about any of the local databases, is to uninstall and reinstall SQL Server.

Cannot Attach to Deleted MDF File

If you are using SQL LocalDb, don’t ever delete the physical .mdf and .log files for your database without going through the SQL Server Object Explorer in Visual Studio or in SQL Server Management Studio. If you delete the files only, you end up with an error like the following in a web application:

Cannot attach the file ‘…\App_Data\DepartmentDb.mdf' as database 'DepartmentDb'.

Or the following error in a desktop app:

SqlException: Cannot open database "DepartmentDb" requested by the login. The login failed.

In this case the database is still registered in LocalDb, so you’ll need to go in the Object Explorer and also delete the database here before SQL Server will recreate the files. 

SQL Server Object Explorer in VS2012

Controlling Connections

Explicitly controlling the connection string for the Entity Framework is easy. You can pass a connection string to the DbContext constructor, or you can pass the name of a connection string that resides in the application’s configuration file. For example, the following code will make sure the Entity Framework connects to the local SQL Server default instance and use a database named departments.

public class DepartmentDb : DbContext 
{
public DepartmentDb()
: base(@"data source=.;
initial catalog=departments;
integrated security=true"
)
{
}

public DbSet<Person> People { get; set; }
}

While the following would tell the framework to look for a connection string named departments in the config file:

public class DepartmentDb : DbContext 
{
public DepartmentDb() : base("departments")
{
}

public DbSet<Person> People { get; set; }
}

If the Entity Framework does not find a connection string named “departments” in you config file, it will assume you want a database named departments on the local SQL Express or LocalDb instances (depending on which connection factory is in place).

Finally, if you do not pass any hints to the DbContext constructor, it will also look for a connection string with the same name as your class (DepartmentDb) in the config file.

As you can see, there are lots of options the Entity Framework tries when establishing a connection. The goal of all this work is to make it easy for you to use databases, but when software is misconfigured or not installed correctly, all these options can also make troubleshooting a bit difficult.

Where Are We?

When troubleshooting connection problems with the Entity Framework the first step is to always figure out what server and database the framework is trying to use. If the problems are permission related, the next step is to find a way to make yourself a sysadmin on the server (or at least get yourself in the dbcreator role). If the problem is making a connection to a server instance that doesn’t exist, you can always explicitly configure a connection string for an existing instance of SQL Server.

If all else fails, use SQL Server Compact, as nearly anything you can do with Code-First Entity Framework will work the compact edition of SQL Server.

Levels Of Abstraction In An MVC View

$
0
0

Working on a dashboard I came across a view arranged like the following diagram:

bad dashboard

The scenario is simplified because there is more to do inside of one block than just @SomeOutput, but focus on the structure of the view. I needed to add some more behaviors to the dashboard using CSS and script code, but it only took a few minutes to achieve frustration. Sometimes the view would delegate to a partial view for a specific section of the dashboard, and sometimes the view would inline all the markup and code for a section. Then there was also the odd case of having one partial view responsible for two entire sections of the dashboard, which threw me off entirely. Being new to the code it took some time to figure out how the pieces worked together to produce the page. 

Before I started making my own changes, I did a little refactoring to structure the view like so ...

better dashboard

... and then development life was easier. The mental model of how to map from implementation to output was simplified, and I instantly knew where to go to make different changes.

There are a number of ways you could spin this story. You could argue how the original view violated the single responsibility principle since it was taking responsibility for providing the structure of the dashboard and rendering some of the details. I’d agree with this argument. You could also argue the original view violated the single level of abstraction principle, and I’d agree with that argument, too.

In the end I simply liked the solution better because it seemed simple and symmetrical. Not many people talk about the aesthetic qualities of balance and symmetry in code, but I think it is a sign of craftsmanship that can benefit software by making code easier to understand and maintain. I bet the dashboard changes again in 3 months, and hopefully the next person has an easier time making those changes.

ASP.NET MVC - Highlight Current Link

$
0
0

In an ASP.NET MVC application, there are many different solutions you might use to highlight the menu item for the current location.

Highlight current item

Here's one - a custom HTML helper for building menu items. The custom helper will detect if the link is a link to the current action, and if so the helper adds an additional CSS class to the link (currentMenuItem).

public static MvcHtmlString MenuLink(
this HtmlHelper helper,
string text, string action, string controller)
{
var routeData = helper.ViewContext.RouteData.Values;
var currentController = routeData["controller"];
var currentAction = routeData["action"];

if(String.Equals(action, currentAction as string,
StringComparison.OrdinalIgnoreCase)
&&
String.Equals(controller, currentController as string,
StringComparison.OrdinalIgnoreCase))

{
return helper.ActionLink(
text,action, controller, null,
new { @class="currentMenuItem"}
);
}
return helper.ActionLink(text, action, controller);
}

Use the helper when building a menu in your Layout view.

<li>@Html.MenuLink("Contact", "Contact", "Home")</li>

And don't forget to add some styles to make the current link appear differently from the other links.

ul#menu li a {
background: none;
color: #999;
padding: 5px;
border-radius: 15px;
text-decoration: none;
}

ul#menu li a.currentMenuItem {
background-color: black;
color: white;
}

Another variant would be for the helper check the current controller name only when deciding to mark a link as current.


Async in Entity Framework 6.0

$
0
0

If you pull the latest Entity Framework source from CodePlex, you can take a look at some of the features being added for the next version of EF. These features include an async API for DbContext (SaveChangesAsync and ExecuteSqlCommandAsync), as well as async operations on IQueryable<T> through some new extension methods.

Here is how the async version of SaveChanges looks in an ASP.NET MVC controller action:

[HttpPost]
public async Task<ActionResult> Edit(Thing thing)
{
if(ModelState.IsValid)
{
_db.Entry(thing).State = EntityState.Modified;
await _db.SaveChangesAsync();
return RedirectToAction("Index");
}

return View(thing);
}

The new IQueryable operators are async versions of operators that materialize a concrete result. For example, finding a single entity:

[HttpGet]
public async Task<ActionResult> Edit(int id)
{
var model = await _db.Things.FindAsync(id);
// or
var model = await _db.Things.SingleAsync(t => t.Id == id);

return View(model);
}

Also forcing execution with ToList:

public async Task<ActionResult> Index()
{
var model = new HomeIndexViewModel();
model.Things = await _db.Things.ToListAsync();

return View(model);
}

Getting an application up and running with EF 6 (including migrations) is slightly challenging, but I've found the easiest approach is to msbuild the Nuget.proj file in the NuGet directory, then adding the NuGet\bin\debug directory as a custom local NuGet repository and adding references to EF 6 via NuGet. I also had to register all the EF assemblies for verification skipping with sn -Vr.

My Favorite Visual Studio 2012 Features

$
0
0

I've grown fond of the following features in Visual Studio 2012.

Round Tripping Projects

Because Visual Studio 2012 doesn't convert solution and project files, you can use 2012 even when the rest of the team uses VS2010.

Finally!

Quick Launch

Even when you know where the option or menu item lives, it's often quicker to hit Ctrl+Q and type a few letters to find a command or option.

Visual Studio Quick Launch

SQL Server Object Explorer

It's the real object explorer from SQL Server Management Studio - now available in VS. Go to View -> SQL Server Object Explorer, or use a Ctrl+\, Ctrl+S shortcut. You can manage server logins, drop databases, and open a new, un-crippled query window.

SQL Server Object Explorer

 

Search Solution Explorer

Click in the search box underneath the toolbar, or use Ctrl+; to go there and keep your fingers on the keyboard. It's a great way to find, for example, all CSS files in a project. The search parameter stays in effect until you clear the box, and you get to see the files in the their solution hierarchy. It doesn't search just files, though, you can also find members by name.

Search in Solution Explorer

Open Files Filter

When working with a bunch of open files, trying to find a specific file in the horizontal tabs of the editor can be a pain. The Open Files Filter button in the Solution Explorer toolbar can show only the open files in Solution Explorer, being both vertical and hierarchical, can make open files easier to find.

Open Files Filter

Giving Data to JavaScript

$
0
0

One set of common questions in the world of ASP.NET MVC & JavaScript revolve around getting data from the server into JavaScript. This isn't about pulling data with SignalR or the WebAPI, but questions along the lines of:

- How do I generate an ActionLink in JavaScript and not hard code a URL?

- How do I get the URL for a WebApi?

- How do I get the ID value of something when the user clicks an item in a list?

If your JavaScript lives inside of your view, you can always use a Razor code expression to inject a value directly into the script. However, this doesn't solve all the scenarios listed above, and if your JavaScript is in an external .js file you don't have the ability to use code expressions. Here are a few techniques I've used to pass computed data from the server to the client.

Using <link>

Generating a <link> tag from a view is simple, and the value can represent an action link, a WebAPI endpoint, or a resource like a template. In the case of the WebAPI, for example, you could emit a link tag from a view using Url.RouteUrl (which requires an httproute member in route values to work properly).

<link id="cartApiUrl" 
href ="@Url.RouteUrl("DefaultApi",
new { httproute = "
", controller = "Cart"})"
rel="api"/>

With jQuery it is easy to find the value of the link, and use the value to call the web service.

var cartApiUrl = $("#cartApiUrl").attr("href");
$.post(cartApiUrl + "/" + itemId).then(updateCart);

Data Attributes

Data- (data dash) attributes are popular because you can embed nearly anything inside, and they are easy to consume from jQuery. Let's take the question of "What item did the user click on?".  If the view renders a data- attribute with an identifier inside, the task is trivial. The view code would look something like the following.

<div>                
<img src="@item.ImageUrl" data-itemid="@item.Id" />
</div>

The JavaScript to retrieve the Id of the clicked item can use jQuery.data.

$("img[data-itemid]").click(function () {
var itemId = $(this).data("itemid");
// ...
});

You can even embed JSON data into a data- attribute, and if jQuery detects JSON data (the value starts with { or [), it will try to parse the value inside and give you an object back. This is useful in cases when you need to build options for a widget, like jQuery UI autocomplete, and include a server generated value (like the URL of the action for autocomplete to use as a data source). The view would look like:

<input type="search" name="q" 
data-quicksearch ='{"source":"@Url.Action("Search")",
"minLength":4, "delay":250}'
/>

Then a few lines of JavaScript could wire up autocomplete throughout an application:

$("input[data-quicksearch]").each(function() {
var input = $(this);
var options = input.data("quicksearch");

// You can now use:
// options.source
// options.minLength
// options.delay

input.autocomplete(options);
});

Dumping Data

Yet another option is to dump a data structure into a view for script to consume. One framework to help with this approach is NGon (inspired by Gon in the Rails world). The NGon implementation takes information you put into a NGon property of the ViewBag and serializes the property into JSON. In a controller action you can throw anything into NGon.

public ActionResult Index()
{
ViewBag.NGon.Count = 3;
ViewBag.NGon.Name = "Home";
ViewBag.NGon.OtherStuff = new[]{2, 4, 6};
ViewBag.NGon.Thing = new Thing
{
Id = 5,
Name = "Home"
};

return View();
}

Then place the serialized data into your view using an HTML helper provided by NGon:

@Html.IncludeNGon()

And on the client, all the values are available to your script code.

var count = ngon.Count;
var thingName = ngon.Thing.Name;

NGon doesn't have a NuGet package and still uses the .NET JavaScriptSerializer (instead of Json.NET). Perhaps there is a pull request in Alex's future.

Working with Enums and Templates In ASP.NET MVC

$
0
0

Imagine you have the following types defined.

public class Movie
{
public int Id { get; set; }
public string Title { get; set; }
public MovieGenre Genre { get; set; }
}

public enum MovieGenre
{
Action,
Drama,
Adventure,
Fantasy,
Boring
}

If you want to display MovieGenre, the DisplayFor helpers generally give you what you expect (i.e. @Html.DisplayFor(m=> m.Genre) displays "Adventure"), but EditorFor will only give you a text input because the framework treats an enum the same as a string.

Default EditorFor with enum

If the user knows your enum values they can type in a value and model binding works correctly, but we certainly don't want users to guess the valid values. A better approach would use a drop down list, or a set of radio buttons, to constrain and guide the user's input. There are a few articles on the web showing how to build a drop down list from enums (Stuart Leeks has a good one - Creating a DropDownList helper for enums). I wanted to try a slightly different approach using templates and supporting localization. If you are familiar with templates in ASP.NET MVC, see Brad Wilson's series on templates and metadata).

Template Selection

The first challenge is getting the MVC framework to select a custom template when it sees @Html.EditorFor(m => m.Genre). If you create a view named MovieGenre.cshtml and place it in the ~/Views/Shared/EditorTemplates folder, the MVC runtime will use the template and you can place inside the template any custom markup you want for editing a Genre. However, trying to have a single generic template (Enum.cshtml) for all enums won't work. The MVC framework sees the enum value as a simple primitive and uses the default string template. One solution to change the default framework behavior is to write a custom model metadata provider and implement GetMetadataForProperty to use a template with the name of "Enum" for such models.

public override ModelMetadata GetMetadataForProperty(
Func<object> modelAccessor, Type containerType, string propertyName)
{
var result = _inner.GetMetadataForProperty(modelAccessor, containerType, propertyName);
if (result.TemplateHint == null &&
typeof(Enum).IsAssignableFrom(result.ModelType))
{
result.TemplateHint = "Enum";
}
return result;
}

The "_inner" field represents the default metadata provider. Depending on how you want to setup the runtime, _inner could also be a call to the base class if you derive from CachedDataAnnotationsModelMetadataProvider. Regardless of the approach, the above code will rely on another provider to do the hard work. The code only throws in "Enum" as the template name to use if there is no template name specified and the model type derives from Enum.

The Template

With a custom metadata provider in place the runtime will locate and use an Enum template when a view uses EditorFor against a MovieGenre property.

Editor templates in place and ready!

The implementation of the template is straightforward. Regardless of the type of UI you want, you'll need to use Enum.GetValues to get all the possible values of the enumeration. You can then use the values to build a drop down list, radio buttons, anything you can image. The following code would render a simple drop down list.

@model Enum

@{

var values = Enum.GetValues(ViewData.ModelMetadata.ModelType).Cast<object>()
.Select(v => new SelectListItem
{
Selected = v.Equals(Model),
Text = v.ToString(),
Value = v.ToString()
});
}

@Html.DropDownList("", values)

Localization and Display Name Customization

Things get a little more complicated in the view if you want to customize the text display of an enum value, or if you want to localize the text using resource files. The Display attribute does most of the work, but as far as I can tell the code has to dig out the attribute on its own (there is no help from the MVC metadata provider). For example, take the following definition for MovieGenre.

public enum MovieGenre
{
[Display(ResourceType = typeof(Resources.Translations), Name = "Action")]
Action,

[Display(Name="Drama!")]
Drama,

Adventure,

Fantasy,

Boring
}

The following template code will display the proper text value, even localized, to the user.

@using System.ComponentModel.DataAnnotations
@model Enum

@{

Func<object, string> GetDisplayName = o =>
{
var result = null as string;
var display = o.GetType()
.GetMember(o.ToString()).First()
.GetCustomAttributes(false)
.OfType<DisplayAttribute>()
.LastOrDefault();
if (display != null)
{
result = display.GetName();
}

return result ?? o.ToString();
};

var values = Enum.GetValues(ViewData.ModelMetadata.ModelType).Cast<object>()
.Select(v => new SelectListItem
{
Selected = v.Equals(Model),
Text = GetDisplayName(v),
Value = v.ToString()
});
}

@Html.DropDownList("", values)

I'd want to measure the performance of the template if it is heavily used in a busy application, but the idea here is to use this approach if you want to create some fancy markup in the template. If all you want to do is ultimately call Html.DropDownList, a custom HTML helper approach is simpler.

Seeding Membership & Roles in ASP.NET MVC 4

$
0
0

Jon Galloway has an overview of the new membership features in ASP.NET MVC 4. The Internet project template moves away from the core membership providers of ASP.NET and into the world of SimpleMembershipProvider and OAuth.

There is quite a bit I could write about the new features and the code generated by the Internet project template, but for this post I just want to cover a scenario I've demonstrated in the past - seeding the roles and membership tables. If you are using Entity Framework code-first migrations it's relatively easy to add some code to the Seed method of the migrations configuration to populate the membership tables with some initial roles and users. Just remember every update-database command will call the Seed method, so you have to write the code to make sure you don't try to create duplicate data.

First, the new project template creates an MVC 4 Internet application without any provider configuration, but for the membership features to work properly during a migration, it appears you need at least some configuration. The following code makes sure the SimpleMembershipProvider and SimpleRolesProvider are in place.

<roleManager enabled="true" defaultProvider="simple">
<providers>
<clear/>
<add name="simple" type="WebMatrix.WebData.SimpleRoleProvider,
WebMatrix.WebData"
/>
</providers>
</roleManager>
<membership defaultProvider="simple">
<providers>
<clear/>
<add name="simple" type="WebMatrix.WebData.SimpleMembershipProvider,
WebMatrix.WebData"
/>
</providers>
</membership>

Then inside the Seed method of the DbMigrationsConfiguration<T> derived class, you can have:

protected override void Seed(MovieDb context)
{
//context.Movies.AddOrUpdate(...);

// ...

SeedMembership();
}

private void SeedMembership()
{
WebSecurity.InitializeDatabaseConnection("DefaultConnection",
"UserProfile", "UserId", "UserName", autoCreateTables: true);

var roles = (SimpleRoleProvider) Roles.Provider;
var membership = (SimpleMembershipProvider) Membership.Provider;

if (!roles.RoleExists("Admin"))
{
roles.CreateRole("Admin");
}
if (membership.GetUser("sallen",false) == null)
{
membership.CreateUserAndAccount("sallen", "imalittleteapot");
}
if (!roles.GetRolesForUser("sallen").Contains("Admin"))
{
roles.AddUsersToRoles(new[] {"sallen"}, new[] {"admin"});
}
}
Viewing all 513 articles
Browse latest View live