Hello concurrent world

Frances Buontempo from BuontempoConsulting


From Anthony William's "C++ concurrency in action - practical multithreading", section 1.4.1 gives a simple "Hello world" program using C++11's thread.

#include <iostream>
#include <thread>

void hello()
{
std::cout <<"Hello concurrent world!\n";
}


int main()
{
std::thread t(hello);
t.join();
}


After Matthew Wilson re-starting his series in Overload, "Quality Matters #7 Exceptions: the story so far" http://accu.org/var/uploads/journals/Overload114.pdf page 10ff, I had a nagging feeling I should put some exception handling round this.

First question, what happens if we make the hello throw an exception? For example, what would this do?

std::thread t_trouble( []{ throw std::exception("Oops");} );

It calls abort. The thread function mustn't let exceptions escape. Also, main should probably catch some exceptions; for example, maybe there aren't enough resources to start the thread yet.

#include <iostream>
#include <thread>

void hello()
{
try
{
std::cout <<"Hello concurrent world!\n";
}
catch(const std::exception& e)
{
//erm... what to do with it?
}
}


int main()
{
try
{
std::thread t(hello);//can I pass parameters? Nico says I can to async (page 964)
t.join(); //Nico says we can do a t.detach and when main exits it will get stopped
}
catch(const std::system_error& e) //pulled in by thread I presume
{
if(e.code() == std::errc::resource_unavailable_try_again)
{
std::cout << "Try again\n";
}
}
catch(const std::exception& e)
{
std::cout << e.what() << '\n';
}
}

Right, so now we are ignoring any exceptions that get thrown.
What should I do with any exceptions I get in a function that's sent to a thread? I could use std::exception_ptr, and std::rethrow_exception when a client tries to get the result. It might be better if I read all of Anthony's book (esp Chapter 8) and use std::packaged_task instead.

accu-general (http://accu.org/index.php/mailinglists) helpfully told me to read all the chapters in the book concurrently.

Writing: Bug Hunting

Pete Goodliffe from Pete Goodliffe

The latest  C Vu magazine from ACCU is out now. It contains my latest Becoming a Better Programer column. This month it's called Bug Hunting and, as you might guess, is about the art of debugging code.

This was inspired by conversations with Greg Law in the lead up to the 2013 ACCU conference.

Visual Lint and Windows Driver Kit (WDK) projects

Products, the Universe and Everything from Products, the Universe and Everything

We have recently been working with Don Burn on PC-lint analysis of Windows Driver Kit (WDK) projects, and he has written an interesting article on the subject titled "Another Look at Lint" in the March-April 2013 issue of the NT Insider.

Within the article you will find the following rather complementary passage:

Finally the ultimate tool for using PC-lint with the WDK is Riverblade's Visual Lint. This is a third party tool providing an integrated package that works inside VS2012. The tool is an add-on to PC-lint which you must still purchase. The capabilities include background analysis of the project, coded display listings that - like Visual Studio - clicking on the error takes you to the line to edit and provides easy lookup of the description of the errors. The latest version of Visual Lint (4.0.2.198) is required for use with the WDK. The tool has a minor bug that if there are two subprojects with the same name, such as filter in the Toaster sample, one needs to be renamed for analysis to work. A fix is in the works.

To use Visual Lint with the WDK choose LintLdx.lnt as the standard lint configuration file for the tool. There is a 30-day free trial of Visual Lint available so if you are considering PC-lint, take a look at what Visual Lint can add to the experience. I expect to be using it for much of my work.

Our thanks to Don Burn for his patience while we worked through the issues raised by the analysis of WDK projects. As a postscript, a fix for the bug he refers to above has already been checked in and should become available in the next public Visual Lint build (most likely 4.0.3.200).

Visual Lint and Windows Driver Kit (WDK) projects

Products, the Universe and Everything from Products, the Universe and Everything

We have recently been working with Don Burn on PC-lint analysis of Windows Driver Kit (WDK) projects, and he has written an interesting article on the subject titled "Another Look at Lint" in the March-April 2013 issue of the NT Insider.

Within the article you will find the following rather complementary passage:

Finally the ultimate tool for using PC-lint with the WDK is Riverblade's Visual Lint. This is a third party tool providing an integrated package that works inside VS2012. The tool is an add-on to PC-lint which you must still purchase. The capabilities include background analysis of the project, coded display listings that - like Visual Studio - clicking on the error takes you to the line to edit and provides easy lookup of the description of the errors. The latest version of Visual Lint (4.0.2.198) is required for use with the WDK. The tool has a minor bug that if there are two subprojects with the same name, such as filter in the Toaster sample, one needs to be renamed for analysis to work. A fix is in the works.

To use Visual Lint with the WDK choose LintLdx.lnt as the standard lint configuration file for the tool. There is a 30-day free trial of Visual Lint available so if you are considering PC-lint, take a look at what Visual Lint can add to the experience. I expect to be using it for much of my work.

Our thanks to Don Burn for his patience while we worked through the issues raised by the analysis of WDK projects. As a postscript, a fix for the bug he refers to above has already been checked in and should become available in the next public Visual Lint build (most likely 4.0.3.200).

Visual Lint and Windows Driver Kit (WDK) projects

Products, the Universe and Everything from Products, the Universe and Everything

We have recently been working with Don Burn on PC-lint analysis of Windows Driver Kit (WDK) projects, and he has written an interesting article on the subject titled "Another Look at Lint" in the March-April 2013 issue of the NT Insider. Within the article you will find the following rather complementary passage:
Finally the ultimate tool for using PC-lint with the WDK is Riverblade's Visual Lint. This is a third party tool providing an integrated package that works inside VS2012. The tool is an add-on to PC-lint which you must still purchase. The capabilities include background analysis of the project, coded display listings that - like Visual Studio - clicking on the error takes you to the line to edit and provides easy lookup of the description of the errors. The latest version of Visual Lint (4.0.2.198) is required for use with the WDK. The tool has a minor bug that if there are two subprojects with the same name, such as filter in the Toaster sample, one needs to be renamed for analysis to work. A fix is in the works. To use Visual Lint with the WDK choose LintLdx.lnt as the standard lint configuration file for the tool. There is a 30-day free trial of Visual Lint available so if you are considering PC-lint, take a look at what Visual Lint can add to the experience. I expect to be using it for much of my work.
Our thanks to Don Burn for his patience while we worked through the issues raised by the analysis of WDK projects. As a postscript, a fix for the bug he refers to above has already been checked in and should become available in the next public Visual Lint build (most likely 4.0.3.200).

Windows 8 Pro on an early 2009 iMac 21.5 (Core 2 Duo)

Pete Barber from C#, C++, Windows &amp; other ramblings

A couple of weeks back I thought I'd have a go writing a Windows Store App.  To do this requires Windows 8.  At the time I was running Windows 7 Home Premium on an early 2009 iMac 21.5 (Core 2 Duo).  This had been installed using Boot Camp including install Boot Camp assistant and the drivers supplied by Apple.

To upgrade to Windows 8 I wanted to avoid a re-installation of all my apps. and data etc so I went with an in place upgrade.  This all seemed to work properly and soon I was running Windows 8 and could access the Windows Store App templates from Visual Studio.  However, soon after Windows 8 kept crashing, well freezing.  It got to the point that after every reboot I'd be lucky to get 5 minutes of up time between each freeze.

Given that Apple haven't provided Windows 8 drivers yet this wasn't exactly a surprise.  I decided to try and work around this by rebooting to OS X and using VMWare Fusion to access the Boot Camp partition.  Whilst rebooting in OS X I managed to corrupt the Windows installation.  I use a non-Apple wireless keyboard (as I need the insert, delete, home & end plus the easily accessible cursor keys for VS development) so holding down Alt to select the OS to boot into didn't work.  When I realized it was going back into Windows I just turned the machine off.  After a couple of times the Windows installation was toast!  To get back to the point of trying Fusion I had to do a fresh Windows install.  In this case installing a minimal Windows 7 installation: just enough to allow the download of Windows 8.  I then installed Windows 8 using the preserve nothing option.

Having now gone through the steps I wanted to avoid I decided to give the new installation a go via direct boot, i.e. no Fusion.  That was two weeks ago.  Since then I've re-installed all the apps. and my personal data and (fingers crossed) haven't had a single crash.  As the freezes were usually happening during some graphical operation e.g. a status bar updating I assumed the fault probably lay with the video drivers.  I didn't install Boot Camp assistant and in particular the Windows 7 drivers from OS X disc.  Well, I did install one.  After a while I noticed I wasn't getting any sound even though all the audio drivers and hardware claimed they were happy.  Eventually I installed by the Cirrus Logic driver which made the speakers work. I haven't gone anywhere near the NVIDIA drivers.

So, the whole point of this post is for those who run Windows via Boot Camp on early iMacs and want to run Windows 8 then perhaps a fresh install (or maybe uninstall the Boot Camp supplied drivers prior to upgrade) is probably the way to go.

Specifying the directory to create SQL CE databases when using Entity Framework

Pete Barber from C#, C++, Windows &amp; other ramblings

In the last few posts I've been describing how to create instances of SQLCE in order to perform automated Integration Testing using NUnit and accessing the dB using Entity Framework.  I covered creating the dB using both Entity Framework and the SQL CE classes.  In particular I wanted control over the directory the dB was created in but I didn't want to tie to a specific location rather let it use the current working directory.

Using the Entity Framework's DbContext constructor that takes the name of a connection string or database name it's suddenly very easy to end up NOT creating the dB you expected where you expected it to be.  This post shows how to avoid these.  Generally speaking the use of the DbContext constructor that takes a Connection String should be avoided unless the name of a connection string from the .config file is being specified.

Example 1 - Using the SqlCeEngine class
1:  const string DB_NAME = "test1.sdf";  
2: const string DB_PATH = @".\" + DB_NAME; // Use ".\" for CWD or a specific path
3: const string CONNECTION_STRING = "data source=" + DB_PATH;
4:
5: using (var eng = new SqlCeEngine(CONNECTION_STRING))
6: {
7: eng.CreateDatabase();
8: }
9:
10: using (var conn = new SqlCeConnection(CONNECTION_STRING))
11: {
12: conn.Open(); // do stuff with db...
13: }
14:

The important thing to note is that the constructor for SqlCeEngine that takes an argument requires a Connection String, i.e. a string containing the "data source=...".  Just specifying the dB path is not sufficient.  To specify a specific directory  include the absolute or relative path.  To specify the current working directory, e.g. bin\debug then just use ".\".

Example 2 - Using DbContext (doesn't work)
1:  using (var ctx = new DbContext("test2.sdf"))  
2: {
3: ctx.Database.Create();
4: }

This code appears to work but doesn't create an instance of an SQL CE dB as desired.  Instead it creates a localDB instance in the user's home directory.  In my case: C:\Users\Pete\._test.sdf.mdf (& corresponding log file).  This is not really surprising as Entity Framework had no way of knowing that a SQL CE dB should be created.

Example 3 - Using DbContext (does work)
1:  Database.DefaultConnectionFactory =  
2: new SqlCeConnectionFactory(
3: "System.Data.SqlServerCe.4.0",
4: @".\", "");
5:
6: using (var ctx = new DbContext("test2.sdf"))
7: {
8: ctx.Database.Create();
9: // do stuff with ctx...
10: }

The difference between the last and this example is changing the default type of dB that EF should create.  As shown this is done by installing a different factory.

The 3rd parameter to SqlCeConnectionFactory is the directory that the dB should be created in.  Just like the first example specifying ".\" means the current working directory and specifying an absolute path to a directory will lead to them being created there.

NOTE: As per the post Integration Testing with NUnit and Entity Framework be aware that creating a dB using the Entity Framework results in the additional table '_MigrationHistory' being created which EF uses to keep the model and dB synchronized.

NOTE1: Whereas SqlCeEngine is a SQL CE class from the System.Data.SqlServerCe assembly, SqlCeConnectionFactory appears to be part of the System.Data.Entity assembly which is part of the Entity Framework.


In the above example the string passed to DbContext can be a name (of a connection string from the .config file) or a connection string.  In this case passing the name of the db, i.e. test2.sdf is equivalent to passing "data source=test2.sdf", well more or less.  If the '.sdf' suffix is omitted with "data source" then the resultant dB is called test2 but if just test2 is passed then the resulting dB will be called test2.sdf.

Example 4 - Using DbContext and the .config file
1:  using (var ctx = new DbContext("test5"))  
2: {
3: ctx.Database.Create();
4: }

App or Web .config
1:  <connectionStrings>  
2: <add name="test5"
3: providerName="System.Data.SqlServerCe.4.0"
4: connectionString="Data Source=test5.sdf"/>
5: </connectionStrings>

This time no factory is specified but the argument to DbContext is the name of a Connection String in the .config file.  As can be seen this contains similar information to that in the factory method enabling EF to create a dB of the correct type.

To use these the instances of these databases rather than calling the create method on the context just use the context directly or more likely in the case of EF a derived context which brings us to one last example.

Example 5 - Using a derived context and .config file
1:  public class TestCtx : DbContext  
2: {
3: }
4: using (var ctx = new TestCtx())
5: {
6: ctx.Database.Create();
7: }

App or Web .config
1:  <connectionStrings>  
2: <add name="TestCtx"
3: providerName="System.Data.SqlServerCe.4.0"
4: connectionString="Data Source=test6.sdf"/>
5: </connectionStrings>

If a derived context is created which will almost certainly be the case then if an instance of this is created and a dB created then EF will look for a Connection String in the .config file that has the same name as the context and take the information from there.

Integration Testing with NUnit and Entity Framework

Pete Barber from C#, C++, Windows &amp; other ramblings

This post gives a quick introduction into creating SQL CE dBs for performing Integration Tests using NUnit.

In the previous post Using NUnit and Entity Framework DbContext to programmatically create SQL Server CE databases and specify the databse directory a basic way was shown to how to create a new dB (using Entity Framework's DbContext) programmtically.  This was used to generate a new dB for a test hosted by NUnit.

The subsequent post Generating a SQL Server CE database schema from a SQL Server database using Entity Framework showed how to generate a SQL CE dB schema from an existing SQL Server database.

This post ties theprevious ones together.  As mentioned in the first post the reason for this is an attempt at what amounts to Integration Testing using NUnit.  I'm currently building a Repository and Unit Of Work abstraction on top of Entity Framework which will allow the isolation of the dB code (in fact it will isolate and abstract away most forms of data storage).  This means any business logic can be tested with a test-double that implements the Repository and UnitOfWork interfaces; which is straight forward Unit Testing.  The Integration Testing is to verify that the Repository and Unit Of Work implementations work correctly.

The rest of the post isn't focused on these two patterns; though it may mention them.  Instead it documents my further experience of using NUnit to writes tests that interact with dB via Entity Framework.  The premise for this is that a dB already exists.

As such the approach to using Entity Framework is a hybrid of Database First and Code First in that the dB schema exists and needs be maintained outside of EF and also that EF should not generate model classes, i.e. allowing the use of Code First POCOs.  This is possible as the POCOs can be defined, a connection made to dB and then the two are conflated via an EF DbContext.  It then seems that EF creates the model on the fly (internally compiles it) and as long as the POCO types map to the dB types then it all works as if by magic!

The advantage of doing it this way is that the existing dB is SQL Express based but for the Integration Testing a new dB can be created when needed, potentially one per test.  In order to keep the test dBs isolated from the real dB SQL Server Compact Edition (SQL Server CE V4) was used.  Therefore the requirement was for the EF code to be able to work with SQL Express and SQL CE with the primary definition of the schema taken from SQL Express.  It's not possible to use exactly the same schema as SQL CE only has a subset of the data-types provides by SQL CE.  However, the process described in the post 
Generating a SQL Server CE database schema from a SQL Server database using Entity Framework showed how to create semantically equivalent SQL.


From this point onwards it's assumed that an SQL file to create the dB has been generated.  Now create a new C# class library project and using the NUGet add Entity Framework, NUnit and SQL CE 4.0.  All my work has been with EF 4.3.1.  Following this drag the Model1.edmx.sqlce file from the project used to generate to new project.  You may wish to rename it, e.g. to test.sqlce.


Creating the database

The post Generating a SQL Server CE database schema from a SQL Server database using Entity Framework showed how to create a new CE dB per-test using the EF DbContext to do the hard work.  A different approach is now taken as the problem with creating a dB using DbContext is that in addition to creating any specified tables and indices etc. it also creates an additional table called '__MigrationHistory' which contains a description of the EF model used to create the dB.  The description of the problem caused by this will be delayed until the "Why DbContext is no longer used to create the database" section.  Suffice to say for the present using the new mechanism avoids the creation of this table.

The code below is the beginnings of a test class.  It is assumed all the tests need a fresh copy of the dB hence the creation is performed in the Setup method.  All this code does is create a SQL CE dB and then
creates the schema.

1:  [TestFixture]  
2: public class SimpleTests
3: {
4: const string DB_NAME = "test.sdf";
5: const string DB_PATH = @".\" + DB_NAME;
6: const string CONNECTION_STRING = "data source=" + DB_PATH;
7: [SetUp]
8: public void Setup()
9: {
10: DeleteDb();
11: using (var eng = new SqlCeEngine(CONNECTION_STRING))
12: eng.CreateDatabase();
13: using (var conn = new SqlCeConnection(CONNECTION_STRING))
14: {
15: conn.Open();
16: string sql=ReadSQLFromFile(@"C:\Users\Pete\work\Jub\EFTests\Test.sqlce");
17: string[] sqlCmds = sql.Split(new string[] { "GO" }, int.MaxValue, StringSplitOptions.RemoveEmptyEntries);
18: foreach (string sqlCmd in sqlCmds)
19: try
20: {
21: var cmd = conn.CreateCommand();
22:
23: cmd.CommandText = sqlCmd;
24: cmd.ExecuteNonQuery();
25: }
26: catch (Exception e)
27: {
28: Console.Error.WriteLine("{0}:{1}", e.Message, sqlCmd);
29: throw;
30: }
31: }
32: }
33: public void DeleteDb()
34: {
35: if (File.Exists(DB_PATH))
36: File.Delete(DB_PATH);
37: }
38: private string ReadSQLFromFile(string sqlFilePath)
39: {
40: using (TextReader r = new StreamReader(sqlFilePath))
41: {
42: return r.ReadToEnd();
43: }
44: }
45: }
46:
The dB file (Test.sdf) will be created in the current working directory.  As the test assembly is located in <project>\bin\debug which is where the NUnit test runner picks up the DLL from this directory this is where it is created.  If a specific directory is required then the '.\' can be replaced with the required path.

The Setup method is marked with NUnit's SetUp attribute meaning it will be invoked on a per-test basis creating a new dB instance for each test.  The DeleteDb method could be marked with [TearDown] attribute but at the moment any previous dB is deleted before creating a new one.  It would be fine to do both as a belt and braces approach.  The reason I didn't make it the TearDown method is so that I could inspect the dB following a test if needed.

SQL CE does not support batch execution of SQL scripts which is where it gets interesting as the SQL generated previously is in batch form.  The code reads the entire file into a string and determines each individual statement by splitting string on the 'GO' command that separates each SQL command.

To help understand the SQL the following is the diagram of the dB I'm working with.  All fields are strings except for the Ids which are numeric.
Each of these commands is then executed.  The previously generated SQL (the SQL for the dB I'm working with is below) will not work completely out of the box.  The ALTER and DROP statements at the beginning don't apply as the schema is being applied to an empty dB, these should be removed.  Interestingly the schema generation step for my dB seems to miss out a 'GO' between the penultimate and ultimate statement.  I had to add one by hand.  Finally, the comments at the end prove a problem as there is no terminating 'GO'.  Removing these fixes the problem.  In the code above the exception handler re-throws the exception after writing out the details.  For everything to proceed the SQL needs modifying to execute perfectly.  If the re-throw is removed then the code will tolerate individual command failures which in this context really just amount to warnings.

NOTE: Text highlighted in red has been removed and text in blue added.

-- --------------------------------------------------
-- Entity Designer DDL Script for SQL Server Compact Edition
-- --------------------------------------------------
-- Date Created: 07/29/2012 12:28:35
-- Generated from EDMX file: C:\Users\Pete\work\Jub\DummyWebApplicationToGenerateSQLServerCE4Script\Model1.edmx
-- --------------------------------------------------


-- --------------------------------------------------
-- Dropping existing FOREIGN KEY constraints
-- NOTE: if the constraint does not exist, an ignorable error will be reported.
-- --------------------------------------------------

    ALTER TABLE [RepComments] DROP CONSTRAINT [FK_RepComments_Reps];
GO

-- --------------------------------------------------
-- Dropping existing tables
-- NOTE: if the table does not exist, an ignorable error will be reported.
-- --------------------------------------------------

    DROP TABLE [RepComments];
GO
    DROP TABLE [Reps];
GO
    DROP TABLE [Roads];
GO

-- --------------------------------------------------
-- Creating all tables
-- --------------------------------------------------

-- Creating table 'RepComments'
CREATE TABLE [RepComments] (
    [CommentId] int IDENTITY(1,1) NOT NULL,
    [RepId] int  NOT NULL,
    [Comment] ntext  NOT NULL
);
GO

-- Creating table 'Reps'
CREATE TABLE [Reps] (
    [RepId] int IDENTITY(1,1) NOT NULL,
    [RepName] nvarchar(50)  NOT NULL,
    [RoadName] nvarchar(256)  NOT NULL,
    [HouseNumberOrName] nvarchar(50)  NOT NULL,
    [ContactTelNumber] nvarchar(20)  NOT NULL,
    [Email] nvarchar(50)  NULL
);
GO

-- Creating table 'Roads'
CREATE TABLE [Roads] (
    [Name] nvarchar(256)  NOT NULL
);
GO

-- --------------------------------------------------
-- Creating all PRIMARY KEY constraints
-- --------------------------------------------------

-- Creating primary key on [CommentId] in table 'RepComments'
ALTER TABLE [RepComments]
ADD CONSTRAINT [PK_RepComments]
    PRIMARY KEY ([CommentId] );
GO

-- Creating primary key on [RepId] in table 'Reps'
ALTER TABLE [Reps]
ADD CONSTRAINT [PK_Reps]
    PRIMARY KEY ([RepId] );
GO

-- Creating primary key on [Name] in table 'Roads'
ALTER TABLE [Roads]
ADD CONSTRAINT [PK_Roads]
    PRIMARY KEY ([Name] );
GO

-- --------------------------------------------------
-- Creating all FOREIGN KEY constraints
-- --------------------------------------------------

-- Creating foreign key on [RepId] in table 'RepComments'
ALTER TABLE [RepComments]
ADD CONSTRAINT [FK_RepComments_Reps]
    FOREIGN KEY ([RepId])
    REFERENCES [Reps]
        ([RepId])
    ON DELETE NO ACTION ON UPDATE NO ACTION;
GO
-- Creating non-clustered index for FOREIGN KEY 'FK_RepComments_Reps'
CREATE INDEX [IX_FK_RepComments_Reps]
ON [RepComments]
    ([RepId]);
GO

-- --------------------------------------------------
-- Script has ended
-- --------------------------------------------------

Getting the SQL into a state where it will run flawlessly is a little bit of a hassle but given the number of times it will be used subsequently it's job a big job, well for a small dB anyway.  To verify that your dB has been created as needed an quick and easy way to test is to comment out the call to DeleteDb() and after a test has run open to the dB using Server Explorer within VS, i.e.



Using the dB in a test

Now that a fresh dB will be created for each test it's time to look at simple test:

1:  [Test]  
2: public void TestOne()
3: {
4: using (var conn = new SqlCeConnection(CONNECTION_STRING))
5: using (var ctx = new TestCtx(conn))
6: {
7: ctx.Roads.Add(new Road() { Name = "Test" });
8: ctx.SaveChanges();
9: Assert.That(1, Is.EqualTo(ctx.Roads.Count()));
10: }
11: }
Road in this case is defined as:

1:  class Road  
2: {
3: [Key]
4: public string Name { get; set; }
5: }

The first thing to note is that EF is not used to form the connection to the dB, instead one is made using the SqlCe specific classes.  Attempting to get EF to connect to a specific dB instance when not referring to a named connection strings in the .config file is a bit of an art (I may write another entry about this).  However, EF is quite happy to work with an existing connection.  This makes for a good separation of responsibilities in the code where EF manages the interactions with the dB but the control of the connection is elsewhere.

NOTE: It is likely that each test will require a connection and a context hence rather it might make more sense to move the creation of the SqlCeConnection and the context (TestCtx in this case) to a SetUp method and as these resources need disposing of adding a TearDown method to do that.  TestCtx could also be modified to pass true to the DbContext constructor to give ownership of the connection to the context so that it will dispose of it then context is disposed off.

I would have preferred to avoid having to defined a specific derived context and instead use DbContext directory, e.g.
1:  [Test]  
2: public void TesTwo()
3: {
4: using (var conn = new SqlCeConnection(CONNECTION_STRING))
5: using (var ctx = new DbContext(conn, false))
6: {
7: ctx.Set<Road>().Add(new Road() { Name = "Test" });
8: ctx.SaveChanges();
9: Assert.That(1, Is.EqualTo(ctx.Set<Road>().Count()));
10: }
11: }

However when SaveChanges() is called the following exception is thrown:

System.InvalidOperationException : The entity type Road is not part of the model for the current context.

This is because EF knows nothing about the Road type.  When a derived context is created for the first time I think EF performs reflection on any properties that expose DbSet.  These are the types that form the Model.  Another option is to create the model, optionally compile it and then pass it to an instance of DbContext.  This way involves a lot less code.

That's it.  The final section is just footnote about the move away from using EF to create the dB.

Why DbContext is no longer used to create the database

As mentioned creating the dB using:
1:  using (var ctx = new DbContext("bar.sdf"))  
2: {
3: ctx.Database.Create();
4: // create schema etc.
5: }
causes the '__MigrationHistory' table to be created.  Assuming this method was used, later on when TestCtx was used top open the dB and perform an operation the following exception would be thrown:

System.InvalidOperationException : The model backing the 'DbContext' context has changed since the database was created. Consider using Code First Migrations to update the database (http://go.microsoft.com/fwlink/?LinkId=238269).
This is because the context used to create the model was a raw DbContext (as per the previous post) whereas the dB was accessed via the TestCtx.  If the context used to create the dB is also changed to TestCtx then this problem goes away.
However, given the original dB is not intended to be created nor be maintained (code migrations) by EF then using the non-context/EF approach to dB completely removes EF from the picture.









Visual Studio 2012 theme support

Products, the Universe and Everything from Products, the Universe and Everything

One of the unexpected (and I would suggest from the comments, unwelcome) changes sprung on developers in the Visual Studio 2012 Beta back in February was the Metroification of the development environment.

However, eye candy (and eyesores!) come and go, and within that change is a more fundamental one - direct support for themes within the Visual Studio IDE. The Visual Studio 2012 Beta and RC include two themes - light (i.e. grey) and dark. Whilst the latter has an obvious appeal within the developer community (we all know devs who prefer green text on a black background) the former hasn't exactly been welcomed, to say the least.

Personally, rather than develop custom theme support for each tool individually I wish they'd just add a "dark" theme to Windows instead and respect the theme settings of the operating system. Obviously my view just isn't "cool" enough for the Visual Studio UX team, but I digress...

Although a campaign to retain the existing Visual Studio 2010 theme has been running on the UserVoice site since the beta arrived (see Add some color to Visual Studio 11 and Leave VS 2010 theme (and the theme editor extension) as an option) Microsoft have not indicated what - if any - changes will be made to the Visual Studio 2012 themes at RTM.

Our working assumption therefore has to be that the themes in the RTM will be broadly comparable with those in the RC (i.e. light and dark). We will find out whether that assumption is correct later this month, of course.

With that in mind, we have been working on theme support in the development branch for Visual Lint for some time now, and things are now beginning to come together:

Visual Lint running with the Visual Studio 2012 RC dark theme

Visual Lint running with the Visual Studio 2012 RC light theme

As Visual Lint uses standard Win32 controls for most of the UI (which for the most part do not support custom text/background colours), to get this far we have had to write custom painted WTL checkbox, radio button, combobox and header controls in addition to the usual WM_CTLCOLORxxxx voodoo. Other UI elements such as menus, scrollbars, command buttons etc. yet haven't yet been looked at, but hopefully will be in due course (there seems to be some indication in the MSDN blogs that scollbars will be auto-themed by the RTM, but we'll see).

Within the displays themselves, the text and background colours of each item are checked for adequate contrast, and the text colour adjusted (by tweaking the luminance) automatically if need be.

Although the Visual Studio interfaces expose the colours used in the active theme (via IVsUIShell2::GetVSSysColorEx() ), they do not seem to provide any way of detecting if the theme has changed (or indeed, finding out which theme is actually running at the time). Our workaround for this is simply to reload the colour scheme whenever the "Tools|Options" command has been executed. We don't really care which theme is running after all - just what colour values it uses, and where.

Indeed, one of the first things we did while working on this was to dump all of the colour values used by the VS2012 RC light & dark themes, as well as the default VS2010 theme, into spreadsheets so we could use them for testing without firing up a host instance of the IDE (developing add-ins may be fun, but it is also much slower than working on your own executable).

Finally, it is a little known fact that the Visual Studio IDE has had colour scheme support internally for some time, so the scheme we have designed will also work with Visual Studio 2010 if you have the theme editor extension installed:

Visual Lint running with Visual Studio 2010 with a modified 'Expression' theme

Needless to say, all of this is proving to be a major task, and it has therefore diverted significant resources from other things we should really have been working on this summer. As a consolation, the theme code we're developing is generic (albeit only on Windows), so can also be used with Eclipse 4.0 (I note that themes are coming to that IDE as well) when the time comes.

Another obvious benefit is of course that there's potentially at least one new CodeProject article (want a themed XP button with a custom background colour? We know how to do it now) in all of this once the dust settles and the inevitable bugs have crawled away. It's about time I wrote a new one, anyway.

Once Visual Lint theme support is complete, we'll obviously also take a look at ResOrg. Beyond that, I think a new article is a foregone conclusion, once we've cleaned the code up a bit and built a good enough demo project...