Automatic migrations with Entity Framework 4.3


This blog post is a tutorial on configuring automatic schema-migrations using Entity Framework 4.3 in an ASP.NET MVC application (we’ll do a post on doing the same with NHibernate soon). Having your application automatically update its database schema greatly eases development and makes frequent deployments to platforms like AppHarbor a cinch.

Why you want automatic migrations

At AppHarbor, we try to make deploying new versions of your code as fast and safe as possible. An important part of dependable application deployment procedures are safe and correct schema-migrations of any underlying datastore. If you are using a schema-less NoSQL datastore like RavenDB, CouchDB or MongoDB, this is probably not a big problem. If you’re using a traditional SQL-based datastore like Microsoft SQL Server or MySQL, migrations are an important concern.

Because AppHarbor makes deployment relatively painless, you’ll likely end up deploying more frequently than you’re used to. Frequent deploys makes automated schema-management important. If it’s a manual and error-prone chore, it will make pushing new versions of your code less attractive and this negates some of the advantages you get from running on AppHarbor. With dependable, automatic migrations in place, you can fearlessly push new versions of your code without worrying whether the underlying data-schema is in sync with your code.

When schema-updates should be triggered

We often get questions from users asking how they can incorporate schema-updates as part of AppHarbor building their code. Schema-migrations during builds is a bad idea, however. This is because your schema and code can get out of sync in a number of ways:

  • AppHarbor runs unit tests after the build and if any of the unit tests fail, the code is not deployed. You will then have an old version of your code running on the new database schema

  • Schema updates are not run if you roll back your application to a previous version of your code. If you roll back and the migration is not run, old code will be running with the newest version of the database schema

  • On AppHarbor there’s is a lag between the build completing and the code getting deployed during which time running code and schema will be out of sync

A much better approach is to place the code someplace where you know it’ll get called at least once before any other code in your app is executed when it’s deployed anew. For ASP.NET MVC applications, Application_Start() is a good bet. Alternatively, if the check to see if the schema is up-to-date is fast or can be cached, running the update whenever you instantiate your repositories also works. In the tutorial below, we will use Entity Framework’s OnModelCreating(DbModelBuilder modelBuilder) method to configure migrations.

Note that Application_Start() and any repository initilization might get called many times for any one deployed version of your app. On AppHarbor, for example, Application_Start() might get called multiple times if your application pool is recycled and started again or if your application is scaled to multiple web workers each starting up their own instance of your code. This makes it very important that your schema-updates are idempotent, i.e. implemented in such a way that running them multiple times won’t cause trouble.

Entity Framework Code First

As mentioned in the introduction, the example we’re building is an Entity Framework-backed ASP.NET MVC app. The application will be split into two projects, “Web”, an ASP.NET MVC web site, and “Core”, a class library. “Core” has all the interesting bits, the website is only included to demonstrate that the migrations are actually working. Here’s a screenshot showing the finished solution in all it’s simplicity.

Finished overview

The finished “Core” contains the following classes:

  • Entity.cs – base class for all model classes, has Id property (required by Entity Framework)
  • User.cs – lone model class (you can add more)
  • Configuration.cs – where migration behaviour is configured
  • Context.cs – the context used to manipulate entities and where migrations are enabled

To start out, let’s set up a standard Entity Framework Code First data store. First create the Core class library project and install Entity Framework from the NuGet package manager console:

install-package EntityFramework -ProjectName Core

Then add these classes:

Entity.cs:

namespace Core.Model
{
    public abstract class Entity
    {
        public int Id { get; set; }
    }
}

User.cs:

namespace Core.Model
{
    public class User : Entity
    {
        public string Name { get; set; }
    }
}

Context.cs:

using System.Data.Entity;
using Core.Model;

namespace Core.Persistence
{
    public class Context : DbContext
    {
        public DbSet<User> Users { get; set; }
    }
}

…and that’s it for Core project for now. Go ahead and create the Web project (this tutorial uses Haack’s Really Empty MVC 3 project template). For development storage, we’ll be using SQL Server Compact and installing EntityFramework.SqlServerCompact gets us the necessary packages:

install-package EntityFramework.SqlServerCompact -ProjectName Web

Add a project reference to the Core project and add HomeController.cs:

using System.Web.Mvc;
using Core.Model;
using Core.Persistence;

namespace Web.Controllers
{
    public class HomeController : Controller
    {
        private readonly Context _context = new Context();

        public ActionResult Index()
        {
            return View(_context.Users);
        }

        public ActionResult Create(User user)
        {
            _context.Users.Add(user);
            _context.SaveChanges();

            return RedirectToAction("Index");
        }
    }
}

Add a Home directory in Views and an Index.cshtml view:

@model IEnumerable<Core.Model.User>

<h2>Index</h2>

<ul>
    @foreach (var user in Model)
    {
        <li>@user.Name</li>
    }
</ul>

@using(Html.BeginForm("Create", "Home", FormMethod.Post))
{
    <input type="text" name="Name" />
    <input type="submit" value="Submit" />
}

Now create an App_Data directory in the Web project for SQL Server CE to store its files and then configure the connection in Web.config:

<connectionStrings>
    <add name="context" connectionString="Data Source=|DataDirectory|data.sdf"
            providerName="System.Data.SqlServerCe.4.0" />
</connectionStrings>

Hitting F5 should result in a web form that you can use to add users to the database.

Automatic migrations

First, try changing the User model class by adding an additional property

namespace Core.Model
{
    public class User : Entity
    {
        public string Name { get; set; }
        public string EmailAddress { get; set; }
    }
}

And update the view accordingly:

@model IEnumerable<Core.Model.User>

<h2>Index</h2>

<ul>
    @foreach (var user in Model)
    {
        <li>@user.Name (@user.EmailAddress)</li>
    }
</ul>

@using(Html.BeginForm("Create", "Home", FormMethod.Post))
{
    <input type="text" name="Name" />
    <input type="text" name="EmailAddress" />
    <input type="submit" value="Submit" />
}

If you try to run the app now, Entity Framework will throw an exception stating that the model has changed and that you should be using migrations. In this tutorial we will use automatic migrations (if your application requires very elaborate migrations then Entity Framework also does code-based migrations). Configuring automatic migrations is extremly simple, just add a configuration class to the Core project:

using System.Data.Entity.Migrations;

namespace Core.Persistence
{
    public class Configuration : DbMigrationsConfiguration<Context>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = true;
            AutomaticMigrationDataLossAllowed = true;
        }
    }
}

(AutomaticMigrationDataLossAllowed is optional. Without it, Entity Framework will throw an exception if it’s about to do a migration that involves dropping columns or tables).

Finally add this OnModelCreating method to the Context class:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    Database.SetInitializer(new MigrateDatabaseToLatestVersion<Context, Configuration>());
}

That’s it! Hit F5 and your app is in business with any previous data intact (less any dropped entities or columns) and the database schema automatically updated to reflect the new model.

Deploying to AppHarbor

The best thing is that all this deploys and works seamlessly on AppHarbor. The only thing lacking on the code is a Web.Release.config transform that changes the providerName attribute in the connectionstring from System.Data.SqlServerCe.4.0 to System.Data.SqlClient:

<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
  <connectionStrings>
    <add xdt:Locator="Condition([@name='context'])" providerName="System.Data.SqlClient"
        xdt:Transform="SetAttributes" />
  </connectionStrings>
</configuration>

You also need add the SQL Server add-on to your application and set the alias to “context” (see screenshot below). This will make AppHarbor overwrite your SQL Server Compact Edition connectionstring with one that will work on AppHarbor.

Setting connectionstring alias

Wrap up

So there you have it. Entity Framework Code First is delightfully simple to configure and use and with the migrations features released in 4.3, managing schemas while developing and deploying fast-changing apps is no longer a chore.

Full source code for this blog post is available here: https://github.com/friism/CodeFirstMigrations

Introducing the AppHarbor Command Line Utility


 

We’re happy to announce the release of the AppHarbor CLI. This utility gives you complete control over your applications using simple commands. After logging in, you can create new applications, retrieve build history, and manage configuration variables and host names.

Get started by downloading and installing the utility. The installer will add it to your system path.

Download AppHarbor CLI

In the first version, the following commands are supported. The commands at the end in parentheses are shortcuts that you can use directly. This will be demonstrated in the examples below.

app                         #  List your applications
app create [name]           #  Create an application ("create")
app delete                  #  Delete application
app info                    #  Get application details
app link [slug]             #  Link directory to an application ("link")
app unlink                  #  Unlink application from directory ("unlink")
build                       #  List latest builds
config add [key=value]      #  Add configuration variable to application
config                      #  List all configuration variables
config remove [key1 key2..] #  Remove configuration variable
help                        #  Display help summary
hostname add [hostname]     #  Add a hostname
hostname                    #  List all associated hostnames
hostname remove [hostname]  #  Remove hostname from application
user login                  #  Login to AppHarbor ("login")
user logout                 #  Logout of AppHarbor ("logout")
user                        #  Show currently logged in user

Example: Create a new application

Begin by opening a command prompt and logging with your AppHarbor user information.

c:dev>appharbor user login
Username: js
Password: **********************
Successfully logged in as js

Create a new directory for your app and use the create shortcut to create the app with AppHarbor and initialize the directory with the Git settings your application needs to push and deploy your code to AppHarbor’s servers.

c:dev>mkdir MyFancyApp
c:dev>cd MyFancyApp

c:devMyFancyApp>appharbor create MyFancyApp
Created application "myfancyapp" | URL: https://myfancyapp.apphb.com

Git repository is not initialized in this folder. 
Do you want to initialize it (type "y")? y

Git repository was initialized with default .gitignore file.
Added "appharbor" as a remote repository. 
Push to AppHarbor with git push appharbor master.

Example: Link an existing application

If you already have an app in a folder configured for use with AppHarbor, you can link it to the existing application so that you can use the CLI commands to manage configuration variables and hostnames.

Navigate to the folder that contains your application and use the link command to tie it to the specified AppHarbor application slug. If the appharbor remote doesn’t exist, it will be created for you.

c:dev>mkdir MyExistingApp

c:dev>cd MyExistingApp

c:devMyExistingApp>appharbor link myexistingapp
Added "appharbor" as a remote repository. 
Push to AppHarbor with git push appharbor master.

Add Spotify, Rdio, and GitHub’s Gist Embeds To Your Site


Embed music from Spotify by right-clicking any song, album, or artist in Spotify and selecting “Copy HTTP Link” or “Copy Spotify URI”:

Then paste that into your post editor, making sure that it’s located on its own line all by itself. You’ll end up with something like this when you view your post:

Rdio

If you’re an Rdio user, you can embed music from them too. Copy the URL from your address bar when looking at a track, artist, or playlist and paste that into your post editor. Here are a few examples:

If you use the Mac application for Rdio you can copy URLs from there as well. If you click the “Share” button you’ll see a URL to copy right at the top. Paste that in to your post editor and you’re all set.

GitHub’s Gist

We’re big fans of the code repository website GitHub here at Automattic and many of us use their Gist code snippets website. While we already have a cool way to embed code into your site, we realize many of you want to post Gist-hosted snippets too so starting today you can. Again, just copy/paste the URL out of your address bar onto its own line in the post editor.

<?php
$query_args = array(
‘foo’ => ‘bar’,
‘apple’ => ‘orange’,
‘posts_per_page’ => 50,
‘offset’ => 0,
);
$some_posts = new WP_Query( $query_args );
while ( $some_posts->have_posts() ) {
/*
* Do some stuff here
*/
// Get more posts
$query_args['offset'] = $query_args['offset'] + $query_args['posts_per_page'];
$some_posts = new WP_Query( $query_args );
}


 

via Add Spotify, Rdio, and GitHub’s Gist Embeds To Your Site.

Integrate Cool Applications with WordPress.com


Integrate Cool Applications with WordPress.com.

The API gives developers access to posts and comments, as well as the ability to Follow, Like, or Reblog content for users. Other features from WordPress.com, like the daily handpicked content on Freshly Pressed, are also available through the API.

An excellent example of an application that uses the new API is the Windows 8 WordPress.com app, available now.

Our goal with the new API is to simplify the experience of using and adding to the data available on WordPress.com. To do this, we now use the OAuth2 protocol to authenticate requests for data. To retrieve public data, you can make unauthenticated requests. To perform actions, such as making new posts or comments, you would need to make authenticated requests. When the API returns data, we now return a standardized JSON object for ease-of-use.

The REST API also self-documents itself; as we add new endpoints, the documentation on our Developer Resources blog will auto-update to provide you with the latest information. In addition, you’ll also have access to a Developer Console, which will allow you to run real REST API queries and see real JSON data directly in your web browser. You can read more about the Console here.

Ready to build an app and integrate it with WordPress.com? Great! You can now sign up for and manage your OAuth2 tokens without waiting through an approval cycle. If you have any questions or feedback on the API, please get in touch with us. Make sure to follow the Developer Resources blog for news, updates, and documentation about the REST API and other awesome services we are making available to developers seeking to integrate with WordPress.com.

Adobe launches its Creative Suite to support 10 Indian languages


Technology giant Adobe on Tuesday launched the latest version of its Creative Suite of products with enhanced functionalities and support for 10 Indian languages in its InDesign software in the country.

Image

Creative Suite is a collection of graphic design, video editing, and web development applications like Photoshop, Acrobat, InDesign and Illustrator.

Aimed specially at the professionals in designing, media and entertainment industries, the new software ‘Creative Suite 6’ (CS6) would be available in four suites — Master Collection (Rs 1.56 lakh), Design and Web Premium, and Production Premium (Rs 1.14 lakh) each and Design Standard (Rs 78,288).

“This release is particularly significant for the large Indian creative community, which is riding a wave of digital printing, media and connectivity proliferation in the country,” Adobe Systems Managing Director South Asia Umang Bedi told reporters in New Delhi.

India’s media and entertainment industry is expected to register a CAGR of 15 per cent to reach Rs 1,457 billion by 2016, according to a recent FICCI-KPMG report and that is the market we are looking at, he added.

Bedi is confident that the new products will help the company strengthen its presence in the Indian market.

“India is a very strong market for us and that is evident from the fact that about 33 per cent of our workforce is here…For a long time, we felt that our products should have support for Indian languages and in the new InDesign software, there is support for 10 Indian languages,” he said.

The company does not disclose country-specific revenue details.

Adobe has also extended its online store to help consumers pay for the software in Indian rupees.

Source :http://www.thehindu.com

 

A New Look for the +1 Button


When your visitors come across something interesting on your site, sometimes you want to encourage a simple endorsement (like +1). Other times, however, you want to help visitors share with their friends, right away. Today’s new Google+ Share button lets you do just that.

In line with the design of the new +1 button, here’s how it looks:

Before visitors share:



When clicked, visitors can add a comment and choose who to share with:


After they’ve shared, the button turns red. They can click to share again.

The new Google+ Share button is available to all publishers, globally. Try adding it to your site now – just visit Google Developers to get the code.

Today, we released the new +1 button from preview and it’s now rolling out to all users. You may also notice the numbers in your +1 buttons increase, as we update our plugins to better reflect social activity around your content. Our Webmaster Tools Help Center article has more details on this update.  Join the conversation on Google+.

Following in the footsteps of our new red and white Google+ icon, the +1 button is sporting a fresh coat of paint. Starting today, this update will be visible first to our Google+ Platform Preview Group and shortly thereafter we’ll roll it out to the public.

Check out the new pixels:


Before you’ve +1’d 



After you’ve +1’d 

The +1 buttons you’ve already installed will automatically update; there’s nothing you need to do. Stop by the updated configuration tool to see how these changes look across all the various sizes and shapes of the +1 button.

We’ll update this post when these changes graduate to the public.

Why Programmers Should Use the Haskell Language – Application Development


Haskell is a standardized, general-purpose, purely functional programming language, with non-strict semantics and strong static typing. In computer science and computer programming, a type system is said to feature strong typing when it specifies one or more restrictions on how operations involving values of different data types can be intermixed. The opposite of strong typing is weak typing. “Strong typing” implies that the programming language places severe restrictions on the intermixing that is permitted to occur. This prevents the compiling or running of source code, which prevents data from being used in an invalid way. Haskell is named after logician Haskell Curry. In Haskell, “a function is a first-class citizen” of the programming language. As a functional programming language, the primary control construct is the function. The language is rooted in the observations of Curry and his intellectual descendants, that “a proof is a program; the formula it proves is a type for the program.” At Microsoft’s Lang.Next conference on the software giant’s Redmond, Wash., campus, a varied group of leading software language geeks met to discuss the future of programming. The group included Andy Adams-Moran, a founder of Galois, a Portland, Ore., firm that provides unique R&D capability for government and commercial clients. Galois applies revolutionary mathematical, computer science and engineering approaches to solve critical problems in software security, safety, privacy and performance. Galois has been instrumental in bringing cutting-edge research into practice for the U.S. Department of Defense, U.S. Department of Energy, the country’s various intelligence agencies, and biotechnology and aerospace companies. In all its projects, Galois employs Haskell. Adams-Moran has been using Haskell since 1991 and said that while he and his colleagues use other languages, “We always come back to Haskell.” Here, eWEEK looks at why Adams-Moran continues to rely on Haskell and why other developers should check it out as well.