Implementing the right-click context menu in Silverlight 4

  1. Download and install Silverlight 4 Toolkit - April 2010.
  2. In your Silverlight 4 project, add references to:
    • System.Windows.Controls
    • System.Windows.Controls.Input.Toolkit
  3. In your UserControl XAML, add the following to the LayoutRoot grid opening tag: MouseRightButtonDown="LayoutRoot_MouseRightButtonDown" MouseRightButtonUp="LayoutRoot_MouseRightButtonUp"
  4. In the codebehind:
using System.Windows.Controls;

...

private void LayoutRoot_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
    e.Handled = true;
}

private void LayoutRoot_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
{
    var contextMenu = new ContextMenu();

    var menuItem = new MenuItem();
    menuItem.Header = "First menu item";
    menuItem.Click += menuItem_Click;
    contextMenu.Items.Add(menuItem);

    contextMenu.IsOpen = true;
    contextMenu.HorizontalOffset = e.GetPosition(null).X;
    contextMenu.VerticalOffset = e.GetPosition(null).Y;
}

private void menuItem_Click(object sender, System.Windows.RoutedEventArgs e)
{
    System.Windows.MessageBox.Show("First menu item was clicked");
}

Notes

  • If you don’t include a reference to System.Windows.Controls, you won’t be able to compile, with the error “‘System.Windows.Controls.MenuItem’ does not contain a definition for ‘Header’ and no extension method ‘Header’ accepting a first argument of type ‘System.Windows.Controls.MenuItem’ could be found (are you missing a using directive or an assembly reference?)”
  • Ensure that System.Windows.Controls.Toolkit (if present) is version 4.0.5.0. If it’s version 2.0.5.0, you’ll get runtime error “Unknown parser error: Scanner 2148474880. [Line: 818 Position: 596]”

16 November 2010 | Silverlight, .NET | 2 Comments

Mastering Agile Management using Scrum

This week I attended a workshop on Mastering Agile Management using Scrum. The trainer was Jesse Fewell (rhymes with “jewel”) from RippleRock.

First, the verdict. This training course is about concepts; it can easily become academic and lofty-sounding if the trainer simply goes through the slides and recites his lecture notes. The teacher will need to have passion, deep industry experience, an irreverent sense of humour, and showmanship for the participants to really appreciate the subject – fortunately, Jesse has all these in spades. What I liked most was that Jesse was explicit and forthright in distinguishing between essence and decoration. Insisting on doing things The One Correct Way would be completely missing the point. Instead, based on the principles, customize the techniques to fit the project.

Core principles, as I understand them

  1. The customer is not purchasing scope; he is funding a project. Which means, focus on delivering what the customer really wants instead of what he thinks he wants.
  2. Fixed schedule; fixed cost; dynamic scope.
  3. Frequent, time-boxed delivery of complete features which meet the customer’s definition of done.
  4. People perform best when they’re empowered to self-organize and think for themselves.
  5. Not wasting the customer’s money is a moral prerogative. Treating people with respect is a moral prerogative. Letting people utilize their full potential is a moral prerogative.

From my personal notes

  • Agile is simple. Agile is hard.
  • We welcome scope change, but not scope creep. (Assuming fixed price and schedule.)
  • The daily stand-up is a risk management meeting, not a status meeting.
  • The backlog is measured by the burndown.
  • The burndown can tell the truth and force the decision-maker to make the hard decisions
  • An Agile team is one that is predictable.
  • The problem with most project plans is too detailed, too soon.
  • Undercommit and overdeliver for each sprint (especially for the first sprint).
  • Look out for wasteful gold-plating that the product owner might not even appreciate.
  • Agile estimation: separate effort from complexity and uncertainty.
  • There is no such thing as a “technical user story”, e.g., “As an architect, I …” A user story can only be signed off by the product owner. So instead of developing layer by layer (DAL, BLL, UI), deliver small vertical slices. Instead of creating all the DB tables up front, create just the tables for one user story at a time.
  • Three answers for all questions that will occur:
    • “How much ___?” (e.g., how much architecture?) “Just enough.”
    • “When do we do ___?” “Just in time.”
    • “Why do we have to do this?” “Just because.” (This is when meaningless but mandatory things are required to be done by external parties).
  • Earn respect for your boundaries (i.e., to say no to requests that will overload the team) by consistently delivering on commitments for every iteration.
  • Good ScrumMasters can lead two or three teams. Great ScrumMasters lead one team.
  • Agile is about people. It will be messy. It’s a continuous journey, and it’s about “can we do better?”

Highlights from the slides

  • Essence: deliver early and often; inspect and adapt along the way
  • Product Owner:
    • “The Decider”
    • Responsible for “what we are delivering”
    • Defines what work needs to be done
    • Prioritizes which work gets done first
    • Validates whether work meets expectations
  • ScrumMaster:
    • “The Catalyst”
    • Responsible for “Are we getting better?”
    • Servant Leader; teaches and corrects, but does NOT manage
    • ScrumMaster’s checklist:
      • How is my Product Owner doing?
      • How is my Team doing?
      • How are our Engineering Practices?
      • How is the organization doing?
  • Product Backlog
    • Integrated (in a single repository)
    • Prioritized
    • Sufficient
    • High-level
    • Often-changing
  • Without a clear definition of “done”, all estimates fail
  • User story sizing:

    Value Meaning
    0 No effort
    1 No problem. We could do this in a day.
    2  
    3  
    5 Most common size
    8  
    13  
    20  
    40  
    100 Impossibly large
    Need more information

11 November 2010 | Agile, Project management | 2 Comments

LINQ to Entities: Deferred Execution and Lazy Loading

How do deferred execution and lazy loading work in LINQ to Entities (Entity Framework)? Let’s find out!

First, some sample data. We don’t want to make it too simple, so let’s have three entities:

  1. Employee, who belongs to a Department
  2. Department, which is under a Functional Group
  3. Functional Group

The data:

Functional Groups

Id Description
1 Functional Group 01
2 Functional Group 02

Departments

Id Description FunctionalGroupId
1 Department 01 1
2 Department 02 2
3 Department 03 2

Employees

Id First Name Last Name DepartmentId
1 Employee One 1
2 Employee Two 1
3 Employee Three 2
4 Employee Four 2
5 Employee Five 3

Experiment #1: Lazy loading and deferred execution

var context = new SampleModel();

var employees = context.Employees;

foreach (var employee in employees)
{
    Console.WriteLine("{0} {1}",
        employee.FirstName,
        employee.LastName);
}
Console.ReadLine();

Results

Employee One
Employee Two
Employee Three
Employee Four
Employee Five

Generated SQL Statements

I placed a breakpoint right before the foreach loop. Before foreach: nothing. After foreach:

SELECT
[Extent1].[Id] AS [Id],
[Extent1].[FirstName] AS [FirstName],
[Extent1].[LastName] AS [LastName],
[Extent1].[DepartmentId] AS [DepartmentId]
FROM [dbo].[Employees] AS [Extent1]

Which means that execution is deferred until properties are hit (.FirstName and .LastName). Also, the Departments and FunctionalGroups tables aren’t loaded, because of lazy loading.

Experiment #2: Deferred execution

var context = new SampleModel();

var employees = context.Employees;

foreach (var employee in employees)
{
    Console.WriteLine("{0} {1} - {2} - {3}",
        employee.FirstName,
        employee.LastName,
        employee.Department.Description,
        employee.Department.FunctionalGroup.Description);
}
Console.ReadLine();

Results

Employee One - Department 01 - Functional Group 01
Employee Two - Department 01 - Functional Group 01
Employee Three - Department 02 - Functional Group 02
Employee Four - Department 02 - Functional Group 02
Employee Five - Department 03 - Functional Group 02

Generated SQL Statements

Before foreach: nothing. After foreach:

SELECT
[Extent1].[Id] AS [Id],
[Extent1].[FirstName] AS [FirstName],
[Extent1].[LastName] AS [LastName],
[Extent1].[DepartmentId] AS [DepartmentId]
FROM [dbo].[Employees] AS [Extent1]

exec sp_executesql N’SELECT
[Extent1].[Id] AS [Id],
[Extent1].[Description] AS [Description],
[Extent1].[FunctionalGroupId] AS [FunctionalGroupId]
FROM [dbo].[Departments] AS [Extent1]
WHERE [Extent1].[Id] = @EntityKeyValue1′,N’@EntityKeyValue1 int’,@EntityKeyValue1=1

exec sp_executesql N’SELECT
[Extent1].[Id] AS [Id],
[Extent1].[Description] AS [Description]
FROM [dbo].[FunctionalGroups] AS [Extent1]
WHERE [Extent1].[Id] = @EntityKeyValue1′,N’@EntityKeyValue1 int’,@EntityKeyValue1=1

exec sp_executesql N’SELECT
[Extent1].[Id] AS [Id],
[Extent1].[Description] AS [Description],
[Extent1].[FunctionalGroupId] AS [FunctionalGroupId]
FROM [dbo].[Departments] AS [Extent1]
WHERE [Extent1].[Id] = @EntityKeyValue1′,N’@EntityKeyValue1 int’,@EntityKeyValue1=2

exec sp_executesql N’SELECT
[Extent1].[Id] AS [Id],
[Extent1].[Description] AS [Description]
FROM [dbo].[FunctionalGroups] AS [Extent1]
WHERE [Extent1].[Id] = @EntityKeyValue1′,N’@EntityKeyValue1 int’,@EntityKeyValue1=2

exec sp_executesql N’SELECT
[Extent1].[Id] AS [Id],
[Extent1].[Description] AS [Description],
[Extent1].[FunctionalGroupId] AS [FunctionalGroupId]
FROM [dbo].[Departments] AS [Extent1]
WHERE [Extent1].[Id] = @EntityKeyValue1′,N’@EntityKeyValue1 int’,@EntityKeyValue1=3

Again, query execution is deferred. This time, the Departments and FunctionalGroups tables are loaded, because I hit both .Department.Description and .Department.FunctionalGroup.Description.

Notice that lots of small SQL statements are sent to the DB to fetch data one piece at a time.

Experiment #3: Adding a using statement

IEnumerable<Employee> employees = null;

using (var context = new SampleModel())
{
    employees = context.Employees;
}

foreach (var employee in employees)
{
    Console.WriteLine("{0} {1} - {2} - {3}",
        employee.FirstName,
        employee.LastName,
        employee.Department.Description,
        employee.Department.FunctionalGroup.Description);
}

Console.ReadLine();

Results

We get an exception! The ObjectContext instance has been disposed and can no longer be used for operations that require a connection. Execution has been deferred, but at the point where the execution is supposed to happen, there is no longer any data context.

The solution is to use either ToArray() or ToList() to not defer execution.

Experiment #4: Immediate execution using ToArray()

IEnumerable<Employee> employees = null;

using (var context = new SampleModel())
{
    employees = context.Employees.ToArray();
}

foreach (var employee in employees)
{
    Console.WriteLine("{0} {1} - {2} - {3}",
        employee.FirstName,
        employee.LastName,
        employee.Department.Description,
        employee.Department.FunctionalGroup.Description);
}

Console.ReadLine();

Generated SQL Statements

Before the foreach loop:

SELECT
[Extent1].[Id] AS [Id],
[Extent1].[FirstName] AS [FirstName],
[Extent1].[LastName] AS [LastName],
[Extent1].[DepartmentId] AS [DepartmentId]
FROM [dbo].[Employees] AS [Extent1]

After the foreach loop:

An exception, again! The ObjectContext instance has been disposed and can no longer be used for operations that require a connection. Because of lazy loading, the Departments and FunctionalGroups tables weren’t loaded at the outset. So when .Department.Description and .Department.FunctionalGroup.Description were hit, there was a run-time error due to entities not being able to be loaded.

(Note: this implies that ToArray() or ToList(), on their own, will result in immediate execution only for the entity in question. Related entities might be loaded down the line if the relevant properties are hit.)

The solution is to use Include.

Experiment #5: Immediate execution plus eager loading

IEnumerable<Employee> employees = null;

using (var context = new SampleModel())
{
    employees = context.Employees
        .Include("Department.FunctionalGroup")
        .ToArray();
}

foreach (var employee in employees)
{
    Console.WriteLine("{0} {1} - {2} - {3}",
        employee.FirstName,
        employee.LastName,
        employee.Department.Description,
        employee.Department.FunctionalGroup.Description);
}

Console.ReadLine();

Results

Employee One - Department 01 - Functional Group 01
Employee Two - Department 01 - Functional Group 01
Employee Three - Department 02 - Functional Group 02
Employee Four - Department 02 - Functional Group 02
Employee Five - Department 03 - Functional Group 02

Generated SQL Statements

Before the foreach loop:

SELECT
[Extent1].[Id] AS [Id],
[Extent1].[FirstName] AS [FirstName],
[Extent1].[LastName] AS [LastName],
[Extent1].[DepartmentId] AS [DepartmentId],
[Extent2].[Id] AS [Id1],
[Extent2].[Description] AS [Description],
[Extent2].[FunctionalGroupId] AS [FunctionalGroupId],
[Extent3].[Id] AS [Id2],
[Extent3].[Description] AS [Description1]
FROM [dbo].[Employees] AS [Extent1]
LEFT OUTER JOIN [dbo].[Departments] AS [Extent2] ON [Extent1].[DepartmentId] = [Extent2].[Id]
LEFT OUTER JOIN [dbo].[FunctionalGroups] AS [Extent3] ON [Extent2].[FunctionalGroupId] = [Extent3].[Id]

After the foreach loop: nothing.

Hats off to the Entity Framework for being clever enough to use left joins for many-to-one relationships.

Experiment #6: Immediate execution, no lazy loading

Let’s say we don’t want FunctionalGroups to be loaded if the .Department.FunctionalGroup property is hit somewhere down the line. We only want Departments to be loaded.

IEnumerable<Employee> employees = null;

using (var context = new SampleModel())
{
    employees = context.Employees
        .Include("Department")
        .ToArray()
        .Select(x => new Employee
        {
            FirstName = x.FirstName,
            LastName = x.LastName,
            Department = new Department
            {
                Description = x.Department.Description
            }
        });
}

foreach (var employee in employees)
{
    Console.WriteLine("{0} {1} - {2} - {3}",
        employee.FirstName,
        employee.LastName,
        employee.Department != null ? employee.Department.Description : string.Empty,
        employee.Department != null && employee.Department.FunctionalGroup != null ? employee.Department.FunctionalGroup.Description : string.Empty);
}

Console.ReadLine();

Results

Employee One - Department 01 -
Employee Two - Department 01 -
Employee Three - Department 02 -
Employee Four - Department 02 -
Employee Five - Department 03 -

Generated SQL Statements

Before the foreach loop:

SELECT
[Extent1].[Id] AS [Id],
[Extent1].[FirstName] AS [FirstName],
[Extent1].[LastName] AS [LastName],
[Extent1].[DepartmentId] AS [DepartmentId],
[Extent2].[Id] AS [Id1],
[Extent2].[Description] AS [Description],
[Extent2].[FunctionalGroupId] AS [FunctionalGroupId]
FROM [dbo].[Employees] AS [Extent1]
LEFT OUTER JOIN [dbo].[Departments] AS [Extent2] ON [Extent1].[DepartmentId] = [Extent2].[Id]

After the foreach loop: nothing. FunctionalGroups isn’t loaded even when .Department.FunctionalGroup is hit, because we’re returning new instances of the Employee entity, not the ObjectContext-derived instances.

Conclusion

Deferred execution and lazy loading are two related concepts in LINQ to Entities. By default, execution is performed only when properties are hit, so that only the necessary entities are loaded. However, this might be undesirable as multitudes of small queries are generated and sent to the server at run-time. If the entities that need to be loaded are known at compile-time by the programmer, it might be better to not use deferred execution nor lazy loading, and ensure that the optimal SQL query is generated and sent to the server by using the techniques highlighted above.

Note of Thanks

I would like to extend my deepest appreciation to Nick Zhebrun and Yuri Korolev for their AnjLab Sql Express Profiler. Truly useful.

9 November 2010 | LINQ, Entity Framework, .NET, C# | 4 Comments

The first key to programming is to type, not to think

I remember vividly this scene from Finding Forrester, which, in my memory, goes something like this: Jamal is stuck. Forrester grabs the typewriter and proceeds to type furiously. Jamal reads what Forrester has written, amazed. Forrester says, “No thinking – that comes later. You must write your first draft with your heart. You rewrite with your head. The first key to writing is … to write, not to think!”

I have just realized that I tend to be struck by analysis paralysis nowadays. When I first started out, it never happened to me: I simply hooked up UI events to SQL statements, and I was done. Then I read up about design patterns and worked with experienced developers who would separate different concerns into layers. As a result I would think and think before writing a single class declaration – and get absolutely nowhere.

One day I noticed, especially at the architecture and design stage, that I would start a little bit, then I would look something up, and then I would get lost reading for two hours. The truth is that I’ve been so scared of making a mistake that I don’t dare start.

So from now on I resolve to just type. If I’m not clacking away at the keyboard then I’m not programming. This doesn’t negate the Big Design Up Front philosophy; I will try to produce a couple of paragraphs of functional specs as far as I possibly can. But stopping to think too much is definitely not progress.

You might have heard that Fred Brooks once said, when building something, plan to throw the first version away; you will anyway. He has actually retracted that: he says we should plan to continually iterate on it.

And you can’t continually iterate if you’re not typing.

15 September 2010 | Software engineering | 1 Comment

PHP whitespace fail

I had a problem with header('Location: http://example.com') not redirecting as it should. After fiddling a bit, I discovered that it worked before, but not after, this line:

$x = $this->foo($bar);

So what was in function foo()?

private function foo($val)
{
    include_once 'baz.php';
    $baz = new Baz();
    return $baz->get_value($val);
}

I then proceeded to examine every nook and cranny of baz.php to see if there were any instances of echo or print or any other form of output. Nope, Baz was a straightforward class with straightforward methods.

I don’t know where these thoughts come from, but I certainly wish they’d come often: it suddenly occurred to me to check for spaces and new lines after the end processing instruction ?> in baz.php. There were indeed a couple of newlines after ?>, and the removal of said newlines solved the problem.

9 September 2010 | PHP | No Comments