Monday, 3 March 2014

Validation adorners not displaying in WPF

The problem

I was developing a WPF application using the IDataErrorInfo interface to perform validation on view models. When errors were encountered I wanted them to be displayed in the UI using adorners to change border appearances and to show error messages. I also wanted these adorners to show when the form first loaded so the user could see straight away what fields needed to be completed.

The problem was that the adorners only appeared after the user changed the values of the validated controls. When the form first loaded things like required fields were not adorned.


Figure 1 – No adorners showing on required fields etc. when the form first loaded.



Figure 2 – The desired result with adorners displayed correctly.

After spending some time checking the behaviour of the application I could see that IDataErrorInfo members were being called when the form loaded and that INotifyPropertyChanged was correctly implemented and the property changed event was being raised correctly.

The solution

The solution was to wrap the form elements in an AdornerDecorator. So, where I previously had a Grid element containing the rows of input controls and labels I wrapped that grid in an AdornerDecorator.

<StackPanel Orientation="Vertical">
    <AdornerDecorator>
        <Grid>
            <Grid.RowDefinitions>
                <!-- Row definitions omitted -->
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <!-- Column definitions omitted -->
            </Grid.ColumnDefinitions>

            <!-- Input controls and labels omitted -->
            
        </Grid>
    </AdornerDecorator>
    
    <!-- Other layout omitted -->
    
</StackPanel>

Explanation

The controls displaying validation errors in the application were based on styles that used the Validation.ErrorTemplate to provide adorned layout to use in the case of errors. For adorners to be displayed there needs to be an AdornerLayer available in the visual tree.

“An Adorner is a custom FrameworkElement that is bound to a UIElement. Adorners are rendered in an AdornerLayer, which is a rendering surface that is always on top of the adorned element or a collection of adorned elements.” [1]

There will be times when there isn’t an AdornerLayer available so you may have to provide one. The way to do this is to add an AdornerDecorator to your XAML remembering that somewhere there will be a call to the static AdornerLayer.GetAdornerLayer method which walks the visual tree looking for an AdornerLayer.

“This static method traverses up the visual tree starting at the specified Visual and returns the first adorner layer found.” [2]
“The AdornerDecorator specifies the position of the AdornerLayer in the visual tree. It is typically used in a ControlTemplate for a control that might host Adorner objects. For example, the ControlTemplate of a Window contains an AdornerDecorator so that the child elements of the window can be adorned. The GetAdornerLayer method returns null if you pass in an element that does not have an AdornerDecorator as an ancestor in its visual tree.” [3]

Note that - as stated above - the AdornerDecorator is typically used in a ControlTemplate. You might want to explore this avenue further.

References

[1] Adorners Overview
[2] AdornerLayer.GetAdornerLayer Method
[3] AdornerDecorator Class

Saturday, 1 March 2014

Create a self-signed certificate for development in IIS 7

This post is a quick follow up to an earlier one, Generating temp SSL certificates for development, which showed a manual method for creating self-signed certificates. If you’ve got IIS 7 then the following method is much quicker and easier.

The method

Open the Internet Information Services (IIS) Manager.

Select the server node in the connections pane.

server-cert-001

Find the Sever Certificates item and double-click on it.

Right-click in the Server Certificates pane and choose Create Self-Signed Certificate… from the pop-up menu.

server-cert-002

In the dialog box provide a friendly name for the certificate and click OK.

 server-cert-003

That’s all there is to creating a self-signed certificate in IIS 7!

To use the certificate on a web site hosted in IIS you need to open the Sites node in the Connected Sites pane and select the web site that needs the SSL certificate.

In the Actions pane on the right click Bindings…

server-cert-004

If there isn’t an HTTPS binding you’ll have to add one in the Site Bindings dialog. You could edit an existing HTTPS binding if you need to.

server-cert-005

You’ll be prompted to select an SSL certificate for the binding. Just select the self-signed certificate you’ve created. Click OK and you’re done.

server-cert-006

You are now ready to use SSL on your website.

References

Sunday, 16 February 2014

Twitter Bootstrap responsive layout not working in Safari

The problem

When creating a responsive website using Twitter Bootstrap the layout does not act responsively on Safari running on the iPad or iPhone.
 

The solution

You need to add a meta tag to the head of your HTML:

<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

So, what is going on here? Firstly the viewport meta tag was introduced to allow developers to control the “virtual viewport”.

“Mobile browsers like Fennec render pages in a virtual "window" (the viewport), usually wider than the screen, so they don't need to squeeze every page layout into a tiny window (which would break many non-mobile-optimized sites). Users can pan and zoom to see different areas of the page.

Mobile Safari introduced the "viewport meta tag" to let web developers control the viewport's size and scale. Many other mobile browsers now support this tag, although it is not part of any web standard.” [1]

The viewport meta tag above is using several properties. Firstly, there’s the width property:

“The width property controls the size of the viewport. It can be set to a specific number of pixels like width=600 or to the special value device-width value which is the width of the screen in CSS pixels at a scale of 100%. (There are corresponding height and device-height values, which may be useful for pages with elements that change size or position based on the viewport height.)” [1]

So, to set the viewport width to the width of the device you would add the following [2]:

<meta name="viewport" content="width=device-width">

Next there’s the initial-scale property:

“The initial-scale property controls the zoom level when the page is first loaded.” [1]

So, to set the ‘zoom level’ to 1.0 you’d add the following [2]:

<meta name="viewport" content="initial-scale=1.0">

And finally, the maximum-scale property:

“The maximum-scale, minimum-scale, and user-scalable properties control how users are allowed to zoom the page in or out.” [1]

“The minimum-scale and maximum-scale properties also affect the behavior when changing orientations. The range of these property values is from >0 to 10.0. The default value for minimum-scale is 0.25 and maximum-scale is 5.0.” [2]

References

[1] Using the viewport meta tag to control layout on mobile browsers

[2] Configuring the Viewport

Sunday, 16 February 2014

Saturday, 11 January 2014

How to access parameters passed in to a mocked method using Moq

The problem

I was writing unit tests for a WPF application using the MVVM pattern supported by Caliburn.Micro. I had methods on the view-model that were automatically bound to buttons in the user interface using Caliburn.Micro’s convention-based bindings. Some of these methods required that a pop-up dialog box be displayed to the end user to confirm an action. The dialog could be submitted or cancelled.
For example, when the user clicked a ‘back’ button to navigate back to a previous screen I needed to check if any data had changed on the current screen. If it had, I needed to present the user with a dialog asking if they really wanted to go back when there was unsaved data. If the user submitted the dialog by clicking OK the application would go to the previous screen.
The code looked something like this:
public void Back()
{
    if (!IsChanged)
    {
        EventAggregator.Publish(new NavigationMessage(GetBackScreen()));
    }
    else
    {
        var heading = ResourceProvider.GetString("Dialog.Navigate.Back.Heading");
        var text = ResourceProvider.GetString("Dialog.Navigate.Back.Text");
        var confirmationDialogViewModel = new ConfirmationDialogViewModel(heading, text);

        WindowManager.ShowChromelessDialog(confirmationDialogViewModel);

        if (confirmationDialogViewModel.Submitted)
        {
            EventAggregator.Publish(new NavigationMessage(GetBackScreen()));
        }
    }
}

By way of explanation, navigation in the application was managed by publishing navigation messages. The Shell view-model subscribed to the navigation messages and swapped the screens as appropriate when it handled such a message. Messaging was accomplished using Caliburn.Micro’s EventAggregator. Dialogs were managed using a class derived from Caliburn.Micro’s WindowManager class.
So the question was, given the code above how could I write unit tests that could test for cases when _confirmationDialogViewModel.Submitted was either true or false? My intention was to use Moq to mock the WindowManager so I would have to be able to access the _confirmationDialogViewModel passed in to WindowManager.ShowChromelessDialog(_confirmationDialogViewModel) and to be able to set its Submitted property.
How could I do that?

The solution

NB: Before I go on I should point out that there is an alternative – and arguably preferable - solution to the one presented below. Rather than instantiating the ConfirmationDialogViewModel as shown above it should have been injected into the parent view-model as a dependency. By so doing I could have simply set the Submitted property after instantiating the ConfirmationDialogViewModel in the unit test. This is what I actually ended up doing but the problem as presented above sparked my curiosity to see if it was possible to get at parameters passed into mocked methods.
Of course you can, by using Moq’s support for callbacks. There are several approaches to this but I liked the following:
[Test]
public void Back_IfConfirmationDialogIsSubmitted_NavigationMessageIsPublished()
{
    // Arrange
    _viewModel.Data = "Data has changed";

    ConfirmationDialogViewModel dialog;

    _mockEventAggregator.Setup(x => x.Publish(It.Is<NavigationMessage>(m => m.ScreenToNavigateTo == Screen.Home)));
    _mockWindowManager.Setup(w => w.ShowChromelessDialog(It.IsAny<ConfirmationDialogViewModel>()))
                      .Callback((object rootModel) => ((ConfirmationDialogViewModel)rootModel).Submit());

    // Act
    _viewModel.Back();

    // Assert
    _mockEventAggregator.Verify(x => x.Publish(It.Is<NavigationMessage>(m => m.ScreenToNavigateTo == Screen.Home)), Times.Once);
}

In this case we are able to call the Submit() method on the dialog view-model automatically when the mocked ShowChromelessDialog method is called (see lines 10 and 11). This in turn caused the Submitted property to be set to true. Job done!
Incidentally, if you need to you can get a reference to the method parameter by doing something like this:
[Test]
public void Back_IfConfirmationDialogIsSubmitted_NavigationMessageIsPublished()
{
    // Arrange
    _viewModel.Data = "Data has changed";
    _mockEventAggregator.Setup(x => x.Publish(It.Is<NavigationMessage>(m => m.ScreenToNavigateTo == Screens.EnquiryList)));

    ConfirmationDialogViewModel dialog = null;
    _mockWindowManager.Setup(w => w.ShowChromelessDialog(It.IsAny<ConfirmationDialogViewModel>()))
                      .Callback((object rootModel) => dialog = (ConfirmationDialogViewModel)rootModel);

    // Act
    _viewModel.Back();

    // We can now get at the dialog variable 
    var heading = dialog.Heading;

    // ... snip ...
 
}

In the example above you could access the dialog variable once the mocked ShowChromelessDialog method has been called.

Thursday, 26 December 2013

The Bounded Context in Domain Driven Design (DDD)

I have used NHibernate for some time now but have recently started to reengage with Microsoft’s Entity Framework. I came across Julie Lerman’s course Entity Framework in the Enterprise on Pluralsight. This is an interesting course and deals with Repositories and the Unit of Work pattern, two concepts I have used extensively with NHibernate. But Julie also deals with a DDD concept – the Bounded Context. It’s been a while since I’ve dealt with DDD so I thought I’d spend some time re-familiarising myself the Bounded Context.

Firstly, let’s see what Eric Evans had to say about Bounded Contexts in his book, “Domain-Driven Design, Tackling Complexity in the Heart of Software”.

“Multiple models coexist on big projects, and this works fine in many cases. Different models apply in different contexts.” [1]

“Multiple models are in play on any large project. Yet when code based on distinct models is combined, software becomes buggy, unreliable, and difficult to understand. Communication among team members becomes confused. It is often unclear in what context a model should not be applied.” [2]

“A model applies in a context. The context may be a certain part of the code, or the work of a particular team. For a model invented in a brainstorming session, the context could be limited to that particular conversation.” [2]

“A BOUNDED CONTEXT delimits the applicability of a particular model so that team members have a clear and shared understanding of what has to be consistent and how it relates to other CONTEXTS. Within that CONTEXT, work to keep the model logically unified, but do not worry about applicability outside those bounds. In other CONTEXTS, other models apply, with differences in terminology, in concepts and in rules, and in dialects of the UBIQUITOUS LANGUAGE. By drawing an explicit boundary, you can keep the model pure, and therefore potent, where it is applicable. At the same time, you avoid confusion when shifting your attention to other CONTEXTS. Integration across the boundaries necessarily will involve some translation, which you can analyze explicitly.” [3]

This makes perfect sense. You can see how the concept of a user, for example, would have different meanings to different departments within a business. If we tried to model a single user that has all the attributes required to satisfy all departments we might end up with a bloated and confused user entity. By separating the model into different bounded contexts, for different departments for example, and having the user defined separately within each context the result is more sharply focused and less confusing models.

The question that might remain is, how could we keep different bounded contexts synchronised? For example, if a user is created in one department in our hypothetical business application, how would we also create it in another at the same time? This could be accomplished using Domain Events or some kind of correlation ID for the same entity in different contexts.

 

See also

 

References

[1] Eric Evans, “Domain-Driven Design, Tackling Complexity in the Heart of Software”, ISBN 0-321-12521-5, p335.

[2] Eric Evans, “Domain-Driven Design, Tackling Complexity in the Heart of Software”, ISBN 0-321-12521-5, p336.

[3] Eric Evans, “Domain-Driven Design, Tackling Complexity in the Heart of Software”, ISBN 0-321-12521-5, p336-357.

Saturday, 21 December 2013

SQL Server indexing basics – a bit of revision

This post really just for me. You may get something from it but don’t expect very much! It’s been a while since I visited SQL Server indexing fundamentals so I thought I’d do a bit of revision and this post is really just my notes.

Pages

“The fundamental unit of data storage in SQL Server is the page. The disk space allocated to a data file (.mdf or .ndf) in a database is logically divided into pages numbered contiguously from 0 to n. Disk I/O operations are performed at the page level. That is, SQL Server reads or writes whole data pages.” [1]

  • The page size is 8 KB
  • This means databases have 128 pages per megabyte
  • Each page begins with a 96-byte header including:
    • Page number
    • Page type
    • Amount of free space on the page
    • Allocation unit ID of the object that owns the page

 

http://i.technet.microsoft.com/dynimg/IC147464.gif

 

Extents

“Extents are the basic unit in which space is managed. An extent is eight physically contiguous pages, or 64 KB. This means SQL Server databases have 16 extents per megabyte.” [1]

 

Heaps

“A heap is a table without a clustered index.” [2]

“If a table is a heap and does not have any nonclustered indexes, then the entire table must be examined (a table scan) to find any row.” [2]

  • Do not use a heap when
    • the data is frequently returned in a sorted order
    • the data is frequently grouped together
    • ranges of data are frequently queried from the table
    • there are no nonclustered indexes and the table is large

 

Indexes

“An index is an on-disk structure associated with a table or view that speeds retrieval of rows from the table or view. An index contains keys built from one or more columns in the table or view. These keys are stored in a structure (B-tree) that enables SQL Server to find the row or rows associated with the key values quickly and efficiently.” [3]

 

Clustered Indexes

  • Clustered indexes sort and store the data rows in the table or view based on their key values. These are the columns included in the index definition. There can be only one clustered index per table, because the data rows themselves can be sorted in only one order. [3]

  • The only time the data rows in a table are stored in sorted order is when the table contains a clustered index. When a table has a clustered index, the table is called a clustered table. If a table has no clustered index, its data rows are stored in an unordered structure called a heap. [3]

 

  • Clustered indexes
    • have a row in sys.partitions (with index_id = 1)
    • determine the physical order of data
  • Consider using when
    • There are a large number of distinct values in a column
    • On columns that are
      • frequently accessed
      • frequently searched for a range of values
    • Queries return very large result sets

 

Nonclustered indexes

  • Nonclustered indexes
    • do not affect the physical order of the data rows
    • have a structure separate from the data rows
    • contain the nonclustered index key values and each key value entry has a pointer to the data row that contains the key value
  • The pointer from an index row in a nonclustered index to a data row is called a row locator

 

Primary keys

  • A primary key automatically creates a clustered index, except when
    • a nonclustered primary key has been explicitly specified
    • a clustered index already exists

“Indexes are automatically created when PRIMARY KEY and UNIQUE constraints are defined on table columns. For example, when you create a table and identify a particular column to be the primary key, the Database Engine automatically creates a PRIMARY KEY constraint and index on that column.” [3]

 

Unique indexes (unique constraints)

  • A unique index is created when you create PRIMARY KEY or UNIQUE constraint. [4]
  • You can create a unique index independent of a constraint or when you create an indexed view

 

Filtered indexes

“A filtered index is an optimized nonclustered index especially suited to cover queries that select from a well-defined subset of data. It uses a filter predicate to index a portion of rows in the table. A well-designed filtered index can improve query performance as well as reduce index maintenance and storage costs compared with full-table indexes.” [5]

  • Use a filtered index when a well defined subset of results are part of a select statement.

 

Index Maintenance

Reorganise

  • Physically reorganises the leaf nodes of the index only

Rebuild

  • Drops the existing index and recreates it

Tips

  • Avoid DBCC SHRINKDB because it increases index fragmentation
  • Put the clustered index on the column that is distinct and increasing in value to avoid fragmentation
  • Check index fragmentation and then
    • If fragmentation is >5% <= 30% then reorganise the index
    • If fragmentation >30% then rebuild the index [6]

 

Beware

  • Too many indexes on a table can reduce performance
    • Execution plan can be less efficient
    • Queries can be less efficient
    • Queries may use the wrong – less efficient – index
  • Duplicate indexes offer no advantages and can reduce performance during inserts, updates and deletions
  • Unused indexes may also reduce performance during inserts, updates and deletions

 

References

[1] Understanding Pages and Extents – SQL 2008 documentation

[2] Heaps (Tables without Clustered Indexes) – SQL 2012 documentation

[3] Clustered and Nonclustered Indexes Described – SQL Server 2012 documentation

[4] Create Unique Indexes - SQL Server 2012 documentation

[5] Create Filtered Indexes - SQL Server 2012 documentation

[6] Reorganize and Rebuild Indexes - SQL Server 2012 documentation

Thursday, 19 December 2013

The Accidental DBA and the SQL Server Maintenance Solution

I recently came across 2 fantastic resources for understanding and implementing the essentials of maintaining SQL Server databases.

The Accidental DBA

As a software developer you often encounter situations where you become the DBA whether you want to or not. It is not uncommon to be working in an environment where there is no dedicated DBA but the applications under development rely on SQL Server as a back-end data store.

So, what do you need to know to keep the SQL Server database up-and-running and to prevent queries from slowing to a standstill? Well, it turns out there is an excellent series of blog posts on www.sqlskills.com called the Accidental DBA, offering 30 days of top tips. You can find the series here:

 

SQL Server Maintenance Solution

Something referred to by the Accidental DBA series is the SQL Server Maintenance Solution put forwards by Ola Hallengren. This awesome set of scripts allows you to run backups, perform integrity checks, and index and statistics maintenance on all editions of Microsoft SQL Server 2005, SQL Server 2008, SQL Server 2008 R2, and SQL Server 2012.

 

UPDATE 24/12/2013 – Replacement for sp_helpindex

Also on sqlskills.com, Kimberly Tripp has a replacement for the standard sp_helpindex stored procedure.