Entityframework 4.3 code first & Migration

I wasn’t a fan of code first when it was released with EF 4. It is lack of data schema migration support. Every time you have schema updates, the database needs to be recreated using the Initializer. With EF Migration shipped out with EF 4.3, It resolves my issue.

Here I created a sample to demonstrate the migration process of EF 4.3, to prove it works with all scenarios. I create the POCOs with three different kinds of relationships and variable types of properties.


The database diagrams show the facts as below,

User to Addresses => one to many relation
User to Profiles => one to one relation
User to Lessons => many to many relation


public class User
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }

public byte Gender { get; set; }
public bool? IsMarried { get; set; }

//one to many relationship
public virtual ICollection<Address> Addresses { get; set; }

//one to one relationship
public virtual Profile Profile { get; set; }

//many to many relationship
public virtual ICollection<Lesson> Lessons { get; set; }

Profile POCO

    public class Profile
        public int UserId { get; set; }

        public string FirstName { get; set; }
        public string LastName { get; set; }

        public virtual User User { get; set; }

Address POCO

    public class Address
        public int Id { get; set; }
        public string Street { get; set; }
        public string State { get; set; }

        public virtual User User { get; set; }

Lesson POCO

    public class Lesson
        public int Id { get; set; }
        public string Name { get; set; }

        public virtual ICollection Users { get; set; }

And create the Context class to inherit from DbContext, and add DbSets to it.

public class CodeFirstExampleContext :DbContext
public DbSet<User> Users { get; set; }
public DbSet<Address> Addresses { get; set; }
public DbSet<Profile> Profiles { get; set; }
public DbSet<Lesson> Lessons { get; set; }

Also make sure you have your connection string inside the web.config/ app.config file.

<add name="CodeFirstExampleContext" connectionString="Data Source=(local)\SQLEXPRESS;Initial Catalog=CodeFirstExample;integrated security=True" providerName="System.Data.SqlClient" />

Now, I can write some code to add some records using the model that I created. And when the execution tries to talk to the database, it will create the database for you.

I put some test code inside the HomeController, Index action method.

        public ActionResult Index()
            Data.User user = new Data.User();
            user.Name = "superwalnut";
            user.Email = "superwalnut@test.com";
            user.Profile = new Profile()
                FirstName = "kev",
                LastName = "wam"
            user.Addresses = new List</pre>
<address>(){ new Address{ Street = "test st", State = "test state" } }; CodeFirstExampleContext context = new CodeFirstExampleContext(); context.Users.Add(user); context.SaveChanges(); return View(); } 

Run the application, your database should be automatically created based on your models.

Now let’s change the User model, add two more columns in.

        public byte Gender { get; set; }
        public bool? IsMarried { get; set; }

How do we update the schema???

No worries. (I am testing using EF4.3.1)

Open Package Manager Console, and type

PM> Enable-Migrations

After you execute this command, it will create a folder inside your project. “Migrations”


Open the Configuration.cs file, you need to manually update the context type


Now you are all set to update schemas, after you have updated the User POCO, type the following command in Package Manager Console.

PM> Add-Migration

It will compare the database schema and your current models and generates a class that contains update methods. You can give a proper name for the generated class. Such as “Added User Gender IsMarried”.

The file will look like “201203270149267_Added User Gender IsMarried.cs”

Now type command in Package Manager Console to update database.

PM> Update-Database

Your database is updated after execution.

With column default values

If you already have records in the database for table User, for the newly added columns Gender (byte) and IsMarried (bool?), they will be given a default value 0. If it is nullable, null is given.

If you want to set existing records with special default values, you need to write Sql scripts in the Migration class Up method. Like below,

Sql("Update User Set Gender = 1");

To checkout the sample project code, go to codeplex


You will need to “Enable Nuget Package Restore” by right clicking your solution file after you download the source from codeplex TFS.


Render modal dialog from a PartialView, client side validation not working

While I am using JQuery to render a modal popup, and the popup content is read from a controller action with a partialview returned. The client side validation is not fired.

Here is a piece of sample code, I am using bootstrap modal to render the modal popup.

var url = "/Feed/Save/" + id;
        $.get(url, null, function (html) {

You need to add a line to parse unobtrusive validator,


After the modified the code, it all works fine,

var url = "/Feed/Save/" + id;
        $.get(url, null, function (html) {

Bootstrap from Twitter is missing a date-picker

Bootstrap is awesome, light weight. I think it is a great replacement of JQuery UI. But there are still a few elements missing from Bootstrap. Such as the very important one: date picker.

I found someone has done a plugin for it. It is pretty cool.

Here it is. http://www.eyecon.ro/bootstrap-datepicker/

To create a date picker, write the markups as follow,

    <div class="input-append date" id="dp3">
    <span class="add-on"><i class="icon-th"></i></span>


Call the javascripts,


There are a few events that you can register as well,


This event fires immediately when the date picker is displayed.


This event is fired immediately when the date picker is hidden.


This event is fired when the date is changed.

    .on('changeDate', function(ev){
    if (ev.date.valueOf() < startDate.valueOf()){


Good stuff!

Leak outs Microsoft RDP vulnerability exploit

Microsoft’s estimate that it would take ne’er-do-wells 30 days to exploit the recently discovered RDP vulnerability appears to be wide of the mark, following the apparent leaking of working proof-of-concept code.
The flaw, patched by the MS12-020 Security Update released by Microsoft last Tuesday, allows remote attackers to execute code under the ‘system’ privilege level. As the attack requires no authentication, it represents a serious threat to any system running Remote Desktop Protocol (RDP) and connected to the internet – some five million machines, according to security researcher Dan Kaminsky.
In mitigation, Microsoft claimed that the complexity of the flaw meant that it was ‘not trivial‘ to produce a working exploit for the flaw, saying that ‘we would be surprised to see one developed in the next few days.‘ Instead, the company predicted that it would take around 30 days for the vulnerability to be actively exploited, giving affected customers time to review and install the patch or implement a workaround.
Sadly, it looks like Microsoft has been caught by surprise after all: a working proof-of-concept has appeared on the internet, giving attackers the code required to readily and easily exploit the security vulnerability.
The code doesn’t appear to have been developed independently, either. Security researcher Luigi Auriemma, who spotted the flaw and provided a proof-of-concept to Microsoft via TippingPoint’s Zero Day Initiative (ZDI) cash-for-bugs security programme, claims that the public proof-of-concept code contains the exact same packet he crafted in his submission to Microsoft. The implication: somebody at Microsoft or TippingPoint leaked the information to the bad guys.
Microsoft, naturally, denies doing any such thing. Instead, the company claims that the leak may have come from one of its Microsoft Active Protections Programme (MAPP) partners, of which ZDI is a member. ‘The details of the proof-of-concept code appear to match the vulnerability information shared with Microsoft Active Protections Programme partners,‘ the company’s director of trustworthy computing Yunsun Wee admits. ‘Consistent with the charter of the MAPP program, we released details related to the vulnerabilities addressed in MS12-020 to MAPP partners under a strict Non-Disclosure Agreement in advance of releasing the security bulletin.
Microsoft is actively investigating the disclosure of these details and will take the necessary actions to protect customers and ensure that confidential information we share is protected pursuant to our contracts and programme requirements,‘ Wee adds.
Those who have installed the MS12-020 patch, either manually or via Windows Update, are protected against exploitation of the flaw.


This is re-blogged from, http://www.bit-tech.net/news/bits/2012/03/19/leak-outs-rdp-exploit/1

Mr. Data Converter, converting csv to other formatted strings

This is a pretty cool JS plugin to convert csv formatted string to other formats.

It supports XML – Properties, XML – Nodes, JSON – Properties, JSON – Column arrays, JSON – Row arrays, Html tables, and others.

I found it very helpful for xml, JSON and html formats.

for example, a csv string as below,

ProviderName, ProviderID, OrganizationName

The converted JSON – properties looks like,

[{"ProviderName":"Microsoft"," ProviderID":"jamcracker"," OrganizationName":"Telstra"}]

The converted JSON – Column array looks like,

  " ProviderID":["jamcracker"],
  " OrganizationName":["Telstra"]

The converted JSON – Row array looks like,


The converted XML – Properties look like,

<?xml version="1.0" encoding="UTF-8"?>
  <row ProviderName="Microsoft"  ProviderID="jamcracker"  OrganizationName="Telstra" ></row>

The converted XML – Nodes look like,

<?xml version="1.0" encoding="UTF-8"?>
    < ProviderID>jamcracker</ ProviderID>
    < OrganizationName>Telstra</ OrganizationName>

The converted Html tables look like,

      <th class="ProviderName-cell">ProviderName</th>
      <th class=" ProviderID-cell"> ProviderID</th>
      <th class=" OrganizationName-cell"> OrganizationName</th>
    <tr class="lastRow">
      <td class="ProviderName-cell">Microsoft</td>
      <td class=" ProviderID-cell">jamcracker</td>
      <td class=" OrganizationName-cell">Telstra</td>

So cool, isn’t it. Save tons of time for my development.

It is from the website, http://www.shancarter.com/data_converter/index.html

And to download from Github, https://github.com/shancarter/Mr-Data-Converter

Create a JQuery plugin for twitter-bootstrap “Confirm Modal popup”

There is a situation that we need user to confirm before they proceed their action. You don’t want to accidently delete very important information. So I come up the idea to extend the bootstrap modal popup to create a confirm modal before calling the function to delete some stuff.

(function ($) {
        //pass the options variable to the function
        confirmModal: function (options) {
            var html = '<div class="modal" id="confirmContainer"><div class="modal-header"><a class="close" data-dismiss="modal">×</a>' +
            '<h3>#Heading#</h3></div><div class="modal-body">' +
            '#Body#</div><div class="modal-footer">' +
            '<a href="#" class="btn btn-primary" id="confirmYesBtn">Confirm</a>' +
            '<a href="#" class="btn" data-dismiss="modal">Close</a></div></div>';

            var defaults = {
                heading: 'Please confirm',
                body:'Body contents',
                callback : null

            var options = $.extend(defaults, options);
            html = html.replace('#Heading#',options.heading).replace('#Body#',options.body);
            var context = $(this);


Basically,  all you need to do in the UI, is to create a link to activate the confirm modal, and a empty div for my plugin to work with. With options, you can pass in modal heading and modal content body. With callback method, is your logic to delete stuff or something you want to do originally.

<script type="text/javascript">
$(function () {
$("#openConfirmModal").click(function () {
heading: 'Confirm to delete',
body: 'Are you sure you want to delete this record?',
callback: function () {
alert('callback test');
<a href="#" id="openConfirmModal">Open Confirm Modal</a>
<div id="confirmDiv"></div>

A SQL server search plugin, from Redgate

It is free.


You can download it from this link http://www.red-gate.com/products/sql-development/sql-search/

After the installation, you can see the button in your Sql server management studio. “SQL Search”




Type the keywords and change the filters to find whatever objects contain your keywords. A great tool for a complex database which has more than 200 tables and stored procedures.

Bootstrap from Twitter, timer saver for the UI designs

Bootstrap is just CSS, but it’s built with Less (Dynamic stylesheet) http://lesscss.org/ .

It is very easy to implement, just drop the code and go. Less can be accomploshed via javascript. Once it is compiled, bootstrap only contains CSS.

What it contains:


  • reset.less A CSS reset for our use to remove unnecessary elements
  • preboot.less Color variables for things like gradients, transparencies, and transitions to simplify vendox-prefixed CSS blocks to one line of code each
  • scaffolding.less Basic and global styles for generating a grid system, structural layout, and page templates
  • type.less Headings, body text, lists, code, and more for a versatile and durable typography system
  • patterns.less Repeatable interface elements like navigation, modals, popovers, and tooltips to take you beyond the default scaffolding styles
  • forms.less Durable styles for various input types, form layouts, and control states.
  • tables.less Styles for tabular data in a number of varied displays

And Javascript (JQuery) Plugins,

  • Modals, A streamlined, but flexible, take on the traditional javascript modal plugin with only the minimum required functionality and smart defaults.
  • Tooltips,A new take on the jQuery Tipsy plugin, Tooltips don’t rely on images—they use CSS3 for animations and data-attributes for local title storage.
  • Collapse,Get base styles and flexible support for collapsible components like accordions and navigation.
  • Dropdowns, Add dropdown menus to nearly anything in Bootstrap with this simple plugin. Bootstrap features full dropdown menu support on in the navbar, tabs, and pills.
  • Popovers, Add small overlays of content, like those on the iPad, to any element for housing secondary information.
  • Carousel, Create a merry-go-round of any content you wish to provide an interactive slideshow of content.
  • Scrollspy, Use scrollspy to automatically update the links in your navbar to show the current active link based on scroll position.
  • Aelrt Messages, The alert plugin is a tiny class for adding close functionality to alerts.
  • Typeahead, A basic, easily extended plugin for quickly creating elegant typeaheads with any form text input.
  • Togglable tabs, Use this plugin to make tabs and pills more useful by allowing them to toggle through tabbable panes of local content.
  • Buttons, Do more with buttons. Control button states or create groups of buttons for more components like toolbars.
  • Transitions, For simple transition effects, include bootstrap-transition.js once to slide in modals or fade out alerts.

Bootstrap at Nuget: http://nuget.org/packages/Twitter.Bootstrap

Less CSS: http://lesscss.org/

Media Queries: http://www.w3.org/TR/css3-mediaqueries/  (a smart example how to implement media queries http://mediaqueri.es/)


Icon for package Twitter.Bootstrap