Tuesday 24 December 2013

Enabling Automatic Code First Migration

This post is describing how to set automatic Entity Framework Code Fist migration, for the manual migration please see my previous post.

Automatic Code First migration feature is useful during development phase when database has not gone into production environment yet.

If you haven't got an EF migration Configuration.cs file then you can run this command on Package Manager Console:
Enable-Migrations –EnableAutomaticMigrations
This will add a folder called 'Migrations' in the project and a file called Configuration.cs with this setting in the constructor method:
AutomaticMigrationsEnabled = true;

If you have already got the file, make sure that AutomaticMigrationsEnabled property setting is set to true in the constructor.

Secondly, ensure that MigrateDatabaseToLatestVersion initialisation option is set on the project startup file (for example; inside global.asax)
Database.SetInitializer(new MigrateDatabaseToLatestVersion<DatabaseContext, Configuration>());
DatabaseContext: your database context class name
Configuration: this is the Configuration file discussed earlier. You would need to make the class to be public if you put the initialiser inside other project.

Also if we want the automatic migration to allow data loss (for example; allowing column to be removed) then AutomaticMigrationDataLossAllowed property would need to be set to true.

So the constructor will have these settings:
public Configuration()
{
    AutomaticMigrationsEnabled = true;
    AutomaticMigrationDataLossAllowed = true;
}

Monday 23 December 2013

Code First Migration

Let say we are using Entity Framework Code First for our project and have a class below:
public class Student
{
   public int StudentId { get; set; }
   public string Name { get; set; }
}
When we use the database context for the first time, the database will be created with a table called __MigrationHistory.

The table has one record initially.

To enable the migration feature, type enable-migrations on Package Manager Console. Some messages will be displayed when the command has finished running.
PM> enable-migrations
Checking if the context targets an existing database...
Detected database created with a database initializer. Scaffolded migration '201312050353336_InitialCreate' corresponding to existing database. To use an automatic migration instead, delete the Migrations folder and re-run Enable-Migrations specifying the -EnableAutomaticMigrations parameter.
Code First Migrations enabled for project CodeFirstMigrationTest.
A folder called 'Migrations' with two files are created.

[timestamp]_InitialCreate.cs is created because the database has already exists when the first time we access the database context. If the database was still empty then only Configuration.cs file would be added.

There are two main commands for the migration feature:
- add-migration - add migration codes in the code layer (under 'Migrations' folder)
- update-database - update the database according to the migration codes written in the code layer

Now let's try to change our model to add a new property:
. . .
public DateTime DOB { get; set; }
. . .
Then run add-migration command to add the change:
PM> add-migration addDOB
Scaffolding migration 'addDOB'.
The Designer Code for this migration file includes a snapshot of your current Code First model. This snapshot is used to calculate the changes to your model when you scaffold the next migration. If you make additional changes to your model that you want to include in this migration, then you can re-scaffold it by running 'Add-Migration addDOB' again.
[timestamp]_addDOB.cs file is created.


Now try update-database command to apply the changes to the database:
PM> update-database
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
Applying explicit migrations: [201312081946270_addDOB].
Applying explicit migration: 201312081946270_addDOB.
Running Seed method.

Then check __MigrationHistory table again. As we can see, a new record is created in the table with Id value the same as the name of the newly generated file.


If necessary, we could customise the codes in the file generated by the add-migration command.

update-database command also has a few parameters that could be useful. We will see briefly TargetMigration, SourceMigration and Script parameters.

To upgrade/downgrade the database to a specific state, use -TargetMigration parameter. For example:
Update-Database –TargetMigration: addDOB
To roll back to empty database, use $InitialDatabase:
Update-Database –TargetMigration: $InitialDatabase

To get the changes in script only without applying those to database, use -Script parameter:
Update-Database -Script -SourceMigration: [initialState] -TargetMigration: [targetState]
If -SourceMigration is not specified then it will use the current database state. If -TargetMigration is not specified then the latest state will be assumed. For example, the command below will generate all migration scripts from empty database up to the addDOB migration state.
Update-Database -Script -SourceMigration: $InitialDatabase -TargetMigration: addDOB

Starting from EF6, we could use the generated scripts to update from any previous state to the one specified as the target. The scripts have logic to check the states based on entries in __MigrationsHistory table.


Reference:
http://msdn.microsoft.com/en-us/data/jj591621.aspx

Friday 22 November 2013

Using Text Description in Enumeration Type

If we would like to have text description for an enum, we could use Description attribute like below:
public enum MyEnum
{
 [Description("Value One")]
 One,

 [Description("Second Value")]
 Two
};

Then to get the description text we could use something like the codes below. Usually we would put this in a helper class.
public static string GetEnumDescription(Enum value)
{
 FieldInfo fi = value.GetType().GetField(value.ToString());

 DescriptionAttribute[] attributes =
  (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);

 if (attributes != null && attributes.Length > 0)
  return attributes[0].Description;
 else
  return value.ToString();
}

Finally the usage:
Helper.GetEnumDescription(MyEnum.Two);


Reference:
http://blog.spontaneouspublicity.com/associating-strings-with-enums-in-c

Friday 15 November 2013

Using Editor Template for Rendering DropDownList

Below is an example of how to have a dropdownlist when editing a model that has an integer type property used for foreign key property. I.e.; I have a model that has this property:
int ItemId { get; set; }
Then I want every time an instance of this model type is being edited, the field is shown as a dropdownlist. To do this, inside 'EditorTemplates' folder under the global 'Views\Shared' or a view's specific folder, I create a partial view named 'Item.cshtml' like below:
@Html.DropDownListFor(model => ViewData.TemplateInfo.FormattedModelValue, ((IEnumerable<Model.Item>)ViewBag.Items).Select(option => new SelectListItem {
                Text = option.Type.Name, 
                Value = option.ItemId.ToString(),
                Selected = (Model != null) && (option.ItemId == (int)ViewData.TemplateInfo.FormattedModelValue)
            }), "Please select")
Note that, I use ViewData.TemplateInfo.FormattedModelValue to get the value. I could also write like this by declaring the model to use:
@model int

@Html.DropDownListFor(model => model, ((IEnumerable<Model.Item>)ViewBag.Items).Select(option => new SelectListItem {
                Text = option.Type.Name, 
                Value = option.ItemId.ToString(),
                Selected = option.ItemId == Model
            }), "Please select")
Then to render the custom template on my edit view page, I do:
@Html.EditorFor(model => model.ItemId, "Item")

For more details about Editor Template or Display Template, you could see my previous post.

Friday 25 October 2013

Inline SelectList for MVC DropDownList

Below are examples of how to write predefined SelectList items of a DropDownList inline in ASP.NET MVC view.
@Html.DropDownListFor(model => model.IsExist,
         new SelectList(new List<Tuple<bool, string>>
         {
           new Tuple<bool, string>(false, "No"),                    
           new Tuple<bool, string>(true, "Yes"),                    
         }, "Item1", "Item2"))
@Html.DropDownListFor(model => model.IsExist,
         new SelectList(new []
         {
           new {ID=false, Name="No"},
           new {ID=true, Name="Yes"},
         }, "ID", "Name"))

Friday 18 October 2013

Arranging Extension Methods

I like to arrange my extension methods in categories based on the functionalities and also to design them to be easily tested (mocked) as described on this post.

That way the methods are grouped nicely and also displayed neatly when showed by intellisense. Below is an example of how I do that:
public interface ICategoryOne
{
 string MethodOne();
 int MethodTwo();
 int MethodThree(string value);
}

internal class RealCategoryOne : ICategoryOne
{
 private StringBuilder sb;

 public RealCategoryOne(StringBuilder sb)
 {
  this.sb = sb;
 }

 public string MethodOne()
 {
  return "method one";
 }

 public int MethodTwo()
 {
  return sb.GetHashCode();
 }

 public int MethodThree(string value)
 {
  return value.Count();
 }
}

public static class MyExtensionMethods
{
 public static Func<StringBuilder, ICategoryOne> CategoryOneFactory = sb => new RealCategoryOne(sb);

 public static ICategoryOne CategoryOne(this StringBuilder sb)
 {
  return CategoryOneFactory(sb);
 }
}  

With intellisense, the methods will be shown like:



Then to test these extension methods with Moq:
Mock<ICategoryOne> categoryOne = new Mock<ICategoryOne>();
categoryOne.Setup(c => c.MethodOne()).Returns("Moq method 1");
categoryOne.Setup(c => c.MethodTwo()).Returns(-555);
categoryOne.Setup(c => c.MethodThree(It.IsAny<string>())).Returns(-999);

StringBuilder sb = new StringBuilder();

MyExtensionMethods.CategoryOneFactory = prm => categoryOne.Object;

var test = sb.CategoryOne().MethodOne();
Assert.AreEqual(test, "Moq method 1");

Alternatively we can create a fake/dummy class for testing:
public class FakeCategoryOne : ICategoryOne
{
 private StringBuilder sb;

 public FakeCategoryOne(StringBuilder sb)
 {
  this.sb = sb;
 }

 public string MethodOne()
 {
  throw new NotImplementedException();
 }

 public int MethodTwo()
 {
  throw new NotImplementedException();
 }

 public int MethodThree(string value)
 {
  throw new NotImplementedException();
 }
}
Then we change the factory above as:
MyExtensionMethods.CategoryOneFactory = prm => new FakeCategoryOne(prm);


Reference:
http://blogs.clariusconsulting.net/kzu/how-to-mock-extension-methods/

Friday 27 September 2013

Data Annotations Attributes for Formatting Purpose

There are many attributes that we can use from System.ComponentModel.DataAnnotations. A few of them have just been added in the latest framework. Some of those are useful for validation and others for formatting purpose. On this post, I'd like to particularly focus on the attributes that can be used for formatting/displaying data.

However, first I will list down the ones that are useful for validation:
- Compare
- CustomValidation (this is different from creating custom validation class that derives from ValidationAttribute class)
- EmailAddress
- FileExtensions
- MaxLength
- MinLength
- Phone
- Range
- RegularExpression
- Required
- StringLength
- Url

Then the ones that are useful for formatting are below:
- Display
Specify the property name to be displayed. Also can be used to set the display order of the property. The default value is 10,000.
e.g.;
[Display(Name=”First Name”, Order=11000)]

- ScaffoldColumn
Hide the property to be displayed by EditorForModel and DisplayForModel.
e.g.;
[ScaffoldColumn(false)]

- DisplayFormat
Display the property in specific format in EditorFor or DisplayFor helper. Some options are:
ConvertEmptyStringToNull, NullDisplayText, DataFormatString, ApplyFormatInEditMode and HtmlEncode.
e.g.;
[DisplayFormat(ConvertEmptyStringToNull = true, NullDisplayText = "[Null]")]
ConvertEmptyStringToNull will automatically convert passed empty string into null when binding model.
NullDisplayText is used to specify text to be displayed if the property value is null. By default an empty string will be displayed.
[DisplayFormat(ApplyFormatInEditMode=true, DataFormatString=”{0:c}”)]
ApplyFormatInEditMode by default is false because most of the time the input passed from edit form would not be able to be parsed.

- ReadOnly
Tell model binder to not set the property with a new value. EditorForModel will still enable the input to be edited however the model binder will ignore the value passed.

- DataType
Set the property to be displayed in a more specific data type. Some of the data types are; MultilineText, Password and Url. The complete list of data types and their description can be found here.
e.g.;
[DataType(DataType.Password)]

- UIHint
Used to specify custom template name to be used by EditorFor or DisplayFor helper when rendering the property. This attribute is useful when we want to use a custom template for displaying a property. The template is put under DisplayTemplates or EditorTemplates folder under Shared or a specific controller folder.

For example; if we create a new template for displaying hyperlink in a file called Hyperlink.cshtml:
<a href="@Model" target="_blank">@Model</a>
Then we can add this attribute on property that we want to be rendered using the new template. If we have put the template under Shared folder then this can be applied to any property in the project.
[UIHint("Hyperlink")]

- HiddenInput
Set the property to be rendered as an html hidden element.

Friday 13 September 2013

Not Supported Database Function in IQueryable Query

One of the simplest ways that we could try to fix errors related to non-translatable function from EF query to its similar database function is to take that function out of the query and put in separate line(s). It might help in some cases.

For example; if we have this error "LINQ to Entities does not recognize the method 'Int64 ToInt64(System.String)' method, and this method cannot be translated into a store expression." because of the code below:
query = query.Where(x => x.StudentId.Value == Convert.ToInt64(number));
then we can try to do as below:
long value = Convert.ToInt64(number);
query = query.Where(x => x.StudentId.Value == value);

Friday 16 August 2013

Using Display Templates or Editor Templates

DisplayTemplates or EditorTemplates is used for providing custom template for a model property whether it is of a single object type or a collection of an object type. DisplayTemplates or EditorTemplates can be used to automatically render an object type in all views in the application or in all views of a particular controller. It can also only be called when needed.

To use that, first create the template (view) for the object type with this name 'object_type.cshtml' under DisplayTemplates or EditorTemplates folder under Views\Shared or a particular controller's views folder (e.g.; Views\Home). By default the framework will search under a controller views folder first then the Shared folder. If we put the template under Shared folder then it will apply to all views. Whenever a particular object type is rendered using EditorFor or DisplayFor, the framework will use the template.

For example, below is a template for a class object type called ItemViewModel:
@model ItemViewModel

@Html.DisplayNameFor(model => model.ItemId)
@Html.DisplayFor(model => model.ItemId)

@Html.DisplayNameFor(model => model.ItemName)
@Html.DisplayFor(model => model.ItemName)

Then render the property with EditorFor or DisplayFor helper method on a view.
EditorFor(model => model.Items)

That's all that we need to do. If the property is a collection of an object type then the template will be rendered multiple times for each item.

If we want the new template to be used only when we call it, then we could name the template using other name other than the object type (e.g.; MyCustomTemplate.cshtml). Then to use it we can specify the template name as the second argument on EditorFor or DisplayFor method
EditorFor(model => model.Items, "MyCustomTemplate")
or by using UIHint attribute on the object property
[UIHint("MyCustomTemplate")]
public IList<ItemViewModel> Items { get; set; }

Friday 9 August 2013

Passing Dynamic Collection Member Manually through Html.BeginForm Method

Let's say we have a model with a collection type member that is populated dynamically on client side and we want to pass them automatically to controller by using Html.BeginForm(). We can manually add html input elements with some conventions to allow the collection to be passed.
The input element must have:
- id attribute like 'CollectionName_IndexNumber__PropertyName'
- and name attribute like 'CollectionName[IndexNumber].PropertyName'

For example, if we have:
public class InvoiceDto
{
 public int InvoiceId { get; set; }
 public string Name { get; set; }    
 public string Description { get; set; }

 public IList<ItemSellingDto> Items { get; set; }
}

public class ItemSellingDto
{
 public int ItemSellingId { get; set; }
 public int ItemId { get; set; }
 public Int16 Quantity { get; set; }     
 public decimal Price { get; set; }
 public int InvoiceId { get; set; }
}
and we would like to add each collection member (ItemSellingDto) to an html table element inside Html.BeginForm() dinamically using JavaScript (see my previous post to see the example layout), then the script would look like something like:
function addRow(response) {
 var tableRows = $('#tblItemSellings tr');
 var tr;
 tr = $('<tr/>');
 tr.append("<td>" + response.ItemName + "</td>");
 tr.append("<td>" + response.Quantity + "</td>");
 tr.append("<td>" + response.Price + "</td>");

    // the first row is for table headers
 tr.append("<td><input type='hidden' id='Items_" + (tableRows.length - 1) + "__ItemId' name='Items[" + (tableRows.length - 1) + "].ItemId' value='" + response.ItemId + "'/></td>");
 tr.append("<td><input type='hidden' id='Items_" + (tableRows.length - 1) + "__Quantity' name='Items[" + (tableRows.length - 1) + "].Quantity' value='" + response.Quantity + "'/></td>");
 tr.append("<td><input type='hidden' id='Items_" + (tableRows.length - 1) + "__Price' name='Items[" + (tableRows.length - 1) + "].Price' value='" + response.Price + "'/></td>");

 $('#tblItemSellings').append(tr);
}

Friday 19 July 2013

Using Partial View and AJAX for Validation - with jQuery Ajax

In the previous post I wrote about using partial view for validation with Ajax.BeginForm. If we want to do the form submission manually with jQuery Ajax method we could do that as well. We only need to do minor changes on the partial view and add the jQuery script. Below is the updated partial view:
@model DTO.ItemSellingDto

<div id="result">
@using (Html.BeginForm("CreateEditPartial", "ItemSellings", FormMethod.Post, new {id="ItemSellingForm"})) {
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>ItemSelling</legend>
        <span style="color: red">@ViewBag.ErrorMessage</span>
        
        <div class="editor-label">
            @Html.LabelFor(model => model.Quantity)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Quantity)
            @Html.ValidationMessageFor(model => model.Quantity)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Price)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Price)
            @Html.ValidationMessageFor(model => model.Price)
        </div>

        . . .

        <div>
            <input id="btnCreateItemSelling" type="submit" value="Create" />
        </div>
    </fieldset>
}
</div>

<script type="text/javascript">
    $(function () {
        $('#ItemSellingForm').submit(function () {   // the form id is specified in Html.BeginForm method parameter
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (result) {
                    if (typeof result == 'object') {
                        $('#result').html('');  // this is to clear the update pane
                        addRow(result);
                    } else {
                        $('#result').html(result);  // display partial view again if input is not valid
                    }
                }
            });
            return false;  // don't forget this, otherwise the page will redirect
        });
    });
</script>
The other codes are still the same as shown here.

Tuesday 16 July 2013

Using Partial View and AJAX for Validation - with Ajax.BeginForm

I would like to create a page that shows an update pane when a button is clicked. The pane should use Ajax so it will be displayed without page refresh. Below are how the screens will look like:



I also want some validation on the input fields on the update pane. However I prefer to have server validation so that all business rules can be put in one place. When the fields are submitted through Ajax, if there's a validation error the message should be shown. However if successful, the new record should be added to a listing table. All of this is done through Ajax so there will be no page refresh.


To be able to do this, first we need to create a Partial View that contains the input fields:
@model DTO.ItemSellingDto

<div id="result">
@using (Ajax.BeginForm(new AjaxOptions(){UpdateTargetId="result", HttpMethod="Post", 
    Url=Url.Action("CreateEditPartial","ItemSellings"), OnSuccess="addRow"})) {
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>ItemSelling</legend>
        <span style="color: red">@ViewBag.ErrorMessage</span>
        
        <div class="editor-label">
            @Html.LabelFor(model => model.Quantity)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Quantity)
            @Html.ValidationMessageFor(model => model.Quantity)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Price)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Price)
            @Html.ValidationMessageFor(model => model.Price)
        </div>

        . . .

        <div>
            <input id="btnCreateItemSelling" type="submit" value="Create" />
        </div>
    </fieldset>
}
</div>
Note that in this case I use Ajax.BeginForm to help with the form submission. We could have used jQuery method $.ajax as well (I will write about this on the next post). Some of the AjaxOptions properties that I have used are:
- UpdateTargetId: this is the target element that will be updated after submission to the server side
- HttpMethod: POST or GET
- Url: this should point to the controller action to process the form
- OnSuccess: we can specify a javascript function to call after the form is successfully submitted.
There are some other options such as LoadingElementId, OnBegin, OnComplete and OnFailure. Please see this page for more details.
We also need a submit type element for the form. Also note that on the first line, we could use a model as well like a normal view.

To show this partial view when the button on the main view is clicked, add a placeholder somewhere on the main page and call the jQuery load function when the button is clicked.
// in this case the button id is 'btnAddItemSelling' 
// and I use a div with id 'itemSellings' for the placeholder
$("#btnAddItemSelling").click(function () {
 $("#itemSellings").load("@Url.Action("CreateEditPartial","ItemSellings")");
});
The url passed in the function parameter is the url used by GET controller action for displaying the partial view that we will create next.

Then we create the controller actions. We have two controller actions, one for displaying the partial view (GET) and the other for receiving the form data after submitted (POST). Note that the actions return partial view type when displaying and when the validation is failed. Also on line 9, we could pass a model as a parameter to the method from the Ajax form.
public ActionResult CreateEditPartial()
{
 // prepare and populate required data for the input fields
 // . . .

 return PartialView("CreateOrEdit");
}

[HttpPost]
public ActionResult CreateEditPartial(ItemSellingDto itemSellingDto)
{
 if (!ModelState.IsValid)
 {
  // prepare and populate required data for the input fields
  // . . .

  return PartialView("CreateOrEdit");
 }
 else
 {
  return Json(itemSellingDto);
 }
}
For the validation, in this case I just simply used Data Annotation but we could use other alternative such as a custom method, etc. I simply used   ModelState.IsValid   to check whether the inputs passed are fine. Then also put   @Html.ValidationMessageFor(...)   for each input field on the view. Note also that I enclosed the Ajax.BeginForm inside a div (please see line 3 and 34 on the partial view file above) and assign the Id to UpdateTargetId (one of the AjaxOptions properties) so that when input is not valid then the partial view content will be automatically put into the target element.

Next, include these two javascript references; jQuery and jQuery Unobtrusive Ajax on the main page. Do NOT put jQuery Unobtrusive Ajax on the partial page as this will cause the page to be submitted multiple times instead of once. Also write the javacript function that will be called when the validation from server side is successful. In this case, the code returns an object if validation is successful then the javascript function checks the data passed, if it is an object then add it to the listing table.



function addRow(response) {
 if(typeof response =='object')
 {
  // append object to table
  . . .
 }
}

Friday 21 June 2013

Adding Codes to an Existing JavaScript Function

Below is a script to add codes (prepend or append) to an existing JavaScript function:
myFunction = (function () {
 // check whether myFunction already exists
 if (typeof myFunction == 'function') {
  var existingFunction = myFunction;
 }
 return function () {
  // some codes before existing function
  // . . .
 
  if (typeof existingFunction != 'undefined') {
   existingFunction.apply(this, arguments); 
   // by using 'apply' we can pass one or more arguments that is initially passed to the original function
  }
  
  // some codes after existing function
  // . . .
 };
} ());  

Friday 7 June 2013

Some WatiN Examples

Below are some examples of WatiN codes for testing:
// find div by id
var div = browser.Div("divId");

// find div by class
var div = browser.Div(Find.ByClass("divClass"));

// click a div
browser.Div("divId").Click();

// click a button
browser.Button("buttonId").Click();

// get <li></li> elements inside a div
var lisCollection= browser.Div("divId").ElementsWithTag("li");
// click the first <li></li>
lisCollection.FirstOrDefault().Click();
// click the one contains a particular inner text
lisCollection.Where(li => li.Text.Contains("some text")).FirstOrDefault().Click();

// get <a></a> elements inside a div
var links = browser.Links.Filter(a => a.Parent.Parent.Parent.ClassName == "divClass");
var links = browser.Links.Filter(a => a.Parent.Parent.Parent.Parent.Id == "divId");

// select from a select dropdown
browser.SelectList("selectId").Option("option text").Select();

// assert a div exists
Assert.IsTrue(browser.Div("divId").Exists);

// assert header(s) with a particular text exists
Assert.IsTrue(browser.ElementsWithTag("h1").Any(x => x.Text == "heading text"));

// assert only one header with a particular text exists
Assert.IsTrue(browser.ElementsWithTag("h3").Where(x => x.Text == "heading text").Count() == 1);

// assert a particular text exists inside a table td 
Assert.IsTrue(browser.Table("tableId").TableCells.Any(x => x.Text == "text inside td"));

Monday 27 May 2013

First Time NSpec with Visual Studio 2012

There are many different tools to do Behaviour Driven Development (BDD) practice. One of them is NSpec. In this post, I described the first step of how to use it with Visual Studio 2012.

Firstly we need to install NSpec and NSpec adapter for xUnit on our test project, we can use Package Manager to install those easily.

Then add a class in the project and put the code below:
using NSpec;
 
class my_first_spec : nspec
{
    void given_the_world_has_not_come_to_an_end()
    {
        it["Hello World should be Hello World"] = () => "Hello World".should_be("Hello World");
    }
}

Build the project then run this command on Package Manager Console:
nspecrunner [your_test_project]\bin\debug\[your_test_project].dll
You should get this result:
my first spec
  given the world has not come to an end
    Hello World should be Hello World

1 Examples, 0 Failed, 0 Pending

If you had this error "The term 'nspecrunner' is not recognized as the name of a cmdlet, function, script file, or operable program" then it seems that the files are not copied properly by PM. You could resolve this issue by manually copying the missing files.
Go to '[your_solution_folder]\packages\nspec.0.9.66\tools' folder then copy these two files; NSpecRunner and NSpecRunner.exe, to '[your_project_folder]\bin\debug' folder.
Restart Visual Studio then run the command again.

Friday 17 May 2013

Modifying Passed Object to a Mocked Interface's Method

For instance we have a mockable interface with a method accepting an object that modifies its property inside without returning back the new property value. The new value however is required by subsequence codes. For example:
public void InsertOrUpdate(Invoice invoice)
{
   . . .
   context.Add<Invoice>(invoice); // this method will save to database and generate an Id
   
   int generatedId = invoice.InvoiceId; // the Id is required for subsequence codes
   . . .
}
Now how do we do this in our unit test with Moq? We can use Callback feature to modify the object passed then go on with our testing:
// Arrange
Mock<IDomainContext> context = new Mock<IDomainContext>();
InvoiceDS invoiceDS = new InvoiceDS(context.Object);
  //set up so that after context.Add<Invoice>(invoice) is called, InvoiceId is set to 5
context.Setup(c => c.Add<Invoice>(It.IsAny<Invoice>())).Callback<Invoice>(i => i.InvoiceId = 5);
Invoice invoice = new Invoice();

// Act
invoiceDS.InsertOrUpdate(invoice);

// Assert
. . .

Friday 19 April 2013

An Example of Object Oriented in JavaScript

Below is an example of implementing object oriented in JavaScript:
var AutoRefresh = {
  counter : 0,
  timesDuration : 5,
  timerId : null,
  autoRefreshIsRunning : false,
  runProcess : function() {
        AutoRefresh.counter++;
        AutoRefresh.autoRefreshIsRunning = true;
        . . .
  },
  stopProcess : function() {      
        AutoRefresh.counter = 0;
        AutoRefresh.autoRefreshIsRunning = false;
        . . .
  }
};

Friday 5 April 2013

Moq - Checking the Order of Methods Called

Say we have codes like below that call two methods:
public void InsertOrUpdate(ItemDto itemDto)
{
    . . .
 context.Add<Item>(item);
 context.SaveChanges();
    . . .
}

We would like to ensure that a method is called after the other. We can use the Callback feature in Moq and a collection type to store predefined values for each method. Then we can check the values stored in the collection and their orders to determine that the methods were called in sequence.
[Fact]
public void SaveChanges_method_is_called_after_Add_method()
{
    // Arrange
    List<string> invokes = new List<string>();
    string addMethod = "Add";
    string saveChangesMethod = "SaveChanges";
    context.Setup(c => c.Add<Item>(It.IsAny<Item>()))
           .Callback(() => invokes.Add(addMethod));
    context.Setup(c => c.SaveChanges())
           .Callback(() => invokes.Add(saveChangesMethod));
            
    // Act
    itemDS.InsertOrUpdate(itemDto);
               
    // Assert
    Assert.Equal(invokes[0], addMethod);
    Assert.Equal(invokes[1], saveChangesMethod);
}

Monday 11 March 2013

Capturing Deadlock Info in SQL Server with System Health and Event Notification

System Health
SQL Server 2008 introduced a new way to capture deadlock information, which is by using system_health event session in Extended Events. This is run by default in the server. To see recent deadlocks that have occurred, run this query:
WITH SystemHealth
 AS (
 SELECT CAST(target_data as xml) AS TargetData
 FROM sys.dm_xe_session_targets st
 JOIN sys.dm_xe_sessions s
 ON s.address = st.event_session_address
 WHERE name = 'system_health'
 AND st.target_name = 'ring_buffer')
 
 SELECT XEventData.XEvent.value('(data/value)[1]','VARCHAR(MAX)') AS DeadLockGraph
 FROM SystemHealth
 CROSS APPLY TargetData.nodes('//RingBufferTarget/event') AS XEventData (XEvent)
 WHERE XEventData.XEvent.value('@name','varchar(4000)') = 'xml_deadlock_report'
Copy the content of each row and save into an .XDL file then open the file on SQL Management Studio. It happened to me that I received this message "The 'victim-list' start tag on line 1 does not match the end tag of 'deadlock' ..." when SSMS is trying to open the file. When I checked the file, there are two nodes immediately after the <deadlock-list> node that do not match. Not sure why they are generated incorrectly. Then I changed those nodes:
<victim-list>
  <victimProcess id="processNumber"/>
to
<deadlock victim="processNumber"/>
Basically we want the file content to have this structure:
<deadlock-list>
  <deadlock victim="...">
    <process-list>
  . . .
 </process-list>
    <resource-list>
  . . .
 </resource-list>
  </deadlock>
</deadlock-list>
Now I could see a deadlock graph is displayed graphically.



Service Broker Event Notification
In SQL Server 2005 or above, we can also use Event Notification to capture deadlock information. We can send the event to a service and then to a queue. Below are the scripts to setup the event notification, service and queue:
-- Need to use a broker enabled database
USE msdb;

--  Create a service broker queue to hold the events
CREATE QUEUE DeadlockQueue
GO

--  Create a service broker service to receive the events and route to the queue
CREATE SERVICE DeadlockService
ON QUEUE DeadlockQueue ([http://schemas.microsoft.com/SQL/Notifications/PostEventNotification])
GO

-- Create the event notification for capturing deadlock graphs and send to the service
CREATE EVENT NOTIFICATION CaptureDeadlocks
ON SERVER
WITH FAN_IN
FOR DEADLOCK_GRAPH
TO SERVICE 'DeadlockService', 'current database' ;
GO 

Each time a deadlock happen, the DeadlockQueue will be added.
USE msdb ;

-- try to see DeadlockQueue data
select * from DeadlockQueue

Then to see the contending queries of the first deadlock before one of them is chosen as a deadlock victim:
USE msdb;
-- Cast message_body to XML and query deadlock graph from TextData
SELECT  message_body.value('(/EVENT_INSTANCE/TextData/
                                  deadlock-list)[1]', 'varchar(max)')
                                  AS DeadlockGraph
FROM    ( SELECT    CAST(message_body AS XML) AS message_body
          FROM      DeadlockQueue
        ) AS sub ;
GO

To get the xml data of the deadlocks one by one:
DECLARE @message_body XML ;

RECEIVE TOP(1) -- just handle one message at a time
@message_body=message_body
FROM DeadlockQueue ;

SELECT  @message_body.query('(/EVENT_INSTANCE/TextData/deadlock-list)[1]') AS XML
GO
Then we can save it as an .XDL file and open in SSMS.

After we have done, drop the instances
drop event notification CaptureDeadlocks on server

drop service DeadlockService

drop queue DeadlockQueue

Example scripts to create a deadlock
Below is an example of how to create a deadlock. We just need to pick two tables and open two SSMS query windows to try these.
-- open window 1 and run this
begin tran
select top(1) Name, 'first window' from TableOne with (xlock);
-- then wait for a while

-- open window 2 and run this
begin tran
SELECT top(1) Name, 'second window' from TableTwo with (xlock);
SELECT top(1) Name, 'second window' from TableOne with (xlock);
-- then wait for a while

-- back to window 1 and run this
select top(1) Name, 'first window' from TableTwo with (xlock);
-- wait for a while, a deadlock should happen

References:
https://www.simple-talk.com/sql/database-administration/handling-deadlocks-in-sql-server/
http://blogs.technet.com/b/mspfe/archive/2012/06/28/how_2d00_to_2d00_monitor_2d00_deadlocks_2d00_in_2d00_sql_2d00_server.aspx

Friday 1 March 2013

Debugging LINQ Query in Visual Studio 2010 with LINQPad

I found out that we can use LINQPad (LINQPad Visualizer) to debug LINQ queries in Visual Studio 2010. To be able to do this we need to:
- install LINQPad

- download LINQPad Visualizer

- copy these files from LINQPad folder (eg. Program Files (x86)\LINQPad4): LINQPad.exe and LINQPad.exe.config
and from the downloaded LINQPad Visualizer folder: linqpadvisualizer.dll, Newtonsoft.Json.dll and Newtonsoft.Json.xml
to Documents\Visual Studio 2010\Visualizers (create the folder if not exists)

- copy LINQPad.exe and LINQPad.exe.config to the same folder as devenv.exe (eg. C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE)

- restart Visual Studio

Then we can put a breakpoint on a LINQ query and start debugging. When we want to inspect a variable, put this on the Name column on Watch window
new System.WeakReference([variable_to_inspect])
then click the magnifier glass icon on the Value column, the visualizer should appear.


Further reading:
https://www.simple-talk.com/dotnet/.net-framework/linq-secrets-revealed-chaining-and-debugging/

Thursday 28 February 2013

Checking Parameter Passed to a Method with Moq

Say we are using TDD and would like to add more business logic to the method below. We would like to make sure that the object's created and updated time should be set with current time.
public void Add(Item item)
{        
    // set item created time

    // set item updated time 

    repository.Add(item);
}

Moq provides some argument checking methods that we can use; there are:
- It.Is<Type>(...) ,
- It.IsInRange<Type>(...) and
- It.IsRegex(...)

Below is a unit test using one of the methods; It.Is<Type>(o => checking_condition)
[Fact]
public void Created_time_should_be_set_as_current_time()
{
    // Arrange
    var item = new Item(); 
    var timeToCompare = DateTime.Now.AddHours(-1);

    // Act
    itemDS.Add(item);

    // Assert
    repository.Verify(c => c.Add(It.Is<Item>(i => i.CreatedAt.CompareTo(timeToCompare) > 0)));
}
or we can write like this:
[Fact]
public void Created_time_should_be_set_as_current_time()
{
    // Arrange
    var item = new Item(); 
    var timeToCompare = DateTime.Now.AddHours(-1);
    repository.Setup(c => c.Add(It.Is<Item>(i => i.CreatedAt.CompareTo(timeToCompare) > 0)));

    // Act
    itemDS.Add(item);

    // Assert
    repository.VerifyAll();
}
Run the test. It will fail. Then we can put the code item.CreatedAt = DateTime.Now; on the method. Run the test again. It should pass now.

Now we want to create a test to make sure updated time is set. We will use another way to check the parameter passed to a method. We will use Callback feature to retrieve the parameter. We cannot put a checking conditional logic in Callback argument. However we can assign the passed parameter to an existing object or add it to an existing collection then later we can inspect it.

[Fact]
public void Updated_time_should_be_set_as_current_time()
{
    // Arrange
    var item = new Item(); 
    var timeToCompare = DateTime.Now.AddHours(-1);

    // repository.Setup(c => c.Add(It.Is<Item>(i => i.UpdatedAt.CompareTo(timeToCompare) > 0)));
    // alternate way by using Callback
    repository.Setup(c => c.Add(It.IsAny<Item>())).Callback<Item>(i => item = i);

    // Act
    itemDS.Add(item);

    // Assert
    // repository.VerifyAll();
    // now we are using Callback
    Assert.True(item.UpdatedAt.CompareTo(timeToCompare) > 0);
}

Just for a note, if required, Callback can be combined with Returns function as well. For example:
mock.Setup(. . .)
    .Returns(. . .)
    .Callback(. . .)

mock.Setup(. . .)
    .Callback(. . .)
    .Returns(. . .)
    .Callback(. . .)

Run the test. It will fail. Put the code item.UpdatedAt = DateTime.Now; Now the test will pass.

Our updated method now is
public void Add(Item item)
{        
    // set item created time
    item.CreatedAt = DateTime.Now;

    // set item updated time 
    item.UpdatedAt = DateTime.Now;

    repository.Add(item);
}

References:
http://code.google.com/p/moq/wiki/QuickStart
http://stackoverflow.com/questions/3269717/moq-how-to-get-to-a-parameter-passed-to-a-method-of-a-mocked-service

Thursday 21 February 2013

How to Seed/Initialise Some Data in Entity Framework Code First

Entity Framework version 5.0.0 is used when writing this post.

First, we need to create a class derived from one of the built in database initialiser options' classes. They are CreateDatabaseIfNotExists, DropCreateDatabaseIfModelChanges and DropCreateDatabaseAlways. In the example below is DropCreateDatabaseIfModelChanges. I think it is possible to create a custom initialiser if we wish to do so.
public class DBInitialiser : DropCreateDatabaseIfModelChanges<MyContext>
{
    protected override void Seed(MyContext context)
    {
        // populate sizes table
        var sizes = new List<Size> {
            new Size {SizeId = 1, Code="S", Description="Small"},
            new Size {SizeId = 2, Code="M", Description="Medium"},
            new Size {SizeId = 3, Code="L", Description="Large"}
        };
        sizes.ForEach(s => context.Sizes.Add(s));       
    }
}
Notice that on line 1, we also pass the context type. Then we need to override the Seed() method and create some items to populate the database.

Next, we need to call Database.SetInitializer() method with an instance of the new derived class as its parameter when the application starts. In an MVC application, this would be inside Application_Start() in Global.asax.cs file.

If you have used Database.SetInitializer() with one of the built in database initialiser options as its parameter then you need to replace it with the new derived class' instance.
//Database.SetInitializer(new DropCreateDatabaseIfModelChanges<MyContext>());
    // Replaced the parameter with the new derived class' instance
    Database.SetInitializer<MyContext>(new DBInitialiser());

Thursday 31 January 2013

Basic Usage of Unity for Dependency Injection in MVC 4 Project

First, we need to install Unity Application Block library. If you use NuGet:
PM> install-package Unity.Mvc3
Yes, that is the correct version even for MVC 4 (at least at the time of writing).

Bootstrapper.cs file will be created in the project.

Next, inside Applicaton_Start() in Global.asax.cs, put this code:
Bootstrapper.Initialise();

Then register our components inside BuildUnityContainer() method in Bootstrapper.cs. For example:
        . . .
        container.RegisterType<IColourRepository, ColourRepository>();
        container.RegisterType<IInvoiceRepository, InvoiceRepository>();
        . . .

Calling container.RegisterControllers() in order to register controllers is no longer required in recent version.

Friday 18 January 2013

Singleton in .NET 4.0 or Above

Below is an example of a class that is implementing Singleton pattern in .NET 4.0 or above. The framework added a new type called System.Lazy<T> that makes laziness (lazy construction) really simple and also thread-safe as well. Prior to this we had to use static constructor, double-check locking or other tricks to ensure the laziness and thread-safe.
public sealed class Singleton
{
    private static readonly Lazy<Singleton> _instance =
        new Lazy<Singleton>(() => new Singleton());

    public static Singleton Instance { get { return _instance.Value; } }

    private Singleton()
    {
        //Console.Write("... Singleton is created ...");
    }
}

We could also use a generic template like this:
public static class Singleton<T> where T : new()
{
    private static readonly Lazy<T> _instance = new Lazy<T>(() => new T());
        
    public static T Instance { get { return _instance.Value; } }
} 
and the class type to be passed:
public class Car
{
    public Car()
    {
        Console.WriteLine("Car is created");
    }
}

References and further reading:
http://geekswithblogs.net/BlackRabbitCoder/archive/2010/05/19/c-system.lazylttgt-and-the-singleton-design-pattern.aspx
http://csharpindepth.com/articles/general/singleton.aspx