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.

image

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

User POCO

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
    {
        [Key]
        [ForeignKey("User")]
        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.

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

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”

image

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

image

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

http://codefirstmigration.codeplex.com/

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

image

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) {
            $("#saveFeed").html(html);
            $("#saveFeedModal").modal('show');
        });

You need to add a line to parse unobtrusive validator,

            $.validator.unobtrusive.parse($("#saveFeed"));

After the modified the code, it all works fine,

var url = "/Feed/Save/" + id;
        $.get(url, null, function (html) {
            $("#saveFeed").html(html);
            $.validator.unobtrusive.parse($("#saveFeed"));
            $("#saveFeedModal").modal('show');
        });

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>
    </div>

image

Call the javascripts,

$('.datepicker').datepicker()

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

show

This event fires immediately when the date picker is displayed.

hide

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

changeDate

This event is fired when the date is changed.

    $('#dp5').datepicker()
    .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
"Microsoft","jamcracker","Telstra"

The converted JSON – properties looks like,

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

The converted JSON – Column array looks like,

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

The converted JSON – Row array looks like,

[
  ["Microsoft","jamcracker","Telstra"]
]

The converted XML – Properties look like,

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

The converted XML – Nodes look like,

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

The converted Html tables look like,

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

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 ($) {
    $.fn.extend({
        //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);
            $(this).html(html);
            $(this).modal('show');
            var context = $(this);
            $('#confirmYesBtn',this).click(function(){
                if(options.callback!=null)
                    options.callback();
                $(context).modal('hide');
            });
        }
    });

})(jQuery);

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 () {
$("#confirmDiv").confirmModal({
heading: 'Confirm to delete',
body: 'Are you sure you want to delete this record?',
callback: function () {
alert('callback test');
}
});
});
</script>
<a href="#" id="openConfirmModal">Open Confirm Modal</a>
<div id="confirmDiv"></div>