<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:atom="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearch/1.1/" xmlns:blogger="http://schemas.google.com/blogger/2008" xmlns:georss="http://www.georss.org/georss" xmlns:gd="http://schemas.google.com/g/2005" xmlns:thr="http://purl.org/syndication/thread/1.0" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0"><channel><atom:id>tag:blogger.com,1999:blog-2918646278142295649</atom:id><lastBuildDate>Wed, 19 Jun 2013 09:17:48 +0000</lastBuildDate><category>Fluent</category><category>Computer humour joke</category><category>Graph</category><category>MVVM</category><category>cover</category><category>Fluent Functor</category><category>Data Context</category><category>Updated</category><category>Visual Studio 2005</category><category>Control</category><category>CodeProject</category><category>event</category><category>DbContext</category><category>Unit of work</category><category>start-up</category><category>C++</category><category>Dependency Property</category><category>CustomAttribute</category><category>TDD</category><category>Twitter "London Surrey Cycle Classic" "Mark Cavendish" #CycleClasic #testevent Twittating Spectwitter Spectwiting</category><category>C++ Unit Testing templates SFINAE TMP sizeof "compilation failure" COM ATL STL CAdapt</category><category>IEnumerator</category><category>Fluent Programming</category><category>EventToCommand</category><category>User Control</category><category>NFS C# .NET Server "Open Source"</category><category>encapsulation</category><category>DbContext SQLServerCE C# NUnit CodeProject SqlCeConnectionFactory databaseDirectory</category><category>.NET 2.0</category><category>"Computer humour" joke UDP</category><category>tactile</category><category>DataContext</category><category>NUnit</category><category>event-to-command pattern</category><category>Code First</category><category>DbContext SQLServerCE C# NUnit SqlCeConnectionFactory</category><category>Windows 8 iMac 21.5 Boot Camp</category><category>Spirit</category><category>Unit Test</category><category>design-time</category><category>IEnumerable</category><category>enumeration</category><category>Intergration Test</category><category>Attribute</category><category>EventCommand</category><category>SizeChanged</category><category>IPad2</category><category>Pattern</category><category>C# "command line" argument parsing attributes reflection TDD WPF</category><category>C#</category><category>C++ C++11 CodeProject</category><category>TreeView</category><category>event to command</category><category>CodeProject C++ C++11  constexpr range-for</category><category>EF</category><category>Dilbert</category><category>enumerator</category><category>Entity Framework DbContext SQLServerCE C# NUnit CodeProject SqlCeConnectionFactory databaseDirectory</category><category>WPF</category><category>Entity Framework</category><title>C#, C++, Windows &amp; other ramblings</title><description /><link>http://petebarber.blogspot.com/</link><managingEditor>noreply@blogger.com (Pete Barber)</managingEditor><generator>Blogger</generator><openSearch:totalResults>26</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/CCWindowsOtherRamblings" /><feedburner:info uri="ccwindowsotherramblings" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item><guid isPermaLink="false">tag:blogger.com,1999:blog-2918646278142295649.post-9156213616650872113</guid><pubDate>Wed, 21 Nov 2012 08:44:00 +0000</pubDate><atom:updated>2012-11-21T00:44:41.165-08:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Windows 8 iMac 21.5 Boot Camp</category><title>Windows 8 Pro on an early 2009 iMac 21.5 (Core 2 Duo)</title><description>A couple of weeks back I thought I'd have a go writing a Windows Store App. &amp;nbsp;To this requires Windows 8. &amp;nbsp;At the time I was running Windows 7 Home Premium on an early 2009 iMac 21.5 (Core 2 Duo). &amp;nbsp;This had been installed using Boot Camp including install Boot Camp assistant and the drivers supplied by Apple.&lt;br /&gt;
&lt;br /&gt;
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. &amp;nbsp;This all seemed to work properly and soon I was running Windows 8 and could access the Windows Store App templates from Visual Studio. &amp;nbsp;However, soon after Windows 8 kept crashing, well freezing. &amp;nbsp;It got to the point that after every reboot I'd be lucky to get 5 minutes of up time between each freeze.&lt;br /&gt;
&lt;br /&gt;
Given that Apple haven't provided Windows 8 drivers yet this wasn't exactly a surprise. &amp;nbsp;I decided to try and work around this by rebooting to OS X and using VMWare Fusion to access the Boot Camp partition. &amp;nbsp;Whilst rebooting in OS X I managed to corrupt the Windows installation. &amp;nbsp;I use a non-Apple wireless keyboard (as I need the insert, delete, home &amp;amp; end plus the easily accessible cursor keys for VS development) so holding down Alt to select the OS to boot into didn't work. &amp;nbsp;When I realized it was going back into Windows I just turned the machine off. &amp;nbsp;After a couple of times the Windows installation was toast! &amp;nbsp;To get back to the point of trying Fusion I had to do a fresh Windows install. &amp;nbsp;In this case installing a minimal Windows 7 installation: just enough to allow the download of Windows 8. &amp;nbsp;I then installed Windows 8 using the preserve nothing option.&lt;br /&gt;
&lt;br /&gt;
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. &amp;nbsp;That was two weeks ago. &amp;nbsp;Since then I've re-installed all the apps. and my personal data and (fingers crossed) haven't had a single crash. &amp;nbsp;As the freezes were usually happening during some graphical operation e.g.&amp;nbsp;a status bar updating I assumed the fault probably lay with the video drivers. &amp;nbsp;I didn't install Boot Camp assistant and in particular the Windows 7 drivers from OS X disc. &amp;nbsp;Well, I did install one. &amp;nbsp;After a while I noticed I wasn't getting any sound even though all the audio drivers and hardware claimed they were happy. &amp;nbsp;Eventually I installed by the Cirrus Logic driver which made the speakers work. I haven't gone anywhere near the NVIDIA drivers.&lt;br /&gt;
&lt;br /&gt;
So, the whole point of this post is for those who run Windows via Boot Camp on early iMac's that if you 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.&lt;img src="http://feeds.feedburner.com/~r/CCWindowsOtherRamblings/~4/HF_28OIwqGU" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/CCWindowsOtherRamblings/~3/HF_28OIwqGU/windows-8-pro-on-early-2009-imac-215.html</link><author>noreply@blogger.com (Pete Barber)</author><thr:total>19</thr:total><feedburner:origLink>http://petebarber.blogspot.com/2012/11/windows-8-pro-on-early-2009-imac-215.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-2918646278142295649.post-6248346524235711788</guid><pubDate>Fri, 03 Aug 2012 11:49:00 +0000</pubDate><atom:updated>2012-08-03T04:57:10.264-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Entity Framework DbContext SQLServerCE C# NUnit CodeProject SqlCeConnectionFactory databaseDirectory</category><title>Specifying the directory to create SQL CE databases when using Entity Framework</title><description>In the last few &lt;a href="http://petebarber.blogspot.co.uk/2012/08/integration-testing-with-nunit-and.html"&gt;posts&lt;/a&gt; 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. &amp;nbsp;I covered creating the dB using both Entity Framework and the SQL CE classes. &amp;nbsp;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.&lt;br /&gt;
&lt;br /&gt;
Using the Entity Framework's &lt;a href="http://msdn.microsoft.com/en-us/library/system.data.entity.dbcontext(v=vs.103).aspx"&gt;DbContext &lt;/a&gt;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. &amp;nbsp;This post shows how to avoid these. &amp;nbsp;Generally speaking the use of the DbContext constructor that takes a &lt;a href="http://msdn.microsoft.com/en-us/library/cc716756.aspx"&gt;Connection String&lt;/a&gt;&amp;nbsp;should be avoided unless the name of a connection string from the .config file is being specified.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Example 1 - Using the SqlCeEngine class&lt;/b&gt;&lt;br /&gt;
&lt;pre style="background-image: URL(http://2.bp.blogspot.com/_z5ltvMQPaa8/SjJXr_U2YBI/AAAAAAAAAAM/46OqEP32CJ8/s320/codebg.gif); background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"&gt;&lt;code style="color: black; word-wrap: normal;"&gt;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:    
&lt;/code&gt;&lt;/pre&gt;
&lt;br /&gt;
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=...". &amp;nbsp;Just&amp;nbsp;specifying&amp;nbsp;the dB path is not sufficient. &amp;nbsp;To specify a specific directory &amp;nbsp;include the absolute or relative path. &amp;nbsp;To specify the current working directory, e.g. bin\debug then just use ".\".&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Example 2 - Using DbContext (doesn't work)&lt;/b&gt;&lt;br /&gt;
&lt;pre style="background-image: URL(http://2.bp.blogspot.com/_z5ltvMQPaa8/SjJXr_U2YBI/AAAAAAAAAAM/46OqEP32CJ8/s320/codebg.gif); background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"&gt;&lt;code style="color: black; word-wrap: normal;"&gt;1:  using (var ctx = new DbContext("test2.sdf"))  
2:  {  
3:    ctx.Database.Create();  
4:  }  
&lt;/code&gt;&lt;/pre&gt;
&lt;br /&gt;
This code appears to work but doesn't create an instance of an SQL CE dB as desired. &amp;nbsp;Instead it creates a &lt;a href="http://blogs.msdn.com/b/sqlexpress/archive/2011/07/12/introducing-localdb-a-better-sql-express.aspx"&gt;localDB&lt;/a&gt; instance in the user's home directory. &amp;nbsp;In my case: C:\Users\Pete\._test.sdf.mdf (&amp;amp; corresponding log file). &amp;nbsp;This is not really surprising as Entity Framework had no way of knowing that a SQL CE dB should be created.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Example 3 - Using DbContext (does work)&lt;/b&gt;&lt;br /&gt;
&lt;pre style="background-image: URL(http://2.bp.blogspot.com/_z5ltvMQPaa8/SjJXr_U2YBI/AAAAAAAAAAM/46OqEP32CJ8/s320/codebg.gif); background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"&gt;&lt;code style="color: black; word-wrap: normal;"&gt;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:  }  
&lt;/code&gt;&lt;/pre&gt;
&lt;br /&gt;
The difference between the last and this example is changing the default type of dB that EF should create. &amp;nbsp;As shown this is done by installing a different factory.&lt;br /&gt;
&lt;br /&gt;
The 3rd parameter to SqlCeConnectionFactory is the directory that the dB should be created in. &amp;nbsp;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.&lt;br /&gt;
&lt;br /&gt;
&lt;i&gt;NOTE: As per the post &lt;a href="http://petebarber.blogspot.co.uk/2012/08/integration-testing-with-nunit-and.html"&gt;Integration Testing with NUnit and Entity Framework&lt;/a&gt;&amp;nbsp;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.&lt;/i&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;i&gt;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.&lt;/i&gt;&lt;br /&gt;
&lt;i&gt;&lt;br /&gt;&lt;/i&gt;&lt;br /&gt;
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. &amp;nbsp;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. &amp;nbsp;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.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Example 4 - Using DbContext and the .config file&lt;/b&gt;&lt;br /&gt;
&lt;pre style="background-image: URL(http://2.bp.blogspot.com/_z5ltvMQPaa8/SjJXr_U2YBI/AAAAAAAAAAM/46OqEP32CJ8/s320/codebg.gif); background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"&gt;&lt;code style="color: black; word-wrap: normal;"&gt;1:  using (var ctx = new DbContext("test5"))  
2:  {  
3:    ctx.Database.Create();  
4:  }  
&lt;/code&gt;&lt;/pre&gt;
&lt;br /&gt;
App or Web .config
&lt;br /&gt;
&lt;pre style="background-image: URL(http://2.bp.blogspot.com/_z5ltvMQPaa8/SjJXr_U2YBI/AAAAAAAAAAM/46OqEP32CJ8/s320/codebg.gif); background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"&gt;&lt;code style="color: black; word-wrap: normal;"&gt;1:  &amp;lt;connectionStrings&amp;gt;  
2:    &amp;lt;add name="test5"  
3:      providerName="System.Data.SqlServerCe.4.0"  
4:      connectionString="Data Source=test5.sdf"/&amp;gt;  
5:  &amp;lt;/connectionStrings&amp;gt;  
&lt;/code&gt;&lt;/pre&gt;
&lt;br /&gt;
This time no factory is specified but the argument to DbContext is the name of a Connection String in the .config file. &amp;nbsp;As can be seen this contains similar information to that in the factory method enabling EF to create a dB of the correct type.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Example 5 - Using a derived context and .config file&lt;/b&gt;&lt;br /&gt;
&lt;pre style="background-image: URL(http://2.bp.blogspot.com/_z5ltvMQPaa8/SjJXr_U2YBI/AAAAAAAAAAM/46OqEP32CJ8/s320/codebg.gif); background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"&gt;&lt;code style="color: black; word-wrap: normal;"&gt;1:  public class TestCtx : DbContext  
2:  {      
3:  }  
4:  using (var ctx = new TestCtx())  
5:  {  
6:    ctx.Database.Create();  
7:  }    
&lt;/code&gt;&lt;/pre&gt;
&lt;br /&gt;
App or Web .config&lt;br /&gt;
&lt;pre style="background-image: URL(http://2.bp.blogspot.com/_z5ltvMQPaa8/SjJXr_U2YBI/AAAAAAAAAAM/46OqEP32CJ8/s320/codebg.gif); background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"&gt;&lt;code style="color: black; word-wrap: normal;"&gt;1:  &amp;lt;connectionStrings&amp;gt;  
2:    &amp;lt;add name="TestCtx"  
3:      providerName="System.Data.SqlServerCe.4.0"  
4:      connectionString="Data Source=test6.sdf"/&amp;gt;  
5:  &amp;lt;/connectionStrings&amp;gt;  
&lt;/code&gt;&lt;/pre&gt;
&lt;br /&gt;
If a derived context is created which will almost&amp;nbsp;certainly&amp;nbsp;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.&lt;img src="http://feeds.feedburner.com/~r/CCWindowsOtherRamblings/~4/Sb5ohZr9xsc" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/CCWindowsOtherRamblings/~3/Sb5ohZr9xsc/specifying-directory-to-create-sql-ce.html</link><author>noreply@blogger.com (Pete Barber)</author><thr:total>0</thr:total><feedburner:origLink>http://petebarber.blogspot.com/2012/08/specifying-directory-to-create-sql-ce.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-2918646278142295649.post-697138137308648689</guid><pubDate>Thu, 02 Aug 2012 14:10:00 +0000</pubDate><atom:updated>2012-08-03T02:17:36.490-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">DbContext SQLServerCE C# NUnit SqlCeConnectionFactory</category><category domain="http://www.blogger.com/atom/ns#">Code First</category><category domain="http://www.blogger.com/atom/ns#">EF</category><category domain="http://www.blogger.com/atom/ns#">Intergration Test</category><category domain="http://www.blogger.com/atom/ns#">Pattern</category><category domain="http://www.blogger.com/atom/ns#">Unit Test</category><category domain="http://www.blogger.com/atom/ns#">CodeProject</category><category domain="http://www.blogger.com/atom/ns#">Entity Framework</category><category domain="http://www.blogger.com/atom/ns#">DbContext</category><category domain="http://www.blogger.com/atom/ns#">Unit of work</category><title>Integration Testing with NUnit and Entity Framework</title><description>This post gives a quick introduction into creating SQL CE dBs for performing Integration Tests using NUnit.&lt;br /&gt;
&lt;br /&gt;
In the previous post&amp;nbsp;&lt;span style="background-color: white;"&gt;&lt;a href="http://petebarber.blogspot.co.uk/2012/04/using-nunit-and-entity-framework.html"&gt;Using NUnit and Entity Framework DbContext to programmatically create SQL Server CE databases and specify the databse directory&lt;/a&gt;&lt;/span&gt;&lt;span style="background-color: white;"&gt;&amp;nbsp;a basic way was shown to how to create a new dB (using Entity Framework's DbContext) programmtically. &amp;nbsp;This was used to generate a new dB for a test hosted by NUnit.&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
The subsequent post&amp;nbsp;&lt;span style="background-color: white;"&gt;&lt;a href="http://petebarber.blogspot.co.uk/2012/06/generating-sql-server-ce-database.html"&gt;Generating a SQL Server CE database schema from a SQL Server database using Entity Framework&lt;/a&gt;&lt;/span&gt;&lt;span style="background-color: white;"&gt;&amp;nbsp;showed how to generate a SQL CE dB schema from an existing SQL Server database.&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
This post ties theprevious ones together. &amp;nbsp;As mentioned in the first post the reason for this is an attempt at what amounts to Integration Testing using NUnit. &amp;nbsp;I'm currently building a &lt;a href="http://martinfowler.com/eaaCatalog/repository.html"&gt;Repository&lt;/a&gt; and &lt;a href="http://martinfowler.com/eaaCatalog/unitOfWork.html"&gt;Unit Of Work&lt;/a&gt; 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). &amp;nbsp;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. &amp;nbsp;The Integration Testing is to verify that the Repository and Unit Of Work implementations work correctly.&lt;br /&gt;
&lt;br /&gt;
The rest of the post isn't focused on these two patterns; though it may mention them. &amp;nbsp;Instead it documents my further experience of using NUnit to writes tests that interact with dB via Entity Framework. &amp;nbsp;The premise for this is that a dB already exists.&lt;br /&gt;
&lt;br /&gt;
&lt;span style="background-color: white;"&gt;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. &amp;nbsp;This is possible as the POCOs can be defined, a connection made to dB and then the two are conflated via an EF DbContext. &amp;nbsp;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!&lt;br /&gt;&lt;span style="background-color: white;"&gt;&lt;br /&gt;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. &amp;nbsp;In order to keep the test dBs isolated from the real dB SQL Server Compact Edition (SQL Server CE V4) was used. &amp;nbsp;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. &amp;nbsp;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. &amp;nbsp;However, the process described in the post&amp;nbsp;&lt;/span&gt;&lt;a href="http://petebarber.blogspot.co.uk/2012/06/generating-sql-server-ce-database.html" style="background-color: transparent;"&gt;Generating a SQL Server CE database schema from a SQL Server database using Entity Framework&lt;/a&gt;&lt;span style="background-color: transparent;"&gt;&amp;nbsp;showed how to create semantically equivalent SQL.&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
From this point onwards it's assumed that an SQL file to create the dB has been generated. &amp;nbsp;Now&amp;nbsp;&lt;span style="background-color: white;"&gt;create a new C# class library project and using the NUGet add Entity Framework, NUnit and SQL CE 4.0. &amp;nbsp;All my work has been with EF 4.3.1. &amp;nbsp;Following this drag the Model1.edmx.sqlce file from the project used to generate to new project. &amp;nbsp;You may wish to rename it, e.g. to test.sqlce.&lt;/span&gt;&lt;br /&gt;
&lt;h3&gt;
&lt;span style="background-color: white;"&gt;&lt;br /&gt;&lt;/span&gt;&lt;/h3&gt;
&lt;h3&gt;
&lt;span style="background-color: white;"&gt;Creating the database&lt;/span&gt;&lt;/h3&gt;
&lt;span style="background-color: white;"&gt;The post&amp;nbsp;&lt;/span&gt;&lt;a href="http://petebarber.blogspot.co.uk/2012/06/generating-sql-server-ce-database.html"&gt;Generating a SQL Server CE database schema from a SQL Server database using Entity Framework&lt;/a&gt;&amp;nbsp;showed how to create a new CE dB per-test using the EF DbContext to do the hard work. &amp;nbsp;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&amp;nbsp;indices&amp;nbsp;etc. it also creates an additional table called '__MigrationHistory' which contains a description of the EF model used to create the dB. &amp;nbsp;The description of the problem caused by this will be delayed until the "Why DbContext is no longer used to create the database" section. &amp;nbsp;Suffice to say for the present using the new mechanism avoids the creation of this table.&lt;br /&gt;
&lt;br /&gt;
The code below is the beginnings of a test class. &amp;nbsp;It is assumed all the tests need a fresh copy of the dB hence the creation is performed in the Setup method. &amp;nbsp;All this code does is create a SQL CE dB and then&lt;br /&gt;
creates the schema.&lt;br /&gt;
&lt;br /&gt;
&lt;pre style="background-image: URL(http://2.bp.blogspot.com/_z5ltvMQPaa8/SjJXr_U2YBI/AAAAAAAAAAM/46OqEP32CJ8/s320/codebg.gif); background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"&gt;&lt;code style="color: black; word-wrap: normal;"&gt;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:    
&lt;/code&gt;&lt;/pre&gt;
&lt;div&gt;
The dB file (Test.sdf) will be created in the current working directory. &amp;nbsp;As the test&amp;nbsp;assembly&amp;nbsp;is located in &amp;lt;project&amp;gt;\bin\debug which is where the NUnit test runner picks up the DLL from this directory this is where it is created. &amp;nbsp;If a specific directory is required then the '.\' can be replaced with the required path.&lt;br /&gt;
&lt;br /&gt;
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. &amp;nbsp;The DeleteDb method could be marked with [TearDown] attribute but at the moment any previous dB is deleted before creating a new one. &amp;nbsp;It would be fine to do both as a belt and braces approach. &amp;nbsp;The reason I didn't make it the TearDown method is so that I could inspect the dB following a test if needed.&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
SQL CE does not support batch execution of SQL scripts which is where it gets interesting as the SQL generated&amp;nbsp;&lt;a href="http://petebarber.blogspot.co.uk/2012/06/generating-sql-server-ce-database.html"&gt;previously&lt;/a&gt;&amp;nbsp;is in batch form. &amp;nbsp;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.&lt;br /&gt;
&lt;br /&gt;
&lt;span style="background-color: white;"&gt;To help understand the SQL the following is the diagram of the dB I'm working with. &amp;nbsp;All fields are strings except for the Ids which are numeric.&lt;/span&gt;&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;
&lt;a href="http://4.bp.blogspot.com/-EaXPH3KrEoo/UBZhXIMhNFI/AAAAAAAAAhc/GmqFEZp8zeA/s1600/model.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" src="http://4.bp.blogspot.com/-EaXPH3KrEoo/UBZhXIMhNFI/AAAAAAAAAhc/GmqFEZp8zeA/s1600/model.png" /&gt;&lt;/a&gt;&lt;/div&gt;
Each of these commands is then executed. &amp;nbsp;The &lt;a href="http://petebarber.blogspot.co.uk/2012/06/generating-sql-server-ce-database.html"&gt;previously&lt;/a&gt;&amp;nbsp;generated&amp;nbsp;&lt;span style="background-color: white;"&gt;SQL&amp;nbsp;&lt;/span&gt;&lt;span style="background-color: white;"&gt;(the SQL for the dB I'm working with is below) will not work completely out of the box. &amp;nbsp;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. &amp;nbsp;Interestingly the schema generation step for my dB seems to miss out a 'GO' between the penultimate and ultimate&amp;nbsp;statement. &amp;nbsp;I had to add one by hand. &amp;nbsp;Finally, the comments at the end prove a problem as there is no terminating 'GO'. &amp;nbsp;Removing these fixes the problem. &amp;nbsp;In the code above the exception handler re-throws the exception after writing out the details. &amp;nbsp;For everything to proceed the SQL needs modifying to execute perfectly. &amp;nbsp;If the re-throw is removed then the code will tolerate&amp;nbsp;individual&amp;nbsp;command failures which in this context really just amount to warnings.&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;span style="background-color: white;"&gt;&lt;i&gt;NOTE: Text highlighted in &lt;span style="color: red;"&gt;red&lt;/span&gt;&amp;nbsp;has been removed and text in &lt;span style="color: blue;"&gt;blue&lt;/span&gt; added.&lt;/i&gt;&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="color: red; font-family: Courier New, Courier, monospace;"&gt;-- --------------------------------------------------&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="color: red; font-family: Courier New, Courier, monospace;"&gt;-- Entity Designer DDL Script for SQL Server Compact Edition&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="color: red; font-family: Courier New, Courier, monospace;"&gt;-- --------------------------------------------------&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="color: red; font-family: Courier New, Courier, monospace;"&gt;-- Date Created: 07/29/2012 12:28:35&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="color: red; font-family: Courier New, Courier, monospace;"&gt;-- Generated from EDMX file: C:\Users\Pete\work\Jub\DummyWebApplicationToGenerateSQLServerCE4Script\Model1.edmx&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="color: red; font-family: Courier New, Courier, monospace;"&gt;-- --------------------------------------------------&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="color: red; font-family: Courier New, Courier, monospace;"&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="color: red; font-family: Courier New, Courier, monospace;"&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="color: red; font-family: Courier New, Courier, monospace;"&gt;-- --------------------------------------------------&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="color: red; font-family: Courier New, Courier, monospace;"&gt;-- Dropping existing FOREIGN KEY constraints&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="color: red; font-family: Courier New, Courier, monospace;"&gt;-- NOTE: if the constraint does not exist, an ignorable error will be reported.&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="color: red; font-family: Courier New, Courier, monospace;"&gt;-- --------------------------------------------------&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="color: red; font-family: Courier New, Courier, monospace;"&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="color: red; font-family: Courier New, Courier, monospace;"&gt;&amp;nbsp; &amp;nbsp; ALTER TABLE [RepComments] DROP CONSTRAINT [FK_RepComments_Reps];&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="color: red; font-family: Courier New, Courier, monospace;"&gt;GO&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="color: red; font-family: Courier New, Courier, monospace;"&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="color: red; font-family: Courier New, Courier, monospace;"&gt;-- --------------------------------------------------&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="color: red; font-family: Courier New, Courier, monospace;"&gt;-- Dropping existing tables&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="color: red; font-family: Courier New, Courier, monospace;"&gt;-- NOTE: if the table does not exist, an ignorable error will be reported.&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="color: red; font-family: Courier New, Courier, monospace;"&gt;-- --------------------------------------------------&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="color: red; font-family: Courier New, Courier, monospace;"&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="color: red; font-family: Courier New, Courier, monospace;"&gt;&amp;nbsp; &amp;nbsp; DROP TABLE [RepComments];&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="color: red; font-family: Courier New, Courier, monospace;"&gt;GO&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="color: red; font-family: Courier New, Courier, monospace;"&gt;&amp;nbsp; &amp;nbsp; DROP TABLE [Reps];&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="color: red; font-family: Courier New, Courier, monospace;"&gt;GO&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="color: red; font-family: Courier New, Courier, monospace;"&gt;&amp;nbsp; &amp;nbsp; DROP TABLE [Roads];&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="color: red; font-family: Courier New, Courier, monospace;"&gt;GO&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="color: red; font-family: Courier New, Courier, monospace;"&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="color: red; font-family: Courier New, Courier, monospace;"&gt;-- --------------------------------------------------&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="color: red; font-family: Courier New, Courier, monospace;"&gt;-- Creating all tables&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="color: red; font-family: Courier New, Courier, monospace;"&gt;-- --------------------------------------------------&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="color: red; font-family: Courier New, Courier, monospace;"&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="color: red; font-family: Courier New, Courier, monospace;"&gt;-- Creating table 'RepComments'&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="font-family: Courier New, Courier, monospace;"&gt;CREATE TABLE [RepComments] (&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="font-family: Courier New, Courier, monospace;"&gt;&amp;nbsp; &amp;nbsp; [CommentId] int IDENTITY(1,1) NOT NULL,&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="font-family: Courier New, Courier, monospace;"&gt;&amp;nbsp; &amp;nbsp; [RepId] int &amp;nbsp;NOT NULL,&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="font-family: Courier New, Courier, monospace;"&gt;&amp;nbsp; &amp;nbsp; [Comment] ntext &amp;nbsp;NOT NULL&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="font-family: Courier New, Courier, monospace;"&gt;);&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="font-family: Courier New, Courier, monospace;"&gt;GO&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="font-family: Courier New, Courier, monospace;"&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="font-family: Courier New, Courier, monospace;"&gt;-- Creating table 'Reps'&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="font-family: Courier New, Courier, monospace;"&gt;CREATE TABLE [Reps] (&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="font-family: Courier New, Courier, monospace;"&gt;&amp;nbsp; &amp;nbsp; [RepId] int IDENTITY(1,1) NOT NULL,&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="font-family: Courier New, Courier, monospace;"&gt;&amp;nbsp; &amp;nbsp; [RepName] nvarchar(50) &amp;nbsp;NOT NULL,&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="font-family: Courier New, Courier, monospace;"&gt;&amp;nbsp; &amp;nbsp; [RoadName] nvarchar(256) &amp;nbsp;NOT NULL,&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="font-family: Courier New, Courier, monospace;"&gt;&amp;nbsp; &amp;nbsp; [HouseNumberOrName] nvarchar(50) &amp;nbsp;NOT NULL,&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="font-family: Courier New, Courier, monospace;"&gt;&amp;nbsp; &amp;nbsp; [ContactTelNumber] nvarchar(20) &amp;nbsp;NOT NULL,&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="font-family: Courier New, Courier, monospace;"&gt;&amp;nbsp; &amp;nbsp; [Email] nvarchar(50) &amp;nbsp;NULL&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="font-family: Courier New, Courier, monospace;"&gt;);&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="font-family: Courier New, Courier, monospace;"&gt;GO&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="font-family: Courier New, Courier, monospace;"&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="font-family: Courier New, Courier, monospace;"&gt;-- Creating table 'Roads'&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="font-family: Courier New, Courier, monospace;"&gt;CREATE TABLE [Roads] (&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="font-family: Courier New, Courier, monospace;"&gt;&amp;nbsp; &amp;nbsp; [Name] nvarchar(256) &amp;nbsp;NOT NULL&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="font-family: Courier New, Courier, monospace;"&gt;);&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="font-family: Courier New, Courier, monospace;"&gt;GO&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="font-family: Courier New, Courier, monospace;"&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="font-family: Courier New, Courier, monospace;"&gt;-- --------------------------------------------------&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="font-family: Courier New, Courier, monospace;"&gt;-- Creating all PRIMARY KEY constraints&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="font-family: Courier New, Courier, monospace;"&gt;-- --------------------------------------------------&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="font-family: Courier New, Courier, monospace;"&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="font-family: Courier New, Courier, monospace;"&gt;-- Creating primary key on [CommentId] in table 'RepComments'&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="font-family: Courier New, Courier, monospace;"&gt;ALTER TABLE [RepComments]&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="font-family: Courier New, Courier, monospace;"&gt;ADD CONSTRAINT [PK_RepComments]&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="font-family: Courier New, Courier, monospace;"&gt;&amp;nbsp; &amp;nbsp; PRIMARY KEY ([CommentId] );&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="font-family: Courier New, Courier, monospace;"&gt;GO&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="font-family: Courier New, Courier, monospace;"&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="font-family: Courier New, Courier, monospace;"&gt;-- Creating primary key on [RepId] in table 'Reps'&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="font-family: Courier New, Courier, monospace;"&gt;ALTER TABLE [Reps]&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="font-family: Courier New, Courier, monospace;"&gt;ADD CONSTRAINT [PK_Reps]&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="font-family: Courier New, Courier, monospace;"&gt;&amp;nbsp; &amp;nbsp; PRIMARY KEY ([RepId] );&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="font-family: Courier New, Courier, monospace;"&gt;GO&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="font-family: Courier New, Courier, monospace;"&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="font-family: Courier New, Courier, monospace;"&gt;-- Creating primary key on [Name] in table 'Roads'&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="font-family: Courier New, Courier, monospace;"&gt;ALTER TABLE [Roads]&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="font-family: Courier New, Courier, monospace;"&gt;ADD CONSTRAINT [PK_Roads]&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="font-family: Courier New, Courier, monospace;"&gt;&amp;nbsp; &amp;nbsp; PRIMARY KEY ([Name] );&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="font-family: Courier New, Courier, monospace;"&gt;GO&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="font-family: Courier New, Courier, monospace;"&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="font-family: Courier New, Courier, monospace;"&gt;-- --------------------------------------------------&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="font-family: Courier New, Courier, monospace;"&gt;-- Creating all FOREIGN KEY constraints&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="font-family: Courier New, Courier, monospace;"&gt;-- --------------------------------------------------&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="font-family: Courier New, Courier, monospace;"&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="font-family: Courier New, Courier, monospace;"&gt;-- Creating foreign key on [RepId] in table 'RepComments'&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="font-family: Courier New, Courier, monospace;"&gt;ALTER TABLE [RepComments]&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="font-family: Courier New, Courier, monospace;"&gt;ADD CONSTRAINT [FK_RepComments_Reps]&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="font-family: Courier New, Courier, monospace;"&gt;&amp;nbsp; &amp;nbsp; FOREIGN KEY ([RepId])&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="font-family: Courier New, Courier, monospace;"&gt;&amp;nbsp; &amp;nbsp; REFERENCES [Reps]&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="font-family: Courier New, Courier, monospace;"&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; ([RepId])&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="font-family: Courier New, Courier, monospace;"&gt;&amp;nbsp; &amp;nbsp; ON DELETE NO ACTION ON UPDATE NO ACTION;&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="color: blue; font-family: Courier New, Courier, monospace;"&gt;GO&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="font-family: Courier New, Courier, monospace;"&gt;-- Creating non-clustered index for FOREIGN KEY 'FK_RepComments_Reps'&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="font-family: Courier New, Courier, monospace;"&gt;CREATE INDEX [IX_FK_RepComments_Reps]&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="font-family: Courier New, Courier, monospace;"&gt;ON [RepComments]&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="font-family: Courier New, Courier, monospace;"&gt;&amp;nbsp; &amp;nbsp; ([RepId]);&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="font-family: Courier New, Courier, monospace;"&gt;GO&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="color: red; font-family: Courier New, Courier, monospace;"&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="color: red; font-family: Courier New, Courier, monospace;"&gt;-- --------------------------------------------------&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="color: red; font-family: Courier New, Courier, monospace;"&gt;-- Script has ended&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style="color: red; font-family: Courier New, Courier, monospace;"&gt;-- --------------------------------------------------&lt;/span&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;
&lt;span style="color: red;"&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
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. &amp;nbsp;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.&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;
&lt;a href="http://2.bp.blogspot.com/-dSxTS7PEH7U/UBZfcL_JyfI/AAAAAAAAAhU/3-ho8IYDEw0/s1600/ServerExplorer.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" src="http://2.bp.blogspot.com/-dSxTS7PEH7U/UBZfcL_JyfI/AAAAAAAAAhU/3-ho8IYDEw0/s1600/ServerExplorer.png" /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;h3&gt;
Using the dB in a test&lt;/h3&gt;
&lt;div&gt;
Now that a fresh dB will be created for each test it's time to look at simple test:&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;br /&gt;
&lt;pre style="background-image: URL(http://2.bp.blogspot.com/_z5ltvMQPaa8/SjJXr_U2YBI/AAAAAAAAAAM/46OqEP32CJ8/s320/codebg.gif); background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"&gt;&lt;code style="color: black; word-wrap: normal;"&gt;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:  }  
&lt;/code&gt;&lt;/pre&gt;
&lt;div&gt;
Road in this case is defined as:&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;pre style="background-image: URL(http://2.bp.blogspot.com/_z5ltvMQPaa8/SjJXr_U2YBI/AAAAAAAAAAM/46OqEP32CJ8/s320/codebg.gif); background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"&gt;&lt;code style="color: black; word-wrap: normal;"&gt;1:  class Road  
2:  {  
3:   [Key]  
4:   public string Name { get; set; }  
5:  }  
&lt;/code&gt;&lt;/pre&gt;
&lt;br /&gt;
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. &amp;nbsp;Attempting to get EF to connect to a specific dB instance when &lt;i&gt;not&lt;/i&gt; referring to a named &lt;a href="http://blogs.msdn.com/b/adonet/archive/2011/01/27/using-dbcontext-in-ef-feature-ctp5-part-2-connections-and-models.aspx"&gt;connection strings&lt;/a&gt; in the .config file is a bit of an art (I may write another entry about this). &amp;nbsp;However, EF is quite happy to work with an existing connection. &amp;nbsp;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.&lt;br /&gt;
&lt;br /&gt;
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. &amp;nbsp;TestCtx could also be modified to pass true to the &lt;a href="http://msdn.microsoft.com/en-us/library/gg696604(v=vs.103).aspx"&gt;DbContext &lt;/a&gt;constructor to give ownership of the connection to the context so that it will dispose of it then context is disposed off.&lt;br /&gt;
&lt;br /&gt;
I would have preferred to avoid having to defined a specific derived context and instead use DbContext directory, e.g.&lt;br /&gt;
&lt;pre style="background-image: URL(http://2.bp.blogspot.com/_z5ltvMQPaa8/SjJXr_U2YBI/AAAAAAAAAAM/46OqEP32CJ8/s320/codebg.gif); background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"&gt;&lt;code style="color: black; word-wrap: normal;"&gt;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&amp;lt;Road&amp;gt;().Add(new Road() { Name = "Test" });  
8:     ctx.SaveChanges();  
9:     Assert.That(1, Is.EqualTo(ctx.Set&amp;lt;Road&amp;gt;().Count()));  
10:    }  
11:  }  
&lt;/code&gt;&lt;/pre&gt;
&lt;br /&gt;
However when SaveChanges() is called the following exception is thrown:&lt;br /&gt;
&lt;br /&gt;
&lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;System.InvalidOperationException : The entity type Road is not part of the model for the current context.&lt;/span&gt;&lt;br /&gt;
&lt;span style="font-family: Courier New, Courier, monospace;"&gt;&lt;br /&gt;&lt;/span&gt;This is because EF knows nothing about the Road type. &amp;nbsp;When a derived context is created for the first time I think EF performs reflection on any properties that expose DbSet. &amp;nbsp;These are the types that form the Model. &amp;nbsp;Another option is to &lt;a href="http://blog.oneunicorn.com/2012/04/21/code-first-building-blocks/"&gt;create the model, optionally compile it and then pass it to an instance of DbContext&lt;/a&gt;. &amp;nbsp;This way involves a lot less code.&lt;br /&gt;
&lt;br /&gt;
That's it. &amp;nbsp;The final section is just footnote about the move away from using EF to create the dB.&lt;br /&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;h3&gt;
&lt;span style="background-color: white;"&gt;Why DbContext is no longer used to create the database&lt;/span&gt;&lt;/h3&gt;
&lt;div&gt;
&lt;span style="background-color: white;"&gt;As mentioned creating the dB using:&lt;/span&gt;&lt;/div&gt;
&lt;pre style="background-image: URL(http://2.bp.blogspot.com/_z5ltvMQPaa8/SjJXr_U2YBI/AAAAAAAAAAM/46OqEP32CJ8/s320/codebg.gif); background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"&gt;&lt;code style="color: black; word-wrap: normal;"&gt;1:  using (var ctx = new DbContext("bar.sdf"))  
2:  {  
3:   ctx.Database.Create();  
4:   // create schema etc.  
5:  }  
&lt;/code&gt;&lt;/pre&gt;
causes the&amp;nbsp;'__MigrationHistory'&amp;nbsp;table to be created. &amp;nbsp;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:&lt;br /&gt;
&lt;br /&gt;
&lt;i&gt;&lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;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)&lt;/span&gt;.&lt;/i&gt;&lt;br /&gt;
&lt;span style="background-color: white;"&gt;This is&amp;nbsp;because&amp;nbsp;the context used to create the model was a raw DbContext (as per the previous post) whereas the dB was accessed via the TestCtx. &amp;nbsp;If the context used to create the dB is also changed to TestCtx then this problem goes away.&lt;/span&gt;&lt;br /&gt;
&lt;span style="background-color: white;"&gt;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.&lt;/span&gt;&lt;br /&gt;
&lt;span style="background-color: white;"&gt;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/CCWindowsOtherRamblings/~4/FAVqjOHz1zQ" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/CCWindowsOtherRamblings/~3/FAVqjOHz1zQ/integration-testing-with-nunit-and.html</link><author>noreply@blogger.com (Pete Barber)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://4.bp.blogspot.com/-EaXPH3KrEoo/UBZhXIMhNFI/AAAAAAAAAhc/GmqFEZp8zeA/s72-c/model.png" height="72" width="72" /><thr:total>1</thr:total><feedburner:origLink>http://petebarber.blogspot.com/2012/08/integration-testing-with-nunit-and.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-2918646278142295649.post-8418417459879136107</guid><pubDate>Wed, 27 Jun 2012 17:40:00 +0000</pubDate><atom:updated>2012-06-27T10:43:50.728-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">DbContext SQLServerCE C# NUnit CodeProject SqlCeConnectionFactory databaseDirectory</category><category domain="http://www.blogger.com/atom/ns#">Entity Framework</category><title>Generating a SQL Server CE database schema from a SQL Server database using Entity Framework</title><description>In a &lt;a href="http://petebarber.blogspot.co.uk/2012/04/using-nunit-and-entity-framework.html"&gt;previous entry&lt;/a&gt; I described how to programmatically create (&amp;amp; destroy) a SQL CE dB for integration testing using NUnit. &amp;nbsp;Since getting that working I ran into a couple of other problems which I've more or less solved so I thought I'd write those up. &amp;nbsp;To begin with though this is a prequel post describing how to obtain the SQL script to create the SQL CE dB.&lt;br /&gt;
&lt;br /&gt;
If you happen to be working exclusively with CE then you'll already have your schema file. &amp;nbsp;In my case I'm using SQLExpress and as this is experimental work I created my dB by hand. &amp;nbsp;However, using the EF it's pretty easy to obtain the schema and have the EF wizard generate the CE schema. &amp;nbsp;This is important as there are differences in the dialect of SQL used by SQL Express and SQL CE and its easier to have a tool handle those, though it doesn't do all of them.&lt;br /&gt;
&lt;br /&gt;
The basic flow is to generate an EF model (EDMX) file from the existing SQL Express database and then use the 'Generate database from model' functionality. &amp;nbsp;It is at this point that the target SQL dB can be chosen, i.e. SQL Server, SQL Server CE or some others.&lt;br /&gt;
&lt;br /&gt;
To create a model requires adding a 'New Item' of type 'ADO.Net Entity Data Model' to a VS project so first a new dummy project needs creating. &amp;nbsp;This is where it gets a little complicated as not any type of project will do. &amp;nbsp;I'm working with CE 4 and require a schema for that version of the dB (though creating one for 3.5 works but I like to things as close to ideal as possible). &amp;nbsp;Due to this constraint it is necessary to chose a Web type project as for some reason the VS2010 integration provided by EF only supports the generation of CE 4 dBs for Web projects. &amp;nbsp;If a simple C# Windows Console project is selected then you're limited to CE 3.5. &amp;nbsp;Thus the simplest project type is the 'ASP.Net Empty Web Application' as shown below.&lt;br /&gt;
&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;
&lt;/div&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;
&lt;a href="http://4.bp.blogspot.com/-NLSwfYEd9II/T6GVUmS4dxI/AAAAAAAAAeg/KnRngm9MeXE/s1600/Add+New+Project.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="442" src="http://4.bp.blogspot.com/-NLSwfYEd9II/T6GVUmS4dxI/AAAAAAAAAeg/KnRngm9MeXE/s640/Add+New+Project.png" width="640" /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
Having done this, next add a new item of type ADO.Net Entity Data Model as below. NOTE: The project will have to reference the Entity Framework assemblies. &amp;nbsp;The easiest way to do this (&amp;amp; the one most people are probably using) is to use the &lt;a href="http://nuget.org/"&gt;NuGet&lt;/a&gt; package.&lt;br /&gt;
&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;
&lt;a href="http://3.bp.blogspot.com/-7xCZrFDlnvY/T-nQi2EpEII/AAAAAAAAAes/Lw72uuThKiQ/s1600/NewItem.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="442" src="http://3.bp.blogspot.com/-7xCZrFDlnvY/T-nQi2EpEII/AAAAAAAAAes/Lw72uuThKiQ/s640/NewItem.png" width="640" /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
Then follow the wizard.&lt;br /&gt;
&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;
&lt;a href="http://4.bp.blogspot.com/-nh-PeMOXUHU/T-nRD_A6GEI/AAAAAAAAAe0/w6Ad9irVaZE/s1600/EDMWiz1.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="526" src="http://4.bp.blogspot.com/-nh-PeMOXUHU/T-nRD_A6GEI/AAAAAAAAAe0/w6Ad9irVaZE/s640/EDMWiz1.png" width="640" /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
&lt;span style="background-color: white;"&gt;Selecting "Generate from database".&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;
&lt;a href="http://2.bp.blogspot.com/-LNAAY_P2AFE/T-nRTfiJeCI/AAAAAAAAAe8/cpviegRKi6Y/s1600/EDMWiz2.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="526" src="http://2.bp.blogspot.com/-LNAAY_P2AFE/T-nRTfiJeCI/AAAAAAAAAe8/cpviegRKi6Y/s640/EDMWiz2.png" width="640" /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
Choose your SQLExpress (or SQL Server) dB but uncheck the "Save entity connection settings in Web.Config as:" as we're converting to SQLCE so want to minimize anything related to other types of SQL Server.&lt;br /&gt;
&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;
&lt;a href="http://3.bp.blogspot.com/-2kZp0hBGzBI/T-nR9Z59oAI/AAAAAAAAAfE/rLTfW5IP1yY/s1600/EDMWiz3.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="526" src="http://3.bp.blogspot.com/-2kZp0hBGzBI/T-nR9Z59oAI/AAAAAAAAAfE/rLTfW5IP1yY/s640/EDMWiz3.png" width="640" /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
Finally select the SQL elements you require. &amp;nbsp;In this example only the existing tables were selected. &amp;nbsp;As this is generating the EF model from an existing database no SQL file is generated just the model for which the diagram is shown, i.e.&lt;br /&gt;
&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;
&lt;a href="http://1.bp.blogspot.com/-cqsCzWO0hK4/T-nSi1Qtz2I/AAAAAAAAAfM/MJbnrwmYiF8/s1600/model.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="640" src="http://1.bp.blogspot.com/-cqsCzWO0hK4/T-nSi1Qtz2I/AAAAAAAAAfM/MJbnrwmYiF8/s640/model.png" width="604" /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
The next phase is to generate the SQL from the model (which was generated from the hand crafted db) but to make sure the SQL that's generated is compliant with SQL CE.&lt;br /&gt;
&lt;br /&gt;
To generate the schema right click and select "Generate model from database..."&lt;br /&gt;
&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;
&lt;a href="http://2.bp.blogspot.com/-3kwtbmcsQ8M/T-nTuljjSgI/AAAAAAAAAfU/xbym0jBJK5Q/s1600/genctx.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="320" src="http://2.bp.blogspot.com/-3kwtbmcsQ8M/T-nTuljjSgI/AAAAAAAAAfU/xbym0jBJK5Q/s320/genctx.png" width="310" /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
This brings up the "Generate database" wizard which is very&amp;nbsp;similar to the&amp;nbsp;previously&amp;nbsp;used&amp;nbsp;"Entity Data Model" wizard used to create the model. &amp;nbsp;From here choose the "New Connection" option which pops up another set of dialogs. &amp;nbsp;On the first choose the type of data source as "Microsoft SQL Server Compact 4.0".&lt;br /&gt;
&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;
&lt;a href="http://1.bp.blogspot.com/-m8KJxslysek/T-srbBM8x5I/AAAAAAAAAfw/Pnlygva6W84/s1600/foo1.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="322" src="http://1.bp.blogspot.com/-m8KJxslysek/T-srbBM8x5I/AAAAAAAAAfw/Pnlygva6W84/s640/foo1.png" width="640" /&gt;&lt;/a&gt;&lt;/div&gt;
Clicking on continue then leads to the next dialog where you need to create a dB.&lt;br /&gt;
&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;
&lt;a href="http://3.bp.blogspot.com/-G9hHA39eCqc/T-ssFR6kTUI/AAAAAAAAAf4/Zv_mRKnO4T4/s1600/foo2.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="500" src="http://3.bp.blogspot.com/-G9hHA39eCqc/T-ssFR6kTUI/AAAAAAAAAf4/Zv_mRKnO4T4/s640/foo2.png" width="640" /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
&lt;br /&gt;
Ok-ing this leads back to the "Generate database wizard".&lt;br /&gt;
&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;
&lt;a href="http://3.bp.blogspot.com/-IE1XXeBvRNI/T-ssViGlTdI/AAAAAAAAAgA/melB8bTi1pE/s1600/foo3.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="570" src="http://3.bp.blogspot.com/-IE1XXeBvRNI/T-ssViGlTdI/AAAAAAAAAgA/melB8bTi1pE/s640/foo3.png" width="640" /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
This time check the "Save entity connection settings in Web.Config" checkbox. &amp;nbsp;This information will be useful later (to be covered in a different post). &amp;nbsp;Clicking "Next" the SQL is generated and present in the wizard.&lt;br /&gt;
&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;
&lt;a href="http://4.bp.blogspot.com/-9a3wdzp-_Cc/T-svlLWuzDI/AAAAAAAAAgM/WN3iVlgBic8/s1600/foo4.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="570" src="http://4.bp.blogspot.com/-9a3wdzp-_Cc/T-svlLWuzDI/AAAAAAAAAgM/WN3iVlgBic8/s640/foo4.png" width="640" /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;
&lt;/div&gt;
This can be copied &amp;amp; pasted directly from here or pressing "Finish" will save the SQL to the file indicated at the top of the dialog box. &amp;nbsp;This file is added to the project. &amp;nbsp;The following prompt will appear when "Finish" is pressed.&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;
&lt;/div&gt;
&amp;nbsp;&lt;a href="http://4.bp.blogspot.com/-F7kCYV4wflY/T-s25saq5gI/AAAAAAAAAgg/WM2g661TtW8/s1600/foo5.png" imageanchor="1" style="background-color: white; margin-left: 1em; margin-right: 1em; text-align: center;"&gt;&lt;img border="0" height="192" src="http://4.bp.blogspot.com/-F7kCYV4wflY/T-s25saq5gI/AAAAAAAAAgg/WM2g661TtW8/s640/foo5.png" width="640" /&gt;&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;span style="background-color: white;"&gt;This doesn't really matter as this is a throw away project but having the updated schemas maybe useful so go with "Yes".&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
The SQL can now be used to configure an empty SQL CE 4.0 database. &amp;nbsp;The easiest way is to open the SQL file and right-click selecting the "Execute SQL" menu item.&lt;br /&gt;
&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;
&lt;a href="http://2.bp.blogspot.com/-ZERqTMcAPpY/T-s6wa-XhgI/AAAAAAAAAgs/rChYaYqDH0Q/s1600/foo6.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="640" src="http://2.bp.blogspot.com/-ZERqTMcAPpY/T-s6wa-XhgI/AAAAAAAAAgs/rChYaYqDH0Q/s640/foo6.png" width="588" /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
This brings up the SQL Server dialog from which if "New Database" is selected an CE 4 one can be specified.&lt;br /&gt;
&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;
&lt;a href="http://2.bp.blogspot.com/-nU9FMUfFYFI/T-s8BnNvL6I/AAAAAAAAAg0/Ok8v_zT8dwE/s1600/foo7.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="366" src="http://2.bp.blogspot.com/-nU9FMUfFYFI/T-s8BnNvL6I/AAAAAAAAAg0/Ok8v_zT8dwE/s640/foo7.png" width="640" /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
Having specified a location and pressed "Ok" the SQL script is executed. &amp;nbsp;As can be seen below this is not without errors. &amp;nbsp;However, this isn't anything to worry about as the errors are to do with dropping tables and&amp;nbsp;indices&amp;nbsp;that currently don't exist as it's a newly created dB. &amp;nbsp;&lt;i style="background-color: white;"&gt;Performing the same steps but missing out the creation of the dB file as it already exists sees the SQL script execute flawlessly.&lt;/i&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;
&lt;a href="http://3.bp.blogspot.com/-mmZTG3w3GFI/T-s8GYKxQGI/AAAAAAAAAg8/My3McjByUIU/s1600/foo8.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="640" src="http://3.bp.blogspot.com/-mmZTG3w3GFI/T-s8GYKxQGI/AAAAAAAAAg8/My3McjByUIU/s640/foo8.png" width="564" /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
&lt;br /&gt;
The final picture shows the newly created&amp;nbsp;database&amp;nbsp;in VS2010's Server Explorer demonstrating that the tables were indeed created.&lt;br /&gt;
&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;
&lt;a href="http://3.bp.blogspot.com/-72LZSSJzEsI/T-s8KbmWkQI/AAAAAAAAAhE/Kpd_LEQytSk/s1600/foo9.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" src="http://3.bp.blogspot.com/-72LZSSJzEsI/T-s8KbmWkQI/AAAAAAAAAhE/Kpd_LEQytSk/s1600/foo9.png" /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
The basis for this post is my experimentation on&amp;nbsp;using&amp;nbsp;NUnit to programmatically test some dB based functionality. &amp;nbsp;If a single instance of a database&amp;nbsp;suffices&amp;nbsp;for all your tests and you can execute the SQL by hand as above and then you can follow these steps. &amp;nbsp;In may case I want to a fresh database per test so I need to automate the running of the SQL Script combined the with the creation and destruction of the underlying database. &amp;nbsp;The creation and deletion aspect were covered in a previous &lt;a href="http://petebarber.blogspot.co.uk/2012/04/using-nunit-and-entity-framework.html"&gt;post&lt;/a&gt; but the next step will have to wait until a later one.&lt;br /&gt;
&lt;span id="goog_880058244"&gt;&lt;/span&gt;&lt;span id="goog_880058245"&gt;&lt;/span&gt;&lt;img src="http://feeds.feedburner.com/~r/CCWindowsOtherRamblings/~4/WzNIiw7-3SU" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/CCWindowsOtherRamblings/~3/WzNIiw7-3SU/generating-sql-server-ce-database.html</link><author>noreply@blogger.com (Pete Barber)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://4.bp.blogspot.com/-NLSwfYEd9II/T6GVUmS4dxI/AAAAAAAAAeg/KnRngm9MeXE/s72-c/Add+New+Project.png" height="72" width="72" /><thr:total>1</thr:total><feedburner:origLink>http://petebarber.blogspot.com/2012/06/generating-sql-server-ce-database.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-2918646278142295649.post-5572790205020806547</guid><pubDate>Thu, 03 May 2012 12:04:00 +0000</pubDate><atom:updated>2012-05-17T01:53:31.478-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Computer humour joke</category><title>More computing humor</title><description>A few more &lt;a href="http://petebarber.blogspot.co.uk/2011/08/couple-of-computing-jokes.html"&gt;computer/programming related jokes&lt;/a&gt;. &amp;nbsp;This time courtesy of the &lt;a href="http://accu.org/"&gt;ACCU &lt;/a&gt;&lt;a href="http://accu.org/index.php/mailinglists"&gt;general mailing list&lt;/a&gt;:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;ul&gt;
&lt;li&gt;I heard a good concurrency joke recently, about 10,000
threads. It was a bit contentious... (Ewan Milne)&lt;/li&gt;
&lt;/ul&gt;
&lt;ul&gt;
&lt;li&gt;A programmer walked into a Bar. &amp;nbsp;I say a Bar, it was actually a Foo. (Frances Buontempo)&lt;/li&gt;
&lt;/ul&gt;
&lt;ul&gt;
&lt;li&gt;Two programmers are sitting in a bar discussing static
and dynamic languages. The next day they get a visit from the RSPCA. When they
ask what it's concerning, the RSPCA man says "We got a tip off that you
were using ducks for typing". (&lt;a href="http://www.justsoftwaresolutions.co.uk/"&gt;Anthony Williams&lt;/a&gt;)&lt;/li&gt;
&lt;/ul&gt;
&lt;ul&gt;
&lt;li&gt;An SEO expert walks into a bar, bars, pub, public house, Irish pub, drinks, beer…. (Anders Knatten)&amp;nbsp;&lt;/li&gt;
&lt;li&gt;&lt;span style="-webkit-border-horizontal-spacing: 0px; -webkit-border-vertical-spacing: 0px; border-collapse: separate; font-family: Tahoma;"&gt;&lt;span style="color: #333333; font-family: HelveticaNeue, 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 14px; line-height: 18px;"&gt;Q: WHY DID THE HACKER GO TO THE BEACH? A: EASY ACCESS TO SHELLS (@yeahok)&lt;/span&gt;&lt;/span&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="MsoPlainText"&gt;
&lt;o:p&gt;&lt;/o:p&gt;&lt;/div&gt;
&lt;br /&gt;
&lt;o:p&gt;&lt;/o:p&gt;&lt;br /&gt;
&lt;div class="MsoPlainText"&gt;
&lt;br /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/CCWindowsOtherRamblings/~4/2wpHyhHo4DY" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/CCWindowsOtherRamblings/~3/2wpHyhHo4DY/more-computing-humor.html</link><author>noreply@blogger.com (Pete Barber)</author><thr:total>0</thr:total><feedburner:origLink>http://petebarber.blogspot.com/2012/05/more-computing-humor.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-2918646278142295649.post-107110117532970663</guid><pubDate>Mon, 16 Apr 2012 18:35:00 +0000</pubDate><atom:updated>2012-04-17T00:03:13.517-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">C++ Unit Testing templates SFINAE TMP sizeof "compilation failure" COM ATL STL CAdapt</category><title>Unit Testing when the success case is compilation failure (with C++)</title><description>There is an issue with the use of Window’s COM types being used with&amp;nbsp;STL containers in versions of Visual Studio prior to 2010. The crux&amp;nbsp;of the matter is that various COM types define the address-of&amp;nbsp;operator and instead of returning the real address of the object they return&amp;nbsp;a logical address. If the STL container re-arranges its contents this can lead&amp;nbsp;to corruption as it can unwittingly manipulate an object at the incorrect address.&lt;br /&gt;
&lt;br /&gt;
The prescribed solution to this problem is to not place the COM types&amp;nbsp;directly into the STL container but instead wrap them with the ATL&amp;nbsp;&lt;a href="http://msdn.microsoft.com/en-us/library/bs6acf5x(v=VS.90).aspx"&gt;CAdapt&lt;/a&gt;&amp;nbsp;class. &amp;nbsp;When adopting this approach&amp;nbsp;there are two&amp;nbsp;important aspects to consider:&lt;br /&gt;
&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;Firstly, is there a way to prevent incorrect usage of the containers?&lt;/li&gt;
&lt;li&gt;Secondly, assuming this is possible, is there a way to make sure it&amp;nbsp;covers the various permutations of STL containers and COM types&amp;nbsp;that are being used?&lt;/li&gt;
&lt;/ul&gt;&lt;br /&gt;
It turns out that the first issue is easily solved using template specialization. &amp;nbsp;The hard part though&amp;nbsp;is creating &amp;nbsp;a set of unit tests that ensure specializations have been created for all permutations and that they are active. &amp;nbsp;This is made even more difficult by the fact a successful use of the&amp;nbsp;specialization&amp;nbsp;results in compilation failure.&lt;br /&gt;
&lt;br /&gt;
This too can be solved by combing various template mechanisms and techniques: SFINAE &amp;amp; Template&amp;nbsp;Meta-programming&amp;nbsp;etc. &amp;nbsp;In the April issue of the &lt;a href="http://accu.org/"&gt;ACCU&lt;/a&gt; &lt;a href="http://accu.org/index.php/journals/c78/"&gt;Overload journal&lt;/a&gt; I have written &lt;a href="http://accu.org/var/uploads/journals/overload108.pdf#page=24"&gt;article&lt;/a&gt; that describes this problem along with the solution. &amp;nbsp;Please follow the &lt;a href="http://accu.org/var/uploads/journals/overload108.pdf#page=24"&gt;link&lt;/a&gt; below (and then jump to page 24 in the PDF if it doesn't open there automatically).&lt;br /&gt;
&lt;br /&gt;
&lt;a href="http://accu.org/var/uploads/journals/overload108.pdf#page=24"&gt;http://accu.org/var/uploads/journals/overload108.pdf#page=24&lt;/a&gt; &lt;br /&gt;
&lt;br /&gt;
The complete &lt;a href="https://github.com/petebarber/TemplateArticleExamples"&gt;source code&lt;/a&gt; the article is also available on GitHut:&amp;nbsp;&lt;a href="https://github.com/petebarber/TemplateArticleExamples"&gt;https://github.com/petebarber/TemplateArticleExamples&lt;/a&gt;&lt;img src="http://feeds.feedburner.com/~r/CCWindowsOtherRamblings/~4/M18-SeEG9KA" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/CCWindowsOtherRamblings/~3/M18-SeEG9KA/unit-testing-when-success-case-is.html</link><author>noreply@blogger.com (Pete Barber)</author><thr:total>3</thr:total><feedburner:origLink>http://petebarber.blogspot.com/2012/04/unit-testing-when-success-case-is.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-2918646278142295649.post-6065216018416447233</guid><pubDate>Mon, 02 Apr 2012 19:27:00 +0000</pubDate><atom:updated>2012-08-02T07:20:36.312-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Entity Framework DbContext SQLServerCE C# NUnit CodeProject SqlCeConnectionFactory databaseDirectory</category><title>Using NUnit and Entity Framework DbContext to programmatically create SQL Server CE databases &amp; specify the databse directory</title><description>&lt;i&gt;NOTE: An update to the method used here is provided in this newer post: &lt;a href="http://petebarber.blogspot.co.uk/2012/08/integration-testing-with-nunit-and.html"&gt;Integration Testing with NUnit and Entity Framework&lt;/a&gt;.&lt;/i&gt;&lt;br /&gt;
&lt;br /&gt;
I won't go into the why but I wanted to write what probably amounts to an integration test of an Entity Framework model. &amp;nbsp;I decided to use NUnit for this. &amp;nbsp;Even though it's predominately for Unit Testing there's no reason why it can't be used for other forms of testing. &amp;nbsp;In fact I think the &lt;a href="http://www.specflow.org/"&gt;SpecFlow &lt;/a&gt;BDD framework eventually performs its tests using NUnit: &lt;i&gt;It's not what you've got but what you do with it!&lt;/i&gt;&lt;br /&gt;
&lt;br /&gt;
The application I'm writing uses SQL Express but for my tests I wanted to create &amp;amp; destroy a database frequently and locally so I opted to use&amp;nbsp;&lt;a href="http://www.microsoft.com/sqlserver/en/us/editions/compact.aspx"&gt;SQL Server Compact Edition&lt;/a&gt;. &amp;nbsp;This is pretty easy to do with EF's &lt;a href="http://msdn.microsoft.com/en-us/library/system.data.entity.dbcontext(v=vs.103).aspx"&gt;DbContext&lt;/a&gt;: just create an instance of it, pass in either the name of the database or a &lt;a href="http://www.connectionstrings.com/articles/show/all-sql-server-connection-string-keywords"&gt;Connection String&lt;/a&gt;, e.g.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;[Test]&lt;/span&gt;&lt;br /&gt;
&lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;public void TestWithConnectionString()&lt;/span&gt;&lt;br /&gt;
&lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;{&lt;/span&gt;&lt;br /&gt;
&lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;&amp;nbsp; var db = new DbContext("Name=Foo");&lt;/span&gt;&lt;br /&gt;
&lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;&lt;br /&gt;
&lt;/span&gt;&lt;br /&gt;
&lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;&amp;nbsp; db.Database.Create();&lt;/span&gt;&lt;br /&gt;
&lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;}&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
which references the following Connection String in the .config file&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;&amp;lt;connectionStrings&amp;gt;&lt;/span&gt;&lt;br /&gt;
&lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;&amp;nbsp; &amp;lt;add name="Foo"&lt;/span&gt;&lt;br /&gt;
&lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;&amp;nbsp; &amp;nbsp; providerName="System.Data.SqlServerCe.4.0"&lt;/span&gt;&lt;br /&gt;
&lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;&amp;nbsp; &amp;nbsp; connectionString="Data Source=foo.sdf"/&amp;gt;&lt;/span&gt;&lt;br /&gt;
&lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;&amp;lt;/connectionStrings&amp;gt;&lt;/span&gt;&lt;span class="Apple-tab-span" style="white-space: pre;"&gt; &lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
As I'm going to be potentially creating many of these I wanted precise control over their name and location. &amp;nbsp;This meant I didn't really want to use a Connection String as this is more or less hard-coded in the .config file. &lt;br /&gt;
&lt;br /&gt;
Instead I opted to create it programmatically. &amp;nbsp;By &lt;a href="http://msdn.microsoft.com/en-us/library/system.data.entity.dbcontext(v=vs.103).aspx"&gt;default&lt;/a&gt; DbContext expects to be using SQL Server in particular an instance of SQLExpress named .\SQLExpress. &amp;nbsp;This is easily changed by replacing the &lt;a href="http://msdn.microsoft.com/en-us/library/system.data.entity.database.defaultconnectionfactory(v=vs.103).aspx"&gt;DefaultConnectionFactory &lt;/a&gt;with the factory class for SQL Server CE: &lt;a href="http://msdn.microsoft.com/en-us/library/system.data.entity.infrastructure.sqlceconnectionfactory(v=vs.103).aspx"&gt;SqlCeConnectionFactory&lt;/a&gt;. &lt;br /&gt;
&lt;br /&gt;
The first parameter to the constructor is the type of the factory class which allows instances of different versions to be created. This is simply the &lt;i&gt;providerName&lt;/i&gt;&amp;nbsp;as per the Connection String. &amp;nbsp;The second parameter is the directory to create any new databases in. &amp;nbsp;The third parameter (unused in the example below) are options to append to the generated Connection String. &amp;nbsp;The code below will result in the creation of C:\UsersPete\TestDBs\bar.sdf assuming the directory exists and the user has appropriate permissions and bar.sdf does not already exist.&lt;br /&gt;
&lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;&lt;br /&gt;
&lt;/span&gt;&lt;br /&gt;
&lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;[Test]&lt;/span&gt;&lt;br /&gt;
&lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;public void TestWithFactory()&lt;/span&gt;&lt;br /&gt;
&lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;{&lt;/span&gt;&lt;br /&gt;
&lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;&amp;nbsp; Database.DefaultConnectionFactory =&amp;nbsp;&lt;/span&gt;&lt;br /&gt;
&lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;&amp;nbsp; &amp;nbsp; new SqlCeConnectionFactory(&lt;/span&gt;&lt;br /&gt;
&lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; "System.Data.SqlServerCe.4.0",&amp;nbsp;&lt;/span&gt;&lt;br /&gt;
&lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; @"C:\Users\Pete\TestDBs\", "");&lt;/span&gt;&lt;br /&gt;
&lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;&lt;br /&gt;
&lt;/span&gt;&lt;br /&gt;
&lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;&amp;nbsp; var db = new DbContext("bar.sdf");&lt;/span&gt;&lt;br /&gt;
&lt;span class="Apple-tab-span" style="white-space: pre;"&gt;&lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;   &lt;/span&gt;&lt;/span&gt;&lt;br /&gt;
&lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;&amp;nbsp; db.Database.Create();&lt;/span&gt;&lt;br /&gt;
&lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;}&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
That's mainly it: &amp;nbsp;A simple way to programmatically create databases. &amp;nbsp;This code should really be moved to the &lt;a href="http://www.nunit.org/index.php?p=setup&amp;amp;r=2.6"&gt;SetUp&lt;/a&gt; method and a corresponding &lt;a href="http://www.nunit.org/index.php?p=teardown&amp;amp;r=2.6"&gt;TearDown&lt;/a&gt; method added to delete the database; oh, and some tests!&lt;br /&gt;
&lt;br /&gt;
I haven't got that far yet and the actual reason for writing the entry was for a short while despite specifying the directory for the databases, i.e.&amp;nbsp;&lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;C:\Users\Pete\TestDBs&amp;nbsp;&lt;/span&gt;they were being created in the current working directory. &amp;nbsp;This was because rather than just specifying the name of the database as the argument to &lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;DbContext&lt;/span&gt; I was passing the string &lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;"DataSource=bar.sdf" &lt;/span&gt;of which the name part appears to be an absolute path and thus override that specified in the &lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;SqlCeConnectionFactory&lt;/span&gt;. &amp;nbsp;As only a file name is present it uses the current working directory for the path element. If you've got the same issue (whether integration testing or not) this might save you a little time.&lt;img src="http://feeds.feedburner.com/~r/CCWindowsOtherRamblings/~4/cC1QdEhbyL4" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/CCWindowsOtherRamblings/~3/cC1QdEhbyL4/using-nunit-and-entity-framework.html</link><author>noreply@blogger.com (Pete Barber)</author><thr:total>70</thr:total><feedburner:origLink>http://petebarber.blogspot.com/2012/04/using-nunit-and-entity-framework.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-2918646278142295649.post-1492521190972672496</guid><pubDate>Wed, 18 Jan 2012 19:00:00 +0000</pubDate><atom:updated>2012-01-18T11:00:14.476-08:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">C# "command line" argument parsing attributes reflection TDD WPF</category><title>A C#/.NET Attributes Based Command Line Argument Parser</title><description>I've been meaning to add a blog entry for this for a while. &amp;nbsp;It's just a link to my &lt;a href="http://www.codeproject.com/KB/cs/NAttrArgs.aspx"&gt;latest Code Project article&lt;/a&gt; that went live last week. &amp;nbsp;It's a long piece describing a small library for handling the parsing of command line arguments in C# programs, either Console or GUI (there's a WPF example).&lt;br /&gt;
&lt;br /&gt;
This is the first project I created using Test Driven Development so as well as the technical details of the library there's also a description of how I found TDD.&lt;br /&gt;
&lt;br /&gt;
You can find it here:&amp;nbsp;&lt;a href="http://www.codeproject.com/KB/cs/NAttrArgs.aspx"&gt;http://www.codeproject.com/KB/cs/NAttrArgs.aspx&lt;/a&gt;&lt;img src="http://feeds.feedburner.com/~r/CCWindowsOtherRamblings/~4/WWKf6bdrVe4" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/CCWindowsOtherRamblings/~3/WWKf6bdrVe4/cnet-attributes-based-command-line.html</link><author>noreply@blogger.com (Pete Barber)</author><thr:total>1</thr:total><feedburner:origLink>http://petebarber.blogspot.com/2012/01/cnet-attributes-based-command-line.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-2918646278142295649.post-4722880360124513807</guid><pubDate>Wed, 04 Jan 2012 13:57:00 +0000</pubDate><atom:updated>2012-01-04T05:57:54.798-08:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">NFS C# .NET Server "Open Source"</category><title>Open Source C# Network File System (NFS) Server (for Windows)</title><description>Happy New Year!&lt;br /&gt;
&lt;br /&gt;
Not a proper post but just a quick link to my latest Code Project &lt;a href="http://www.codeproject.com/KB/IP/NFSServer.aspx"&gt;article&lt;/a&gt;. &amp;nbsp;A few years ago I wrote an NFS Server (in C#). &amp;nbsp;I had reason to revisit this lately so I thought I might as well write it up as a &lt;a href="http://www.codeproject.com/KB/IP/NFSServer.aspx"&gt;Code Project article&lt;/a&gt; and &lt;a href="https://github.com/petebarber/NFS"&gt;Open Source&lt;/a&gt; it. &amp;nbsp;You can grab it from &lt;a href="https://github.com/petebarber/NFS"&gt;GitHub&lt;/a&gt;.&lt;br /&gt;
&lt;br /&gt;
Links:&lt;br /&gt;
&lt;br /&gt;
Article:&amp;nbsp;http://www.codeproject.com/KB/IP/NFSServer.aspx&lt;br /&gt;
Source:&amp;nbsp;&lt;a href="https://github.com/petebarber/NFS"&gt;https://github.com/petebarber/NFS&lt;/a&gt;&lt;img src="http://feeds.feedburner.com/~r/CCWindowsOtherRamblings/~4/nw6ZcfzXtFI" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/CCWindowsOtherRamblings/~3/nw6ZcfzXtFI/open-source-c-network-file-system-nfs.html</link><author>noreply@blogger.com (Pete Barber)</author><thr:total>0</thr:total><feedburner:origLink>http://petebarber.blogspot.com/2012/01/open-source-c-network-file-system-nfs.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-2918646278142295649.post-1631985374784431425</guid><pubDate>Tue, 06 Dec 2011 13:07:00 +0000</pubDate><atom:updated>2011-12-06T05:07:52.868-08:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">CodeProject C++ C++11  constexpr range-for</category><title>Obtaining the size of a C++ array using templates and other techniques (from C++11) - Part 2</title><description>Welcome back! &amp;nbsp;In &lt;a href="http://petebarber.blogspot.com/2011/11/obtaining-size-of-c-array-using.html"&gt;Part 1&lt;/a&gt;&amp;nbsp;we saw a nifty technique to obtain the size of an array via &lt;a href="http://accu.org/index.php/journals/409"&gt;function template argument deduction&lt;/a&gt;. &amp;nbsp;However, this ended with the problem of how to use this value at compile time, e.g. as the size of another array. &amp;nbsp;This proves hard in C++98 but &lt;a href="http://www2.research.att.com/~bs/C++0xFAQ.html"&gt;C++11&lt;/a&gt; changes things.&lt;br /&gt;
&lt;br /&gt;
The simplest way to enable compile time use is to make use of the new &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;&lt;a href="http://www2.research.att.com/~bs/C++0xFAQ.html#constexpr"&gt;constexpr&lt;/a&gt;&lt;/span&gt; keyword. &amp;nbsp;This tells the compiler that the function can be completely evaluated (to a constant value) at compile. &amp;nbsp;As such C++11 allows this function &lt;i&gt;to be called&lt;/i&gt;&amp;nbsp;at compile time though instead the evaluated constant value is used. &amp;nbsp;Adding this to the definition of &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;GetNumberOfElements&amp;nbsp;&lt;/span&gt;as below&lt;br /&gt;
&lt;br /&gt;
&lt;span class="Apple-style-span" style="background-color: white; color: #222222; line-height: 18px;"&gt;&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;&lt;b&gt;template&amp;lt;typename T, size_t sizeOfArray&amp;gt;&lt;/b&gt;&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;
&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;&lt;span class="Apple-style-span" style="background-color: white; line-height: 18px;"&gt;&lt;b&gt;&lt;span class="Apple-style-span" style="color: red;"&gt;constexpr &lt;/span&gt;&lt;span class="Apple-style-span" style="color: #222222;"&gt;size_t GetNmberOfElements(T (&amp;amp;)[sizeOfArray])&lt;/span&gt;&lt;/b&gt;&lt;/span&gt;&lt;br style="background-color: white; color: #222222; line-height: 18px;" /&gt;&lt;span class="Apple-style-span" style="background-color: white; color: #222222; font-weight: bold; line-height: 18px;"&gt;{&lt;/span&gt;&lt;br style="background-color: white; color: #222222; line-height: 18px;" /&gt;&lt;span class="Apple-style-span" style="background-color: white; color: #222222; font-weight: bold; line-height: 18px;"&gt;&lt;span class="Apple-style-span" style="white-space: pre;"&gt;&amp;nbsp;   &lt;/span&gt;return sizeOfArray;&lt;/span&gt;&lt;br style="background-color: white; color: #222222; line-height: 18px;" /&gt;&lt;span class="Apple-style-span" style="background-color: white; color: #222222; font-weight: bold; line-height: 18px;"&gt;}&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
now allows the following to compile&lt;br /&gt;
&lt;br /&gt;
&lt;b style="font-family: 'Courier New', Courier, monospace;"&gt;&lt;span class="Apple-style-span" style="background-color: white; color: #222222; line-height: 18px;"&gt;char a[100];&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;
&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;&lt;b&gt;&lt;span class="Apple-style-span" style="background-color: white; color: #222222; line-height: 18px;"&gt;char b[GetNumberOfElements(a)];&lt;/span&gt;&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;
&lt;span class="Apple-style-span" style="background-color: white; color: #222222; font-family: 'Courier New', Courier, monospace; font-size: 13px; line-height: 18px;"&gt;&lt;b&gt;&lt;br /&gt;
&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;
Is this the best that we can do? &amp;nbsp;Using raw array types isn't that good. &amp;nbsp;Even though the size of the array is known and can now be discovered at compile time using it in &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/e5sk9w9k.aspx"&gt;std::for_each&lt;/a&gt;&lt;/span&gt;&amp;nbsp;is&amp;nbsp;somewhat burdensome as the length must be obtained in order to obtain the end iterator, i.e.&lt;br /&gt;
&lt;br /&gt;
&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;&lt;b&gt;std::for_each(&amp;amp;a[0], &amp;amp;a[GetNumberOfElements(a)], SomeFunctor())&lt;span class="Apple-style-span" style="font-size: x-small;"&gt;;&lt;/span&gt;&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
Due to the raw array not being an object it doesn't have an &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;end&lt;/span&gt; method which means the code must rely on the programmer&amp;nbsp;specifying&amp;nbsp;the correct index for the end of an array or using the technique above.&lt;br /&gt;
&lt;br /&gt;
This can be remedied by moving from raw array types to&amp;nbsp;&lt;a href="http://msdn.microsoft.com/en-us/library/bb983093.aspx"&gt;std::array&lt;/a&gt; (first made available in &lt;a href="http://en.wikipedia.org/wiki/C%2B%2B_Technical_Report_1"&gt;TR1&lt;/a&gt;), e.g.&lt;br /&gt;
&lt;br /&gt;
&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;&lt;b&gt;std::array&amp;lt;char, 100&amp;gt; a;&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;
&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;&lt;b&gt;std::for_each(&lt;span class="Apple-style-span" style="color: red;"&gt;std::begin(a)&lt;/span&gt;, &lt;span class="Apple-style-span" style="color: red;"&gt;std::end(a)&lt;/span&gt;, SomeFunctor());&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
(Note the use of the C+11 non-member versions begin and end functions)&lt;br /&gt;
&lt;br /&gt;
The downside of using &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;std::array&lt;/span&gt; is that even though it can be initialized when defined, e.g.&lt;br /&gt;
&lt;br /&gt;
&lt;b style="font-family: 'Courier New', Courier, monospace;"&gt;std::array&amp;lt;int, 4&amp;gt; a = { 0, 1, 2, 3 };&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
It effectively requires the length of the array specifying twice. &amp;nbsp;Firstly as the template parameter and then again implicitly by the number of elements in the initializer list.&lt;br /&gt;
&lt;br /&gt;
Given the new&amp;nbsp;&lt;a href="http://www2.research.att.com/~bs/C++0xFAQ.html#init-list"&gt;initializer list&lt;/a&gt; feature of C++11 it could be expected that this would allow&amp;nbsp;initialization&amp;nbsp;without the length parameter. &amp;nbsp;However it seems this is not supported "out of the box" though there are some &lt;a href="http://stackoverflow.com/questions/6114067/how-to-emulate-c-array-initialization-int-arr-e1-e2-e3-behaviou"&gt;interesting techniques&lt;/a&gt; to allow this.&lt;br /&gt;
&lt;br /&gt;
All is not lost though. &amp;nbsp;Taking a step back and returning to the raw array the size issue can be circumvented by use of C++11's &lt;a href="http://www2.research.att.com/~bs/C++0xFAQ.html#for"&gt;range-for&lt;/a&gt; statement.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;char a[100];&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;
&lt;b&gt;&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;SomeFunctor sf;&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;
&lt;b&gt;&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;for (auto x : a)&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;
&lt;b&gt;&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;&lt;span class="Apple-tab-span" style="white-space: pre;"&gt; &lt;/span&gt;sf(x);&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
To backtrack once again, the use of the non-member versions of begin and end can also be used on raw arrays so the example above can also be written as:&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;char a[100];&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;
&lt;b&gt;&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;std::for_each(std::begin(a), std::end(a), SomeFunctor());&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
Which if the purpose of the loop is to invoke a functor then std::for_each is more&amp;nbsp;succinct&amp;nbsp;than range-for as it doesn't require an explicit&amp;nbsp;instance&amp;nbsp;of the functor. &lt;br /&gt;
&lt;br /&gt;
I suspect the same technique for finding the length of a naked array along with &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;constexpr &lt;/span&gt;is used by the non-member version of &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;end&amp;nbsp;&lt;/span&gt;to obtain the length. &amp;nbsp;In fact one version of end is probably a function template overloaded to accept a raw array as its container parameter, e.g.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;template&amp;lt;typename T, size_t&amp;gt;&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;
&lt;b&gt;&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;constexpr T* example_begin(T (&amp;amp;array)[])&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;
&lt;b&gt;&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;{&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;
&lt;b&gt;&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;&lt;span class="Apple-style-span" style="white-space: pre;"&gt;&amp;nbsp;   &lt;/span&gt;return &amp;amp;array[0];&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;
&lt;b&gt;&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;}&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;
&lt;b&gt;&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;&lt;br /&gt;
&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;
&lt;b&gt;&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;template&amp;lt;typename T, size_t sizeOfArray&amp;gt;&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;
&lt;b&gt;&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;constexpr T* example_end(T (&amp;amp;array)[sizeOfArray])&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;
&lt;b&gt;&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;{&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;
&lt;b&gt;&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;&lt;span class="Apple-style-span" style="white-space: pre;"&gt;&amp;nbsp;   &lt;/span&gt;return &amp;amp;array[sizeOfArray];&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;
&lt;b&gt;&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;}&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;
&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;&lt;b&gt;&lt;br /&gt;
&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;
&lt;b&gt;&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;char a[100];&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;
&lt;b&gt;&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;std::for_each(example_begin(a), example_end(a), SomeFunctor());&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
However, any looping mechanism that requires both the start and end to be specified rather than just the container does allow for an error to occur by having begin and end of different containers specified whereas range-for eliminates this possibility!&lt;br /&gt;
&lt;div&gt;&lt;br /&gt;
&lt;/div&gt;In summary, it's possible to find the size of a raw array using function template deduction and using C++11 features that value can be used at compile time. &amp;nbsp;However, if the reason that the size needs obtaining is to obtain the end iterator then C++11 makes this redundant through the use of range-for and the non-member versions of begin and more accurately end.&lt;br /&gt;
&lt;a href="http://www.blogger.com/"&gt;&lt;/a&gt;&lt;img src="http://feeds.feedburner.com/~r/CCWindowsOtherRamblings/~4/P0JoOxSItqI" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/CCWindowsOtherRamblings/~3/P0JoOxSItqI/obtaining-size-of-c-array-using.html</link><author>noreply@blogger.com (Pete Barber)</author><thr:total>0</thr:total><feedburner:origLink>http://petebarber.blogspot.com/2011/12/obtaining-size-of-c-array-using.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-2918646278142295649.post-5142043890868461547</guid><pubDate>Fri, 18 Nov 2011 13:52:00 +0000</pubDate><atom:updated>2012-02-20T04:59:03.465-08:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">C++ C++11 CodeProject</category><title>Obtaining the size of a C++ array using templates and other techniques (from C++11) - Part 1</title><description>Recently I was helping somebody debug an issue around the use of &lt;a href="http://msdn.microsoft.com/en-us/library/ce3zzk1k(v=vs.80).aspx"&gt;swprintf_s&lt;/a&gt;. &amp;nbsp;The issue turned out to an &lt;a href="http://www.hacker-dictionary.com/terms/obi_wan-error"&gt;Obi-Wan&lt;/a&gt; (off by one) error. &amp;nbsp;I don't tend use the likes of printf() very much instead preferring to use a &lt;a href="http://msdn.microsoft.com/en-us/library/7d0zt0ws.aspx"&gt;std::stringstream&lt;/a&gt; if I need to format into a string.&lt;br /&gt;
&lt;br /&gt;
I'd assumed that the Microsoft's secure versions of these methods, i.e. those with _s suffix took a buffer size so when looking at the help for swprintf_s I was&amp;nbsp;momentarily&amp;nbsp;taken aback by the lack of a buffer parameter. &amp;nbsp;However I then noticed that swprintf_s is not just a regular function but is in fact a function template:&lt;br /&gt;
&lt;br /&gt;
&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;&lt;b&gt;template &amp;lt;size t size&amp;gt;&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;
&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;&lt;b&gt;int swprintf_s(&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;
&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;&lt;b&gt;&amp;nbsp; &amp;nbsp; wchar_t (&amp;amp;buffer)[size],&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;
&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;&lt;b&gt;&amp;nbsp; &amp;nbsp; const wchar_t *format [, argument] ...); // C++ only&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
One of the most useful properties of a function template is its ability to deduce its argument types. &amp;nbsp;In this case the argument is not a type parameter but a fundamental type (though using the &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;size_t &lt;/span&gt;typedef) that specifies the size of the target string buffer (in characters not bytes).  When used as:&lt;br /&gt;
&lt;br /&gt;
&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;&lt;b&gt;wchar_t buf[10];&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;
&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;&lt;b&gt;swprintf_s(buf, "%d", 10);&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
It deduces that the size of the buffer (buf) is 10. &amp;nbsp;This works because the template parameter is used to specify the size of the expected &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;wchar_t &lt;/span&gt;array that &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;swprintf_f &lt;/span&gt;expects. &amp;nbsp;It could have been specified as in &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;swprintf_s&amp;lt;10&amp;gt;(buf, "%d, 10)&lt;/span&gt; but this is where the beauty lies in that the compiler is able to deduce it. &amp;nbsp;This is what function templates do and how they're often used so there's nothing novel here accept the application of finding an array size. &amp;nbsp;This is a really neat trick and I don't know why I've missed it for so long!&lt;br /&gt;
&lt;br /&gt;
An important point here is that the signature is a reference to an array (note the &lt;b&gt;&amp;amp;&lt;/b&gt; before buffer) as opposed to the array syntax of just &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;wchar_t (buffer)[size]&lt;/span&gt;.  If this were used the function template would be unable to deduce the parameter (&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;size&lt;/span&gt;). This is because the syntax:&lt;br /&gt;
&lt;br /&gt;
&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;&lt;b&gt;template&amp;lt;size_t size&amp;gt; foo(wchar_t (buffer)[size])&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;a href="http://www.informit.com/guides/content.aspx?g=cplusplus&amp;amp;seqNum=207"&gt;decays &lt;/a&gt;to become:&lt;br /&gt;
&lt;br /&gt;
&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;&lt;b&gt;template&amp;lt;size_t size&amp;gt; foo(wchar_t* buffer);&lt;br /&gt;
&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;
When compiled, i.e.  &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;foo()&lt;/span&gt; can accept a pointer to a &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;wchar_t&lt;/span&gt;&lt;span class="Apple-style-span" style="font-family: Georgia, 'Times New Roman', serif;"&gt; array of any size. In fact a pointer to &lt;/span&gt;&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;wchar_t*&lt;/span&gt; is fine. There is nothing special about this and it's just the standard decay that C (and C++) has always supported.&lt;br /&gt;
&lt;br /&gt;
Anyway, after that slight diversion into decay let's return to deducing the size of an array.  So why is this is this useful? In order to iterate over each of any arrays elements, e.g.&lt;br /&gt;
&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;&lt;b&gt;&lt;br /&gt;
int a[] = { 0, 1, 2, 3, 4 };&lt;/b&gt;&lt;/span&gt;&lt;b style="font-family: 'Courier New', Courier, monospace;"&gt;for (int i = 0; i &amp;lt; sizeof(a)/sizeof(int); ++i)&lt;/b&gt;&lt;br /&gt;
&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;&lt;b&gt;&lt;span class="Apple-tab-span" style="white-space: pre;"&gt; &lt;/span&gt;SomeFn(i);&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
or slightly better:&lt;br /&gt;
&lt;br /&gt;
&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;&lt;b&gt;int a[] = { 0, 1, 2, 3, 4 };&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;
&lt;b&gt;&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;std::for_each(&amp;amp;a[0], &amp;amp;a[sizeof(a) / sizeof(int)], &amp;amp;SomeFn)&lt;/span&gt;&lt;/b&gt;&lt;b style="font-family: 'Courier New', Courier, monospace; font-size: small;"&gt;;&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
The number of elements is required in order to terminate the iteration.&lt;br /&gt;
&lt;br /&gt;
The concept can be generalized to obtain the size of any type of array, i.e.&lt;br /&gt;
&lt;br /&gt;
&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;&lt;b&gt;template&amp;lt;typename T, size_t sizeOfArray&amp;gt; int GetNmberOfElements(T (&amp;amp;)[sizeOfArray])&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;
&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;&lt;b&gt;{&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;
&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;&lt;b&gt;&lt;span class="Apple-style-span" style="white-space: pre;"&gt;&amp;nbsp;   &lt;/span&gt;return sizeOfArray;&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;
&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;&lt;b&gt;}&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
Which can be used to rewrite the previous examples as:&lt;br /&gt;
&lt;br /&gt;
&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;&lt;b&gt;int a[] = { 0, 1, 2, 3, 4 };&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;
&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;&lt;b&gt;std::for_each(&amp;amp;a[0], &amp;amp;a[GetNumberOfElements(a)], &amp;amp;SomeFn);&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
Returning to the discussions about decay it should be noted that this mechanism only works for actual arrays. &amp;nbsp;The signature used to prevent decay, i.e. using the '&amp;amp;' means that a pointer cannot be passed, e.g.&lt;br /&gt;
&lt;br /&gt;
&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;&lt;b&gt;char *pa = new char[100];&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;
&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;&lt;b&gt;GetNumberOfElements&amp;lt;char, 100&amp;gt;(pa);&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;
&lt;div&gt;&lt;br /&gt;
&lt;/div&gt;&lt;div&gt;Won't compile with VC++ 2010 giving:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;
&lt;/div&gt;&lt;div&gt;&lt;div&gt;&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;&lt;b&gt;Error&lt;span class="Apple-tab-span" style="white-space: pre;"&gt; &lt;/span&gt;3&lt;span class="Apple-tab-span" style="white-space: pre;"&gt; &lt;/span&gt;error C2664: 'GetNumberOfElements' : cannot convert parameter 1 from 'char *' to 'char (&amp;amp;)[100]'&lt;/b&gt;&lt;span class="Apple-tab-span" style="font-size: x-small; white-space: pre;"&gt; &lt;/span&gt;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;
&lt;/div&gt;This makes perfect sense as it's explicitly requires an array. &amp;nbsp;Even if for some reason it could accept the pointer then it wouldn't be able to deduce the size because this information isn't&amp;nbsp;syntactically&amp;nbsp;available (though will be most likely embedded within memory block that &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;pa&lt;/span&gt; points too; quite possibly a few bytes further back so that when delete [] is invoked the C++ runtime will know how much memory to free). &amp;nbsp;Looking at the &lt;a href="http://msdn.microsoft.com/en-us/library/ce3zzk1k(v=vs.80).aspx"&gt;MSDN help for swprintf_s()&lt;/a&gt;&amp;nbsp;it is clear why additional definitions (the non-template overloads) are provided as these deal with passing pointers.&lt;br /&gt;
&lt;br /&gt;
Now that this cool feature can be used to easily obtain array sizes the next thing you tend to want to do is then define other arrays using this information, i.e.&lt;br /&gt;
&lt;br /&gt;
&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;&lt;b&gt;char a[100];&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;
&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;&lt;b&gt;char b[GetNumberOfElements(a)];&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
However this won't compile as despite the fact that GetNumberOfElements() performs (well the compiler does) the size deduction at compile time the result is only available at runtime. &amp;nbsp;To define an array the size must be known at compile time.&lt;br /&gt;
&lt;br /&gt;
There is a clever &lt;a href="http://stackoverflow.com/questions/2270726/how-to-determine-the-size-of-an-array-of-strings-in-c/2271577#2271577"&gt;hack &lt;/a&gt;to make this available at compile time but it requires the use a macro which is&amp;nbsp;unpleasant. &amp;nbsp;However, at this point it's C++11 to the rescue but that'll have to wait until &lt;a href="http://petebarber.blogspot.com/2011/12/obtaining-size-of-c-array-using.html"&gt;part 2&lt;/a&gt; which is available &lt;a href="http://petebarber.blogspot.com/2011/12/obtaining-size-of-c-array-using.html"&gt;here&lt;/a&gt;.&lt;img src="http://feeds.feedburner.com/~r/CCWindowsOtherRamblings/~4/ktXttUMq8PM" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/CCWindowsOtherRamblings/~3/ktXttUMq8PM/obtaining-size-of-c-array-using.html</link><author>noreply@blogger.com (Pete Barber)</author><thr:total>2</thr:total><feedburner:origLink>http://petebarber.blogspot.com/2011/11/obtaining-size-of-c-array-using.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-2918646278142295649.post-3895520423947462998</guid><pubDate>Wed, 17 Aug 2011 18:10:00 +0000</pubDate><atom:updated>2012-02-20T10:45:39.829-08:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">CodeProject</category><category domain="http://www.blogger.com/atom/ns#">Attribute</category><category domain="http://www.blogger.com/atom/ns#">C#</category><category domain="http://www.blogger.com/atom/ns#">.NET 2.0</category><category domain="http://www.blogger.com/atom/ns#">CustomAttribute</category><category domain="http://www.blogger.com/atom/ns#">Fluent Programming</category><title>Unit Testing C# Custom Attributes with NUnit Part 4</title><description>In&amp;nbsp;&lt;a href="http://petebarber.blogspot.com/2011/07/unit-testing-c-custom-attributes-with_1337.html"&gt;Unit Testing C# Custom Attributes with NUnit Part 3&lt;/a&gt;&amp;nbsp;towards the end I showed the following code&lt;br /&gt;
&lt;pre&gt;&lt;span style="color: #2b91af;"&gt;Assert&lt;/span&gt;.That(&lt;span style="color: #2b91af;"&gt;MethodBase&lt;/span&gt;.GetCurrentMethod(), 
            &lt;span style="color: #2b91af;"&gt;Has&lt;/span&gt;.Attribute&amp;lt;&lt;span style="color: #2b91af;"&gt;FunkyAttribute&lt;/span&gt;&amp;gt;().Property(&lt;span style="color: #a31515;"&gt;"SettingOne"&lt;/span&gt;).TypeOf&amp;lt;&lt;span style="color: blue;"&gt;int&lt;/span&gt;&amp;gt;());&lt;/pre&gt;to test the type of a property on an attribute. &amp;nbsp;As it turns out this does not actually do that. &amp;nbsp;Instead it tests the type of the value returned from the property. &amp;nbsp;What's happening is that the object returned from &lt;i&gt;Property()&lt;/i&gt;&amp;nbsp;isn't some of meta-object representing a property but is the actual value of the property.&lt;br /&gt;
&lt;br /&gt;
In the case above it amounts to the same thing. &amp;nbsp;As the property type is an &lt;i&gt;int&lt;/i&gt;&amp;nbsp;even if it has not been set the value will be &lt;i&gt;0&lt;/i&gt;&amp;nbsp;of which type is &lt;i&gt;int&lt;/i&gt;. &amp;nbsp;However, if it's a reference type (quite likely a &lt;i&gt;string&lt;/i&gt;) or a nullable type the value can be &lt;i&gt;null&lt;/i&gt;. &amp;nbsp;E.g.&lt;br /&gt;
&lt;br /&gt;
&lt;pre style="color: black;"&gt;&lt;span style="color: #2b91af;"&gt;Assert&lt;/span&gt;.That(&lt;span style="color: #2b91af;"&gt;MethodBase&lt;/span&gt;.GetCurrentMethod(), 
     &lt;span style="color: #2b91af;"&gt;Has&lt;/span&gt;.Attribute&amp;lt;&lt;span style="color: #2b91af;"&gt;FunkyAttribute&lt;/span&gt;&amp;gt;().Property(&lt;span style="color: #a31515;"&gt;"FunkyName"&lt;/span&gt;).TypeOf&amp;lt;&lt;span style="color: blue;"&gt;string&lt;/span&gt;&amp;gt;());&lt;/pre&gt;&lt;pre style="color: black;"&gt;&lt;/pre&gt;&lt;pre style="color: black;"&gt;&lt;/pre&gt;&lt;pre style="color: black;"&gt;&lt;span class="Apple-style-span" style="font-family: 'Times New Roman';"&gt;&lt;span class="Apple-style-span" style="white-space: normal;"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="color: black;"&gt;&lt;span class="Apple-style-span" style="font-family: 'Times New Roman';"&gt;&lt;span class="Apple-style-span" style="white-space: normal;"&gt;&amp;nbsp;&lt;/span&gt;&lt;/span&gt;&lt;/pre&gt;Which causes the following when run:&lt;br /&gt;
&lt;pre style="color: black;"&gt;&lt;/pre&gt;&lt;pre&gt;&lt;span class="Apple-style-span" style="color: black;"&gt;
&lt;/span&gt;AttrTestV3.FunkyTester.TestThatTheTypeOfFunkyNameWhenNotSetIs_string:
  Expected: attribute AttrTestDefs.FunkyAttribute property FunkyName &amp;lt;System.String&amp;gt;
  But was:  &amp;lt;AttrTestDefs.FunkyAttribute&amp;gt;
&lt;/pre&gt;&lt;div&gt;&lt;br /&gt;
&lt;/div&gt;&lt;div&gt;It seems that when there is no value &lt;i&gt;Property()&lt;/i&gt;&amp;nbsp;which tests for the presence of a the specified property name and implicitly returns the value of the property (if found) has nothing to return so for some reason the attribute type obtained from the call &lt;i&gt;Has.Attribute()&lt;/i&gt;&amp;nbsp;is returned.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;
&lt;/div&gt;&lt;div&gt;Currently, there is no way with NUnit to handle this case. &amp;nbsp;I started a &lt;a href="http://groups.google.com/group/nunit-discuss/browse_thread/thread/11013b373eef2334/260d31a53360a33c?lnk=gst&amp;amp;q=is+this+a+bug#260d31a53360a33c"&gt;thread on the NUnit discussion group&lt;/a&gt; which discusses this issue and it seems like the authors of NUnit have some plans.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;
&lt;/div&gt;&lt;div&gt;As an interim solution if the property is optional for a custom attribute then in the fixture make sure a value is assigned. &amp;nbsp;In the case above:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;
&lt;/div&gt;&lt;pre&gt;[&lt;span style="color: #2b91af;"&gt;Test&lt;/span&gt;]
[&lt;span style="color: #2b91af;"&gt;Funky&lt;/span&gt;(FunkyName = &lt;span style="color: #a31515;"&gt;"dummy"&lt;/span&gt;)]
&lt;span style="color: blue;"&gt;public void&lt;/span&gt; TestThatTheTypeOfFunkyNameWhenNotSetIs2_string()
{
    &lt;span style="color: #2b91af;"&gt;Assert&lt;/span&gt;.That(&lt;span style="color: #2b91af;"&gt;MethodBase&lt;/span&gt;.GetCurrentMethod(),
         &lt;span style="color: #2b91af;"&gt;Has&lt;/span&gt;.Attribute&amp;lt;&lt;span style="color: #2b91af;"&gt;FunkyAttribute&lt;/span&gt;&amp;gt;().Property(&lt;span style="color: #a31515;"&gt;"FunkyName"&lt;/span&gt;).TypeOf&amp;lt;&lt;span style="color: blue;"&gt;string&lt;/span&gt;&amp;gt;());
}&lt;/pre&gt;&lt;pre style="color: black;"&gt;&lt;/pre&gt;&lt;pre style="color: black;"&gt;&lt;/pre&gt;&lt;br /&gt;
I think that's the end again:-) &amp;nbsp;Here are the links to the previous parts: &lt;a href="http://petebarber.blogspot.com/2011/07/unit-testing-c-custom-attributes-with.html"&gt;One&lt;/a&gt;, &lt;a href="http://petebarber.blogspot.com/2011/07/unit-testing-c-custom-attributes-with_26.html"&gt;two &lt;/a&gt;&amp;amp; &lt;a href="http://petebarber.blogspot.com/2011/07/unit-testing-c-custom-attributes-with_1337.html"&gt;three&lt;/a&gt;.&lt;img src="http://feeds.feedburner.com/~r/CCWindowsOtherRamblings/~4/1gw9NL9-MGI" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/CCWindowsOtherRamblings/~3/1gw9NL9-MGI/unit-testing-c-custom-attributes-with.html</link><author>noreply@blogger.com (Pete Barber)</author><thr:total>0</thr:total><feedburner:origLink>http://petebarber.blogspot.com/2011/08/unit-testing-c-custom-attributes-with.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-2918646278142295649.post-2362108597240258507</guid><pubDate>Sun, 14 Aug 2011 15:44:00 +0000</pubDate><atom:updated>2011-08-14T08:44:05.834-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Twitter "London Surrey Cycle Classic" "Mark Cavendish" #CycleClasic #testevent Twittating Spectwitter Spectwiting</category><title>Spectating with Twitter: Twittating or Spectwiting</title><description>Today I went to watch (spectate) a small part of the &lt;a href="http://www.cyclingweekly.co.uk/news/latest/529695/cavendish-wins-london-surrey-cycle-classic.html"&gt;London-Surrey Cycle Classic&lt;/a&gt;.  Being a 160KM cycle race it wasn't possible to see a lot of it.  Even though it featured one of Britain's most&amp;nbsp;prominent&amp;nbsp;and&amp;nbsp;successful&amp;nbsp;cyclists&amp;nbsp;&lt;a href="http://www.markcavendish.co.uk/"&gt;Mark Cavendish&lt;/a&gt; the BBC or I suppose any other TV companies chose not to broadcast it live, in fact there didn't seem to be any conventional mainstream live media coverage.  Bummer!&lt;br /&gt;
&lt;br /&gt;
However, &lt;a href="http://twitter.com/#!/foobarber"&gt;Twitter&lt;/a&gt; to the rescue.  There seemed to be several authoritative sources (&lt;a href="http://twitter.com/#!/cyclingweekly"&gt;@cyclingweekly&lt;/a&gt;,&amp;nbsp;&lt;a href="http://twitter.com/#!/roadcyclinguk"&gt;@roadcyclinguk&lt;/a&gt;,&amp;nbsp;&lt;a href="http://twitter.com/#!/antmccrossan"&gt;@antmccrossan&lt;/a&gt;&amp;nbsp;and&amp;nbsp;&lt;a href="http://twitter.com/#!/CycleSurrey"&gt;@CycleSurrey&lt;/a&gt;); presumably travelling with the race or being fed data from someone who was that were Tweeting throughout the race.  Given the dearth of information, following these people or &amp;nbsp;the searches &lt;a href="http://twitter.com/#!/search?q=%23CycleClassic"&gt;#CycleClassic&lt;/a&gt;&amp;nbsp;and/or&amp;nbsp;&lt;a href="http://twitter.com/#!/search?q=%23testevent"&gt;#testevent&lt;/a&gt;&amp;nbsp;was the the only way to find out anything.&lt;br /&gt;
&lt;br /&gt;
I suspect it's how most people were informed of the result; Mark Cavendish won!  I was wondering if this was the first time for a major&amp;nbsp;sporting event&amp;nbsp;(unless you're from the BBC) &amp;nbsp;that the majority of spectators 'watched' via Twitter, i.e. Twittating or should that be Spectwiting!  Now this doesn't differ too much from receiving text message updates to a sporting event or just checking the score except that this was largely unofficial and the only available channel. &amp;nbsp;In addition the community aspect of Twitter generated&amp;nbsp;an almost a stadium like atmosphere albeit virtual.&lt;br /&gt;
&lt;br /&gt;
The lack of live coverage also meant that in addition to no information there were no pictures either.  However a lot of the tweets had accompanying pictures and some videos.  Whilst not live TV it was something.  Even more interesting given the nature of the event: a cycle road race, it meant that the stream of &amp;nbsp;Tweets was actually charting the progress of the race.&lt;br /&gt;
&lt;br /&gt;
Thinking about this the natural extension is the possibility of broadcasting an event purely by the crowd on Twitter.  If there are enough people to cover a course and whatever lag Twitter; and mobile Internet access has doesn't interfere too much then as the race passes the current status along with images could be Tweeted. &lt;br /&gt;
&lt;br /&gt;
This stream could be consumed in real time by a special Twitter client that pulls it together chronologically and importantly will display pictures.  These wouldn't be continuous motion (well they could be if the intervals between each Tweeter were short enought) but would give a visual sense of the event. &amp;nbsp;This is essentially newspaper reporting but in near real time as opposed to live TV which is real time.&lt;br /&gt;
&lt;br /&gt;
One other thought on the basis that the highlights won't be available for a week is that it should be possible to write a program to consume the previously mentioned Twitter searches and pull these together along with the attached pictures and videos to create some sort of&amp;nbsp;watch-able&amp;nbsp;programme.&lt;img src="http://feeds.feedburner.com/~r/CCWindowsOtherRamblings/~4/-R5tm8RkTWw" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/CCWindowsOtherRamblings/~3/-R5tm8RkTWw/spectating-with-twitter-twittating-or.html</link><author>noreply@blogger.com (Pete Barber)</author><thr:total>0</thr:total><feedburner:origLink>http://petebarber.blogspot.com/2011/08/spectating-with-twitter-twittating-or.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-2918646278142295649.post-575129821938488005</guid><pubDate>Thu, 04 Aug 2011 20:08:00 +0000</pubDate><atom:updated>2011-08-04T13:12:15.979-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">"Computer humour" joke UDP</category><title>A couple of computing jokes</title><description>&lt;span class="Apple-style-span"&gt;The problem with a UDP joke is that you have no idea if people get it. (from&amp;nbsp;&lt;/span&gt;&lt;span class="Apple-style-span" style="color: #444444; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; line-height: 17px;"&gt;&lt;a class="screen-name screen-name-fearthecowboy pill" href="http://twitter.com/#!/fearthecowboy" style="color: #0084b4; font-weight: bold; margin-bottom: 0px; margin-left: 0px; margin-right: 2px; margin-top: 0px; padding-bottom: 2px; padding-left: 0px; padding-right: 0px; padding-top: 2px; text-decoration: none;"&gt;&lt;strong style="font-weight: bold; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px; padding-bottom: 0px; padding-left: 0px; padding-right: 0px; padding-top: 0px;"&gt;&lt;span class="Apple-style-span" style="font-size: x-small;"&gt;@fearthecowboy&lt;/span&gt;&lt;/strong&gt;&lt;/a&gt;&lt;/span&gt;&lt;span class="Apple-style-span"&gt;)&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
A SQL query walks into a bar, goes up to a couple of tables and says, "Can I join you?".&lt;img src="http://feeds.feedburner.com/~r/CCWindowsOtherRamblings/~4/4-A1XiHW95k" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/CCWindowsOtherRamblings/~3/4-A1XiHW95k/couple-of-computing-jokes.html</link><author>noreply@blogger.com (Pete Barber)</author><thr:total>0</thr:total><feedburner:origLink>http://petebarber.blogspot.com/2011/08/couple-of-computing-jokes.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-2918646278142295649.post-2597245588773164653</guid><pubDate>Tue, 26 Jul 2011 21:16:00 +0000</pubDate><atom:updated>2011-07-26T14:16:59.744-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">CodeProject</category><category domain="http://www.blogger.com/atom/ns#">Fluent</category><category domain="http://www.blogger.com/atom/ns#">Attribute</category><category domain="http://www.blogger.com/atom/ns#">C#</category><category domain="http://www.blogger.com/atom/ns#">NUnit</category><category domain="http://www.blogger.com/atom/ns#">CustomAttribute</category><category domain="http://www.blogger.com/atom/ns#">TDD</category><category domain="http://www.blogger.com/atom/ns#">Fluent Programming</category><title>Unit Testing C# Custom Attributes with NUnit Part 3</title><description>During&amp;nbsp;&lt;a href="http://petebarber.blogspot.com/2011/07/unit-testing-c-custom-attributes-with_26.html"&gt;Unit Testing C# Custom Attributes with NUnit Part 2&lt;/a&gt;&amp;nbsp;where the Assertions were converted from the &lt;a href="http://www.nunit.org/index.php?p=assertions&amp;amp;r=2.5.10"&gt;Classic &lt;/a&gt;to the &lt;a href="http://www.nunit.org/index.php?p=constraintModel&amp;amp;r=2.5.10"&gt;Constraint&lt;/a&gt;&amp;nbsp;model it was simply a process of replacing&lt;br /&gt;
&lt;br /&gt;
Assert.&amp;lt;SomeAssertion&amp;gt;(&amp;lt;object&amp;gt;)&lt;br /&gt;
&lt;br /&gt;
with&lt;br /&gt;
&lt;br /&gt;
Assert.That(&amp;lt;object&amp;gt;, &lt;b&gt;Is&lt;/b&gt;.&amp;lt;SomeAssertion&amp;gt;)&lt;br /&gt;
&lt;br /&gt;
The key thing being the 'Is' object that houses all the original assertions used. &amp;nbsp;Whilst doing this I came across the 'Has' object. &amp;nbsp;This doesn't appear in the documentation until about halfway when &lt;a href="http://www.nunit.org/index.php?p=collectionConstraints&amp;amp;r=2.5.10"&gt;collections&lt;/a&gt;&amp;nbsp;are covered. &amp;nbsp;Not mentioned at all in the documentation is the method Has.Attribute&amp;lt;&lt;i&gt;AttributeType&lt;/i&gt;&amp;gt; which tests whether an attribute (custom or otherwise) is present on the object being tested. &amp;nbsp; For the current method this is simply:&lt;br /&gt;
&lt;br /&gt;
&lt;pre style="color: black;"&gt;&lt;span style="color: #2b91af;"&gt;Assert&lt;/span&gt;.That(&lt;span style="color: #2b91af;"&gt;MethodBase&lt;/span&gt;.GetCurrentMethod(), &lt;span style="color: #2b91af;"&gt;Has&lt;/span&gt;.Attribute&amp;lt;&lt;span style="color: #2b91af;"&gt;FunkyAttribute&lt;/span&gt;&amp;gt;());&lt;/pre&gt;&lt;br /&gt;
Even better,&amp;nbsp;having obtained the Attribute (if not present the assertion will fail) it too can be tested. &amp;nbsp;The important aspect here is that it contains a specific property which can easily be tested in the same statement by appending '.Property(&amp;lt;PropertyName&amp;gt;)' in&amp;nbsp;a&amp;nbsp;&lt;a href="http://en.wikipedia.org/wiki/Fluent_interface"&gt;Fluent&lt;/a&gt;&amp;nbsp;style to give:&lt;br /&gt;
&lt;br /&gt;
&lt;pre style="color: black;"&gt;&lt;span style="color: #2b91af;"&gt;Assert&lt;/span&gt;.That(&lt;span style="color: #2b91af;"&gt;MethodBase&lt;/span&gt;.GetCurrentMethod(), &lt;span style="color: #2b91af;"&gt;Has&lt;/span&gt;.Attribute&amp;lt;&lt;span style="color: #2b91af;"&gt;FunkyAttribute&lt;/span&gt;&amp;gt;().Property(&lt;span style="color: #a31515;"&gt;"FunkyName"&lt;/span&gt;));&lt;/pre&gt;&lt;br /&gt;
The next is to test whether this property contains the correct value. &amp;nbsp;This can be obtained in a&amp;nbsp;similar&amp;nbsp;way&amp;nbsp;by further appending '.EqualTo(&amp;lt;SomeValue&amp;gt;)' to give:&lt;br /&gt;
&lt;br /&gt;
&lt;pre style="color: black;"&gt;&lt;span style="color: #2b91af;"&gt;Assert&lt;/span&gt;.That(&lt;span style="color: #2b91af;"&gt;MethodBase&lt;/span&gt;.GetCurrentMethod(), &lt;span style="color: #2b91af;"&gt;Has&lt;/span&gt;.Attribute&amp;lt;&lt;span style="color: #2b91af;"&gt;FunkyAttribute&lt;/span&gt;&amp;gt;().Property(&lt;span style="color: #a31515;"&gt;"FunkyName"&lt;/span&gt;).EqualTo(&lt;span style="color: #a31515;"&gt;"RipSnorter"&lt;/span&gt;));&lt;/pre&gt;&lt;br /&gt;
In a single statement tests for the presence of the Custom Attribute, a property of it and finally that property's value have been conducted. &amp;nbsp;This is considerably shorter than both the&amp;nbsp;&lt;a href="http://petebarber.blogspot.com/2011/07/unit-testing-c-custom-attributes-with.html"&gt;original&lt;/a&gt;&amp;nbsp;and &lt;a href="http://petebarber.blogspot.com/2011/07/unit-testing-c-custom-attributes-with_26.html"&gt;second&lt;/a&gt;&amp;nbsp;examples which required the reflection code to obtain the Custom Attribute followed by 3&amp;nbsp;separate&amp;nbsp;assertions. &lt;br /&gt;
&lt;br /&gt;
This does not meet the original testing requirements which were:&lt;br /&gt;
&lt;br /&gt;
&lt;ul style="color: #222222; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: 13px; line-height: 1.4; margin-bottom: 0.5em; margin-left: 0px; margin-right: 0px; margin-top: 0.5em; padding-bottom: 0px; padding-left: 2.5em; padding-right: 2.5em; padding-top: 0px;"&gt;&lt;li style="margin-bottom: 0.25em; margin-left: 0px; margin-right: 0px; margin-top: 0px; padding-bottom: 0px; padding-left: 0px; padding-right: 0px; padding-top: 0px; text-indent: 0px;"&gt;A Custom Attribute of the correct type existed on the test method.&lt;/li&gt;
&lt;li style="margin-bottom: 0.25em; margin-left: 0px; margin-right: 0px; margin-top: 0px; padding-bottom: 0px; padding-left: 0px; padding-right: 0px; padding-top: 0px; text-indent: 0px;"&gt;That the property to be tested of the Custom Attribute had the expected name.&lt;/li&gt;
&lt;li style="margin-bottom: 0.25em; margin-left: 0px; margin-right: 0px; margin-top: 0px; padding-bottom: 0px; padding-left: 0px; padding-right: 0px; padding-top: 0px; text-indent: 0px;"&gt;That the property&amp;nbsp;to be tested of the Custom Attribute&amp;nbsp;had the correct type.&lt;/li&gt;
&lt;li style="margin-bottom: 0.25em; margin-left: 0px; margin-right: 0px; margin-top: 0px; padding-bottom: 0px; padding-left: 0px; padding-right: 0px; padding-top: 0px; text-indent: 0px;"&gt;That the value of property to be tested of the Custom Attribute&amp;nbsp;could be set.&lt;/li&gt;
&lt;li style="margin-bottom: 0.25em; margin-left: 0px; margin-right: 0px; margin-top: 0px; padding-bottom: 0px; padding-left: 0px; padding-right: 0px; padding-top: 0px; text-indent: 0px;"&gt;That the value of property to be tested of the Custom Attribute&amp;nbsp;could be obtained.&lt;/li&gt;
&lt;li style="margin-bottom: 0.25em; margin-left: 0px; margin-right: 0px; margin-top: 0px; padding-bottom: 0px; padding-left: 0px; padding-right: 0px; padding-top: 0px; text-indent: 0px;"&gt;That the property to be tested of the Custom Attribute&amp;nbsp;had the expected value.&lt;/li&gt;
&lt;/ul&gt;&lt;div&gt;&lt;span class="Apple-style-span" style="color: #222222; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: x-small;"&gt;&lt;span class="Apple-style-span" style="line-height: 18px;"&gt;&lt;br /&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/div&gt;&lt;div&gt;Remaining are setting, getting (obtain) and type checking.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;
It turns out that that the tests for being able to set and get the property are not needed as if a property is created on a Custom Attribute then a getter and setter must be supplied. &amp;nbsp;The property can be private but if this is the case then it cannot be set as part of the Attribute syntax. &amp;nbsp;If the former condition is not met or an attempt is made to set a private property then a compilation error will occur.&lt;br /&gt;
&lt;br /&gt;
&lt;/div&gt;&lt;div&gt;Whilst successfully testing the property's value would suggest a type match this it not strictly the case as if the expected value can be converted to the type of the property then the test will be successful, e.g.&lt;/div&gt;&lt;br /&gt;
&lt;pre style="color: black;"&gt;&lt;span style="color: #2b91af;"&gt;Assert&lt;/span&gt;.That(&lt;span style="color: #2b91af;"&gt;MethodBase&lt;/span&gt;.GetCurrentMethod(), &lt;span style="color: #2b91af;"&gt;Has&lt;/span&gt;.Attribute&amp;lt;&lt;span style="color: #2b91af;"&gt;FunkyAttribute&lt;/span&gt;&amp;gt;().Property(&lt;span style="color: #a31515;"&gt;"SettingOne"&lt;/span&gt;).EqualTo(77.0));&lt;/pre&gt;&lt;br /&gt;
&lt;div&gt;which causes the double to be converted to an int. &amp;nbsp;It wouldn't be possible to actually set 'SettingOne' to a double value when using the attribute as this&amp;nbsp;will fail to compile, e.g.&lt;br /&gt;
&lt;br /&gt;
&lt;pre style="color: black;"&gt;[&lt;span style="color: #2b91af;"&gt;Funky&lt;/span&gt;(SettingOne = 77.9)]&lt;/pre&gt;&lt;br /&gt;
As this is testing an implementation of a Custom Attribute rather than its&amp;nbsp;application then it is necessary to check that the implementation hasn't been&amp;nbsp;accidentally&amp;nbsp;changed to allow this in which case the previous&amp;nbsp;erroneous test would pass. &amp;nbsp;This means testing the type.&lt;br /&gt;
&lt;br /&gt;
Unfortunately this is where the Fluent interface of NUnit's Constraint model falls downs a little as it's not possible to perform multiple tests on the same initial subject which in this case is the&amp;nbsp;&lt;a href="http://msdn.microsoft.com/en-us/library/system.reflection.methodbase.aspx"&gt;MethodBase&lt;/a&gt;&amp;nbsp;returned from the &lt;i&gt;static &lt;/i&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/system.reflection.methodbase.getcurrentmethod.aspx"&gt;MethodBase.GetCurrentMethod()&lt;/a&gt;&amp;nbsp;call. &amp;nbsp;Therefore an additional assertion is required:&lt;br /&gt;
&lt;br /&gt;
&lt;pre style="color: black;"&gt;&lt;span style="color: #2b91af;"&gt;Assert&lt;/span&gt;.That(&lt;span style="color: #2b91af;"&gt;MethodBase&lt;/span&gt;.GetCurrentMethod(), &lt;span style="color: #2b91af;"&gt;Has&lt;/span&gt;.Attribute&amp;lt;&lt;span style="color: #2b91af;"&gt;FunkyAttribute&lt;/span&gt;&amp;gt;().Property(&lt;span style="color: #a31515;"&gt;"SettingOne"&lt;/span&gt;).TypeOf&amp;lt;&lt;span style="color: blue;"&gt;int&lt;/span&gt;&amp;gt;());&lt;/pre&gt;&lt;br /&gt;
&lt;/div&gt;&lt;div style="margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px;"&gt;This means the original example can be reduced to the following:&lt;/div&gt;&lt;br /&gt;
&lt;pre style="color: black;"&gt;[&lt;span style="color: #2b91af;"&gt;Test&lt;/span&gt;]
&lt;span style="color: green;"&gt;//[Funky(FunkyName = "RipSnorter")]&lt;/span&gt;&lt;span style="color: blue;"&gt;
public void&lt;/span&gt; TestThatNameIsRipSnorter()
{
 &lt;span style="color: #2b91af;"&gt;Assert&lt;/span&gt;.That(&lt;span style="color: #2b91af;"&gt;MethodBase&lt;/span&gt;.GetCurrentMethod(), &lt;span style="color: #2b91af;"&gt;Has&lt;/span&gt;.Attribute&amp;lt;&lt;span style="color: #2b91af;"&gt;FunkyAttribute&lt;/span&gt;&amp;gt;().Property(&lt;span style="color: #a31515;"&gt;"FunkyName"&lt;/span&gt;).EqualTo(&lt;span style="color: #a31515;"&gt;"RipSnorter"&lt;/span&gt;));
 &lt;span style="color: #2b91af;"&gt;Assert&lt;/span&gt;.That(&lt;span style="color: #2b91af;"&gt;MethodBase&lt;/span&gt;.GetCurrentMethod(), &lt;span style="color: #2b91af;"&gt;Has&lt;/span&gt;.Attribute&amp;lt;&lt;span style="color: #2b91af;"&gt;FunkyAttribute&lt;/span&gt;&amp;gt;().Property(&lt;span style="color: #a31515;"&gt;"FunkyName"&lt;/span&gt;).TypeOf&amp;lt;&lt;span style="color: blue;"&gt;string&lt;/span&gt;&amp;gt;());
}

[&lt;span style="color: #2b91af;"&gt;Test&lt;/span&gt;]
[&lt;span style="color: #2b91af;"&gt;Funky&lt;/span&gt;(SettingOne = 77)]
&lt;span style="color: blue;"&gt;public void&lt;/span&gt; TestThatSettingOneIs77()
{
 &lt;span style="color: green;"&gt;// Two asserts&lt;/span&gt;&lt;span style="color: #2b91af;"&gt;
 Assert&lt;/span&gt;.That(&lt;span style="color: #2b91af;"&gt;MethodBase&lt;/span&gt;.GetCurrentMethod(), 
&lt;span style="color: #2b91af;"&gt;             Has&lt;/span&gt;.Attribute&amp;lt;&lt;span style="color: #2b91af;"&gt;FunkyAttribute&lt;/span&gt;&amp;gt;().Property(&lt;span style="color: #a31515;"&gt;"SettingOne"&lt;/span&gt;).EqualTo(77));
 &lt;span style="color: #2b91af;"&gt;Assert&lt;/span&gt;.That(&lt;span style="color: #2b91af;"&gt;MethodBase&lt;/span&gt;.GetCurrentMethod(), 
&lt;span style="color: #2b91af;"&gt;             Has&lt;/span&gt;.Attribute&amp;lt;&lt;span style="color: #2b91af;"&gt;FunkyAttribute&lt;/span&gt;&amp;gt;().Property(&lt;span style="color: #a31515;"&gt;"SettingOne"&lt;/span&gt;).TypeOf&amp;lt;&lt;span style="color: blue;"&gt;int&lt;/span&gt;&amp;gt;());

 &lt;span style="color: green;"&gt;// Use of '.And'.  &lt;/span&gt;&lt;span style="color: darkblue;"&gt;Note the trailing '.'&lt;/span&gt;&lt;span style="color: #2b91af;"&gt;
 Assert&lt;/span&gt;.That(&lt;span style="color: #2b91af;"&gt;MethodBase&lt;/span&gt;.GetCurrentMethod(), 
&lt;span style="color: #2b91af;"&gt;             Has&lt;/span&gt;.Attribute&amp;lt;&lt;span style="color: #2b91af;"&gt;FunkyAttribute&lt;/span&gt;&amp;gt;().Property(&lt;span style="color: #a31515;"&gt;"SettingOne"&lt;/span&gt;).TypeOf&amp;lt;&lt;span style="color: blue;"&gt;int&lt;/span&gt;&amp;gt;().
             And.Attribute&amp;lt;&lt;span style="color: #2b91af;"&gt;FunkyAttribute&lt;/span&gt;&amp;gt;().Property(&lt;span style="color: #a31515;"&gt;"SettingOne"&lt;/span&gt;).EqualTo(77));&lt;/pre&gt;&lt;pre style="color: black;"&gt;&lt;span style="color: green;"&gt;// Use of overloaded '&amp;amp;'&lt;/span&gt;&lt;span style="color: #2b91af;"&gt;
 Assert&lt;/span&gt;.That(&lt;span style="color: #2b91af;"&gt;MethodBase&lt;/span&gt;.GetCurrentMethod(), 
&lt;span style="color: #2b91af;"&gt;             Has&lt;/span&gt;.Attribute&amp;lt;&lt;span style="color: #2b91af;"&gt;FunkyAttribute&lt;/span&gt;&amp;gt;().Property(&lt;span style="color: #a31515;"&gt;"SettingOne"&lt;/span&gt;).TypeOf&amp;lt;&lt;span style="color: blue;"&gt;int&lt;/span&gt;&amp;gt;()
           &amp;amp; &lt;span style="color: #2b91af;"&gt;Has&lt;/span&gt;.Attribute&amp;lt;&lt;span style="color: #2b91af;"&gt;FunkyAttribute&lt;/span&gt;&amp;gt;().Property(&lt;span style="color: #a31515;"&gt;"SettingOne"&lt;/span&gt;).EqualTo(77));
}&lt;/pre&gt;&lt;br /&gt;
with the Custom Attribute definition remaining as&lt;br /&gt;
&lt;br /&gt;
&lt;pre style="color: black;"&gt;&lt;span style="color: blue;"&gt;public class&lt;/span&gt;&lt;span style="color: #2b91af;"&gt; FunkyAttribute&lt;/span&gt; : &lt;span style="color: #2b91af;"&gt;Attribute&lt;/span&gt;
{
 &lt;span style="color: blue;"&gt;public int&lt;/span&gt; SettingOne { &lt;span style="color: blue;"&gt;get&lt;/span&gt;; &lt;span style="color: blue;"&gt;set&lt;/span&gt;; }
 &lt;span style="color: blue;"&gt;public string&lt;/span&gt; FunkyName { &lt;span style="color: blue;"&gt;get&lt;/span&gt;; &lt;span style="color: blue;"&gt;set&lt;/span&gt;; }
}&lt;/pre&gt;&lt;pre style="color: black;"&gt;&lt;/pre&gt;&lt;pre style="color: black;"&gt;&lt;span class="Apple-style-span" style="font-family: Arial, Helvetica, sans-serif;"&gt;&lt;span class="Apple-style-span" style="white-space: normal;"&gt;In the &lt;/span&gt;&lt;i style="color: black; white-space: normal;"&gt;TestSettingOneIs77&lt;/i&gt;&lt;span class="Apple-style-span" style="white-space: normal;"&gt;&amp;nbsp;method the need for two separate assertions has been slightly improved upon. &amp;nbsp;This is by using the 'And' method which is of the Fluent style. &amp;nbsp;The final assertion is exactly the same as the previous but just&amp;nbsp;demonstrates&amp;nbsp;the overloaded '&amp;amp;' syntax instead. &amp;nbsp;&lt;/span&gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre&gt;&lt;span class="Apple-style-span" style="white-space: normal;"&gt;&lt;span class="Apple-style-span" style="font-family: Arial, Helvetica, sans-serif;"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre&gt;&lt;span class="Apple-style-span" style="white-space: normal;"&gt;&lt;span class="Apple-style-span" style="font-family: Arial, Helvetica, sans-serif;"&gt;I don't think either of these styles is particularly better than the two line equivalent as they both require two calls to obtain the Custom Attribute; one for each test. &amp;nbsp;However, using NUnit's Constraint model coupled with Fluent interface reduces the required code dramatically so is worthwhile. &amp;nbsp;Additionally I'm not sure if the Classic model actually allows Attributes to be obtained. &amp;nbsp;&lt;/span&gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre&gt;&lt;span class="Apple-style-span" style="white-space: normal;"&gt;&lt;span class="Apple-style-span" style="font-family: Arial, Helvetica, sans-serif;"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre&gt;&lt;span class="Apple-style-span" style="white-space: normal;"&gt;&lt;span class="Apple-style-span" style="font-family: Arial, Helvetica, sans-serif;"&gt;A test per-property on a Custom Attribute is probably also&amp;nbsp;desirable&amp;nbsp;but there's nothing stopping you combining all the individual property tests into a single assertion by the use of &amp;nbsp;'.And.HasAttribute().Property().EqualTo()'. &amp;nbsp;One of these would be required &amp;nbsp;for each of the remaining properties along with a&amp;nbsp;similar one for the type check. &amp;nbsp;A test per-property is more readable.&lt;/span&gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre&gt;&lt;span class="Apple-style-span" style="white-space: normal;"&gt;&lt;span class="Apple-style-span" style="font-family: Arial, Helvetica, sans-serif;"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="color: black;"&gt;&lt;span class="Apple-style-span" style="white-space: normal;"&gt;&lt;span class="Apple-style-span" style="font-family: Arial, Helvetica, sans-serif;"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="color: black;"&gt;&lt;/pre&gt;&lt;pre style="color: black;"&gt;&lt;span class="Apple-style-span" style="font-family: Arial, Helvetica, sans-serif; white-space: normal;"&gt;I think I'm done for a while on this subject now!&lt;/span&gt;&lt;/pre&gt;&lt;img src="http://feeds.feedburner.com/~r/CCWindowsOtherRamblings/~4/W1WNNyncdRk" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/CCWindowsOtherRamblings/~3/W1WNNyncdRk/unit-testing-c-custom-attributes-with_1337.html</link><author>noreply@blogger.com (Pete Barber)</author><thr:total>0</thr:total><feedburner:origLink>http://petebarber.blogspot.com/2011/07/unit-testing-c-custom-attributes-with_1337.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-2918646278142295649.post-5768903268749810976</guid><pubDate>Tue, 26 Jul 2011 19:29:00 +0000</pubDate><atom:updated>2012-02-20T10:43:24.025-08:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">CodeProject</category><category domain="http://www.blogger.com/atom/ns#">Fluent</category><category domain="http://www.blogger.com/atom/ns#">Attribute</category><category domain="http://www.blogger.com/atom/ns#">C#</category><category domain="http://www.blogger.com/atom/ns#">NUnit</category><category domain="http://www.blogger.com/atom/ns#">CustomAttribute</category><category domain="http://www.blogger.com/atom/ns#">TDD</category><category domain="http://www.blogger.com/atom/ns#">Fluent Programming</category><title>Unit Testing C# Custom Attributes with NUnit Part 2</title><description>I thought that my last post about&amp;nbsp;&lt;a href="http://petebarber.blogspot.com/2011/07/unit-testing-c-custom-attributes-with.html"&gt;Unit Test C# Custom Attributes with NUnit&lt;/a&gt;&amp;nbsp;was going to be the only one. &amp;nbsp;However, after reading more of the NUnit documentation I found that despite the&amp;nbsp;&lt;a href="http://www.nunit.org/index.php?p=quickStart&amp;amp;r=2.5.10"&gt;QuickStart&lt;/a&gt;&amp;nbsp;guide using the&amp;nbsp;&lt;a href="http://www.nunit.org/index.php?p=assertions&amp;amp;r=2.5.10"&gt;Classic&lt;/a&gt;&amp;nbsp;model the preferred model for working with NUnit is that of&amp;nbsp;&lt;a href="http://www.nunit.org/index.php?p=constraintModel&amp;amp;r=2.5.10"&gt;Constraints&lt;/a&gt;. &amp;nbsp;As such I thought I ought to change over to this which is what the updated code below shows.&lt;br /&gt;
&lt;br /&gt;
&lt;pre style="color: black;"&gt;[&lt;span style="color: #2b91af;"&gt;Test&lt;/span&gt;]
[&lt;span style="color: #2b91af;"&gt;Funky&lt;/span&gt;(FunkyName = &lt;span style="color: #a31515;"&gt;"RipSnorter"&lt;/span&gt;)]
&lt;span style="color: blue;"&gt;public void&lt;/span&gt; TestThatNameIsRipSnorter()
{
 TestAttrProperty&amp;lt;&lt;span style="color: #2b91af;"&gt;FunkyAttribute&lt;/span&gt;, &lt;span style="color: blue;"&gt;string&lt;/span&gt;&amp;gt;(&lt;span style="color: #2b91af;"&gt;MethodBase&lt;/span&gt;.GetCurrentMethod(), &lt;span style="color: #a31515;"&gt;"FunkyName"&lt;/span&gt;, &lt;span style="color: #a31515;"&gt;"RipSnorter"&lt;/span&gt;);
}

[&lt;span style="color: #2b91af;"&gt;Test&lt;/span&gt;]
[&lt;span style="color: #2b91af;"&gt;Funky&lt;/span&gt;(SettingOne = 77)]
&lt;span style="color: blue;"&gt;public void&lt;/span&gt; TestThatSettingOneIs77()
{
 TestAttrProperty&amp;lt;&lt;span style="color: #2b91af;"&gt;FunkyAttribute&lt;/span&gt;, &lt;span style="color: blue;"&gt;int&lt;/span&gt;&amp;gt;(&lt;span style="color: #2b91af;"&gt;MethodBase&lt;/span&gt;.GetCurrentMethod(), &lt;span style="color: #a31515;"&gt;"SettingOne"&lt;/span&gt;, 77);
}

&lt;span style="color: green;"&gt;// Helpers&lt;/span&gt;&lt;span style="color: blue;"&gt;
private void&lt;/span&gt; TestAttrProperty&amp;lt;TAttr, TProp&amp;gt;(&lt;span style="color: #2b91af;"&gt;MethodBase&lt;/span&gt; method, &lt;span style="color: blue;"&gt;string&lt;/span&gt; argName, TProp expectedValue)
{
 &lt;span style="color: blue;"&gt;object&lt;/span&gt;[] customAttributes = method.GetCustomAttributes(&lt;span style="color: blue;"&gt;typeof&lt;/span&gt;(TAttr), &lt;span style="color: blue;"&gt;false&lt;/span&gt;);

 &lt;span style="color: #2b91af;"&gt;Assert&lt;/span&gt;.AreEqual(1, customAttributes.Count());

 TAttr attr = (TAttr)customAttributes[0];

 &lt;span style="color: #2b91af;"&gt;PropertyInfo&lt;/span&gt; propertyInfo = attr.GetType().GetProperty(argName);

 &lt;span style="color: #2b91af;"&gt;Assert&lt;/span&gt;.That(propertyInfo, &lt;span style="color: #2b91af;"&gt;Is&lt;/span&gt;.Not.Null);
 &lt;span style="color: #2b91af;"&gt;Assert&lt;/span&gt;.That(propertyInfo.PropertyType, &lt;span style="color: #2b91af;"&gt;Is&lt;/span&gt;.EqualTo(&lt;span style="color: blue;"&gt;typeof&lt;/span&gt;(TProp)));
 &lt;span style="color: #2b91af;"&gt;Assert&lt;/span&gt;.That(propertyInfo.CanRead, &lt;span style="color: #2b91af;"&gt;Is&lt;/span&gt;.True);
 &lt;span style="color: #2b91af;"&gt;Assert&lt;/span&gt;.That(propertyInfo.CanWrite, &lt;span style="color: #2b91af;"&gt;Is&lt;/span&gt;.True);
 &lt;span style="color: #2b91af;"&gt;Assert&lt;/span&gt;.That(propertyInfo.GetValue(attr, &lt;span style="color: blue;"&gt;null&lt;/span&gt;), &lt;span style="color: #2b91af;"&gt;Is&lt;/span&gt;.EqualTo(expectedValue));
}&lt;/pre&gt;&lt;br /&gt;
The major change is rather that  than calling Assert.&amp;lt;Assertion&amp;gt; the Constraint model starts with specifying the object to be tested followed by the test. &amp;nbsp;Additionally, the Constraint model encourages a Fluent style interface, e.g.&lt;br /&gt;
&lt;br /&gt;
&lt;pre style="color: #2b91af;"&gt;Assert&lt;span style="color: black;"&gt;.IsNotNull(propertyInfo);&lt;/span&gt;&lt;/pre&gt;&lt;br /&gt;
becomes&lt;br /&gt;
&lt;br /&gt;
&lt;pre style="color: #2b91af;"&gt;Assert&lt;span style="color: black;"&gt;.That(propertyInfo, &lt;/span&gt;Is&lt;span style="color: black;"&gt;.Not.Null);&lt;/span&gt;&lt;/pre&gt;&lt;br /&gt;
I'm not going to explain the new model here (the above link has the details) but rather this is to just point out this style which can be&amp;nbsp;contrasted&amp;nbsp;to the sample in the previous post.&lt;br /&gt;
&lt;br /&gt;
In addition I&amp;nbsp;remembered&amp;nbsp;that a far easier way to obtain the current method metadata, i.e.&amp;nbsp;&lt;a href="http://msdn.microsoft.com/en-us/library/system.reflection.methodbase.aspx"&gt;MethodBase&lt;/a&gt;&amp;nbsp;was to simply to use reflection by calling&amp;nbsp;&lt;i&gt;MethodBase.GetCurrentMethod()&lt;/i&gt;&amp;nbsp;from &lt;i&gt;System.Reflection.&lt;/i&gt;&lt;br /&gt;
&lt;br /&gt;
You might also have noticed that in this updated example the &lt;i&gt;FunkyAttribute &lt;/i&gt;property &lt;i&gt;Name&lt;/i&gt; has become &lt;i&gt;FunkyName&lt;/i&gt;. &lt;br /&gt;
&lt;br /&gt;
&lt;pre style="color: black;"&gt;&lt;span style="color: blue;"&gt;public class&lt;/span&gt;&lt;span style="color: #2b91af;"&gt; FunkyAttribute&lt;/span&gt; : &lt;span style="color: #2b91af;"&gt;Attribute&lt;/span&gt;
{
 &lt;span style="color: blue;"&gt;public int&lt;/span&gt; SettingOne { &lt;span style="color: blue;"&gt;get&lt;/span&gt;; &lt;span style="color: blue;"&gt;set&lt;/span&gt;; }
 &lt;span style="color: blue;"&gt;public string&lt;/span&gt; FunkyName { &lt;span style="color: blue;"&gt;get&lt;/span&gt;; &lt;span style="color: blue;"&gt;set&lt;/span&gt;; }
}&lt;/pre&gt;&lt;br /&gt;
This was to&amp;nbsp;differentiate from the &lt;a href="http://msdn.microsoft.com/en-us/library/system.reflection.memberinfo.name.aspx"&gt;Name&lt;/a&gt;&amp;nbsp;property of the&amp;nbsp;&lt;a href="http://msdn.microsoft.com/en-us/library/8z852kf5.aspx"&gt;PropertyInfo&lt;/a&gt;&amp;nbsp;class.&lt;br /&gt;
&lt;br /&gt;
However, this isn't the main reason for part 2. &amp;nbsp;However, this post seems long enough already so the good bit will come in &lt;a href="http://petebarber.blogspot.com/2011/07/unit-testing-c-custom-attributes-with_1337.html"&gt;part 3&lt;/a&gt; which I'll write immediately so not too much waiting around. &amp;nbsp;A &lt;a href="http://petebarber.blogspot.com/2011/08/unit-testing-c-custom-attributes-with.html"&gt;part 4&lt;/a&gt; also emerged!&lt;img src="http://feeds.feedburner.com/~r/CCWindowsOtherRamblings/~4/-HOJCyKZzsg" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/CCWindowsOtherRamblings/~3/-HOJCyKZzsg/unit-testing-c-custom-attributes-with_26.html</link><author>noreply@blogger.com (Pete Barber)</author><thr:total>0</thr:total><feedburner:origLink>http://petebarber.blogspot.com/2011/07/unit-testing-c-custom-attributes-with_26.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-2918646278142295649.post-7655562342164992876</guid><pubDate>Wed, 20 Jul 2011 20:23:00 +0000</pubDate><atom:updated>2012-02-20T10:41:16.516-08:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">CodeProject</category><category domain="http://www.blogger.com/atom/ns#">Attribute</category><category domain="http://www.blogger.com/atom/ns#">C#</category><category domain="http://www.blogger.com/atom/ns#">.NET 2.0</category><category domain="http://www.blogger.com/atom/ns#">NUnit</category><category domain="http://www.blogger.com/atom/ns#">CustomAttribute</category><category domain="http://www.blogger.com/atom/ns#">TDD</category><title>Unit Testing C# Custom Attributes with NUnit</title><description>I've been experimenting with &lt;a href="http://en.wikipedia.org/wiki/Test-driven_development"&gt;TDD&lt;/a&gt;&amp;nbsp;and as usual I've seemed to pick a non-standard problem to start with. &amp;nbsp;In this case I was creating a new C# &lt;a href="http://msdn.microsoft.com/en-us/library/sw480ze8(v=vs.71).aspx"&gt;Custom Attribute&lt;/a&gt;&amp;nbsp;class, e.g.&lt;br /&gt;
&lt;br /&gt;
&lt;pre style="color: black;"&gt;&lt;span style="color: blue;"&gt;public class&lt;/span&gt;&lt;span style="color: #2b91af;"&gt; FunkyAttribute&lt;/span&gt; : &lt;span style="color: #2b91af;"&gt;Attribute&lt;/span&gt;
{
 &lt;span style="color: blue;"&gt;public int&lt;/span&gt; SettingOne { &lt;span style="color: blue;"&gt;get&lt;/span&gt;; &lt;span style="color: blue;"&gt;set&lt;/span&gt;; }
 &lt;span style="color: blue;"&gt;public string&lt;/span&gt; Name { &lt;span style="color: blue;"&gt;get&lt;/span&gt;; &lt;span style="color: blue;"&gt;set&lt;/span&gt;; }
}&lt;/pre&gt;&lt;br /&gt;
which would be used such as&lt;br /&gt;
&lt;br /&gt;
&lt;pre style="color: black;"&gt;[&lt;span style="color: #2b91af;"&gt;Funky&lt;/span&gt;(Name=&lt;span style="color: #a31515;"&gt;"SomeThingFunkierThanJust_f"&lt;/span&gt;)]
&lt;span style="color: blue;"&gt;public static int&lt;/span&gt; f() { &lt;span style="color: blue;"&gt;return&lt;/span&gt; 7; }&lt;/pre&gt;&lt;br /&gt;
Testing this is a little strange as rather than having a standard test method which invokes a method and asserts the result, e.g.&lt;br /&gt;
&lt;a name='more'&gt;&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;span class="Apple-style-span" style="font-family: monospace; white-space: pre;"&gt;[&lt;/span&gt;&lt;span class="Apple-style-span" style="font-family: monospace; white-space: pre;"&gt;&lt;span style="color: #2b91af;"&gt;Test&lt;/span&gt;&lt;/span&gt;&lt;span class="Apple-style-span" style="font-family: monospace; white-space: pre;"&gt;]&lt;/span&gt;&lt;br /&gt;
&lt;pre style="color: black;"&gt;&lt;span style="color: blue;"&gt;public void&lt;/span&gt; TestThat_f_Returns7()
{
 &lt;span style="color: #2b91af;"&gt;Assert&lt;/span&gt;.AreEqual(7, &lt;span style="color: red;"&gt;SomeClass&lt;/span&gt;.f());
}&lt;/pre&gt;&lt;br /&gt;
There is no method to call because an Attribute is applied to an element of the program such as the definition of &lt;i&gt;f()&lt;/i&gt; above. &amp;nbsp;In the end I settled on the following&lt;br /&gt;
&lt;br /&gt;
&lt;pre style="color: black;"&gt;&lt;span style="color: blue;"&gt;public class&lt;/span&gt;&lt;span style="color: #2b91af;"&gt; FunkyTester&lt;/span&gt;
{
 [&lt;span style="color: #2b91af;"&gt;Test&lt;/span&gt;]
 [&lt;span style="color: #2b91af;"&gt;Funky&lt;/span&gt;(Name=&lt;span style="color: #a31515;"&gt;"RipSnorter"&lt;/span&gt;)]
 &lt;span style="color: blue;"&gt;public void&lt;/span&gt; TestThatNameIsRipSnorter()
 {
  TestAttrProperty&amp;lt;&lt;span style="color: #2b91af;"&gt;FunkyAttribute&lt;/span&gt;, &lt;span style="color: blue;"&gt;string&lt;/span&gt;&amp;gt;(&lt;span style="color: blue;"&gt;new&lt;/span&gt;&lt;span style="color: #2b91af;"&gt; StackFrame&lt;/span&gt;().GetMethod(), &lt;span style="color: #a31515;"&gt;"Name"&lt;/span&gt;, &lt;span style="color: #a31515;"&gt;"RipSnorter"&lt;/span&gt;);
 }

 [&lt;span style="color: #2b91af;"&gt;Test&lt;/span&gt;]
 [&lt;span style="color: #2b91af;"&gt;Funky&lt;/span&gt;(SettingOne=77)]
 &lt;span style="color: blue;"&gt;public  void&lt;/span&gt; TestThatSettingOneIs77()
 {
  TestAttrProperty&amp;lt;&lt;span style="color: #2b91af;"&gt;FunkyAttribute&lt;/span&gt;, &lt;span style="color: blue;"&gt;int&lt;/span&gt;&amp;gt;(&lt;span style="color: blue;"&gt;new&lt;/span&gt;&lt;span style="color: #2b91af;"&gt; StackFrame&lt;/span&gt;().GetMethod(), &lt;span style="color: #a31515;"&gt;"SettingOne"&lt;/span&gt;, 77);
 }

 &lt;span style="color: green;"&gt;// Helpers&lt;/span&gt;&lt;span style="color: blue;"&gt;
 private void&lt;/span&gt; TestAttrProperty&amp;lt;TAttr, TProp&amp;gt;(&lt;span style="color: #2b91af;"&gt;MethodBase&lt;/span&gt; method, &lt;span style="color: blue;"&gt;string&lt;/span&gt; argName, TProp expectedValue)
 {
  &lt;span style="color: blue;"&gt;object&lt;/span&gt;[] customAttributes = method.GetCustomAttributes(&lt;span style="color: blue;"&gt;typeof&lt;/span&gt;(TAttr), &lt;span style="color: blue;"&gt;false&lt;/span&gt;);

  &lt;span style="color: #2b91af;"&gt;Assert&lt;/span&gt;.AreEqual(1, customAttributes.Count());

  TAttr attr = (TAttr)customAttributes[0];

  &lt;span style="color: #2b91af;"&gt;PropertyInfo&lt;/span&gt; propertyInfo = attr.GetType().GetProperty(argName);

  &lt;span style="color: #2b91af;"&gt;Assert&lt;/span&gt;.IsNotNull(propertyInfo);
  &lt;span style="color: #2b91af;"&gt;Assert&lt;/span&gt;.AreEqual(&lt;span style="color: blue;"&gt;typeof&lt;/span&gt; (TProp), propertyInfo.PropertyType);
  &lt;span style="color: #2b91af;"&gt;Assert&lt;/span&gt;.IsTrue(propertyInfo.CanRead);
  &lt;span style="color: #2b91af;"&gt;Assert&lt;/span&gt;.IsTrue(propertyInfo.CanWrite);
  &lt;span style="color: #2b91af;"&gt;Assert&lt;/span&gt;.AreEqual(expectedValue, (TProp)propertyInfo.GetValue(attr, &lt;span style="color: blue;"&gt;null&lt;/span&gt;));
 }
}&lt;/pre&gt;&lt;br /&gt;
This test class contains 2 test methods which are identified by the &lt;a href="http://www.nunit.org/"&gt;NUnit &lt;/a&gt;&lt;i&gt;[Test]&lt;/i&gt; attribute. &amp;nbsp;In addition there is the use of the &lt;i&gt;FunkyAttribute &lt;/i&gt;to be tested, i.e. &lt;i&gt;[Funky]&lt;/i&gt;. &amp;nbsp;The Custom Attribute is&amp;nbsp;fairly&amp;nbsp;simple with a default (parameterless) constructor and just two; differently typed properties both with a getter and a setter. &amp;nbsp;For each of these I wanted to check :&lt;br /&gt;
&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;A Custom Attribute of the correct type existed on the test method.&lt;/li&gt;
&lt;li&gt;That the property to be tested of the Custom Attribute had the expected name.&lt;/li&gt;
&lt;li&gt;That the property&amp;nbsp;to be tested of the Custom Attribute&amp;nbsp;had the correct type.&lt;/li&gt;
&lt;li&gt;That the value of property to be tested of the Custom Attribute&amp;nbsp;could be set.&lt;/li&gt;
&lt;li&gt;That the value of property to be tested of the Custom Attribute&amp;nbsp;could be obtained.&lt;/li&gt;
&lt;li&gt;That the property to be tested of the Custom Attribute&amp;nbsp;had the expected value.&lt;/li&gt;
&lt;/ul&gt;&lt;div&gt;&lt;br /&gt;
&lt;/div&gt;&lt;div&gt;As I wanted to perform these tests for each property of the Custom Attribute a helper method was called for which in this case is &lt;i&gt;TestAttrProperty&lt;/i&gt;. &amp;nbsp;This method is generic so can be used for any property of a Custom Attribute that has a public getter and setter. &amp;nbsp;It just takes a reference to an instance of the a method (which will always be a Test method) that the Custom Attribute is set on along with parameters for the property's name and its expected value. &amp;nbsp;The latter is a generic typed parameter (&lt;i&gt;TProp&lt;/i&gt;) along with the type of the actual Custom Attribute (&lt;i&gt;TAttr&lt;/i&gt;).&lt;/div&gt;&lt;div&gt;&lt;br /&gt;
&lt;/div&gt;&lt;div&gt;&lt;i&gt;TestAttrProperty()&lt;/i&gt; then obtains all the Custom Attributes instances matching the type of &lt;i&gt;TAttr&lt;/i&gt;. &amp;nbsp;There can only be zero or one; the success case being one! &amp;nbsp;By limiting the search to just the Custom Attribute type being tested this means that the NUnit &lt;i&gt;TestAttribute&lt;/i&gt; instance is not included which means no filtering of the results is required prior the tests.&amp;nbsp;Following that reflection is used to obtain the&amp;nbsp;&lt;a href="http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.aspx"&gt;PropertyInfo&lt;/a&gt;&amp;nbsp;of the property under test. &amp;nbsp;This is then used for execution the remaining of the tests.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;
&lt;/div&gt;&lt;div&gt;The &lt;a href="http://msdn.microsoft.com/en-us/library/system.reflection.methodinfo.aspx"&gt;MethodInfo&lt;/a&gt;&amp;nbsp;for the test method is easily obtained&amp;nbsp;&amp;nbsp;from the current stack frame from the System.Diagnostics namespace&lt;/div&gt;&lt;div&gt;&lt;br /&gt;
&lt;/div&gt;&lt;div&gt;Hopefully, this little snippet shows a simple generic way to test Custom Attributes with NUnit.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;
&lt;/div&gt;&lt;div&gt;A next step would be to add the ability to test that the Custom Attribute can be successful applied to data members.&lt;br /&gt;
&lt;br /&gt;
Wait, there's &lt;a href="http://petebarber.blogspot.com/2011/07/unit-testing-c-custom-attributes-with_26.html"&gt;more&lt;/a&gt;! &amp;nbsp;Following this parts &lt;a href="http://petebarber.blogspot.com/2011/07/unit-testing-c-custom-attributes-with_26.html"&gt;two&lt;/a&gt;, &lt;a href="http://petebarber.blogspot.com/2011/07/unit-testing-c-custom-attributes-with_1337.html"&gt;three &lt;/a&gt;and &lt;a href="http://petebarber.blogspot.com/2011/08/unit-testing-c-custom-attributes-with.html"&gt;four &lt;/a&gt;were written.&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/CCWindowsOtherRamblings/~4/L7EtHLAO5bE" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/CCWindowsOtherRamblings/~3/L7EtHLAO5bE/unit-testing-c-custom-attributes-with.html</link><author>noreply@blogger.com (Pete Barber)</author><thr:total>0</thr:total><feedburner:origLink>http://petebarber.blogspot.com/2011/07/unit-testing-c-custom-attributes-with.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-2918646278142295649.post-4392257202343896357</guid><pubDate>Mon, 18 Jul 2011 17:30:00 +0000</pubDate><atom:updated>2011-07-18T10:30:57.395-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">WPF</category><category domain="http://www.blogger.com/atom/ns#">Control</category><category domain="http://www.blogger.com/atom/ns#">Dependency Property</category><category domain="http://www.blogger.com/atom/ns#">User Control</category><category domain="http://www.blogger.com/atom/ns#">C#</category><title>A Simple WPF ComobBox based Brush Selector Control</title><description>Following the last Code Project &lt;a href="http://www.codeproject.com/KB/WPF/DPsInUserControl.aspx"&gt;article&lt;/a&gt;&amp;nbsp;I popped my stack and finished the original article that spawned it. &amp;nbsp;It's up on Code Project now and you can find it&amp;nbsp;&lt;a href="http://www.codeproject.com/KB/WPF/BrushSelectorArticle.aspx"&gt;here&lt;/a&gt;&amp;nbsp;or in long hand: from&amp;nbsp;&lt;a href="http://www.codeproject.com/KB/WPF/BrushSelectorArticle.aspx"&gt;http://www.codeproject.com/KB/WPF/BrushSelectorArticle.aspx&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
As the title suggests this one shows how to implement a simple control that allows a SolidColorBrush to be selected from a panel. &amp;nbsp;In fact it demonstrates how to do with using a Style and a UserControl and compares both approaches.&lt;img src="http://feeds.feedburner.com/~r/CCWindowsOtherRamblings/~4/q591bsB9ofs" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/CCWindowsOtherRamblings/~3/q591bsB9ofs/simple-wpf-comobbox-based-brush.html</link><author>noreply@blogger.com (Pete Barber)</author><thr:total>0</thr:total><feedburner:origLink>http://petebarber.blogspot.com/2011/07/simple-wpf-comobbox-based-brush.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-2918646278142295649.post-3808223201932059343</guid><pubDate>Tue, 12 Jul 2011 12:06:00 +0000</pubDate><atom:updated>2011-07-12T05:06:41.985-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">WPF</category><category domain="http://www.blogger.com/atom/ns#">Control</category><category domain="http://www.blogger.com/atom/ns#">encapsulation</category><category domain="http://www.blogger.com/atom/ns#">Dependency Property</category><category domain="http://www.blogger.com/atom/ns#">User Control</category><category domain="http://www.blogger.com/atom/ns#">C#</category><title>Exploring the use of Dependency Properties in WPF User Controls</title><description>I recently wrote my first WPF User Control.  This was mainly to customize a ComboBox as opposed to implement a completely new control.  As such, I needed to access some of the Dependency Properties (DPs) on the ComboBox.  Whilst it's possible to dip into the Content property of a UserControl this is somewhat unpleasant as it violates encapsulation.  The result was that I spent a bit of time experimenting with different ways to access these DPs whilst retaining the encapsulation of the embedded ComboBox.  This is all written up as a Code Project &lt;a href="http://www.codeproject.com/KB/WPF/DPsInUserControl.aspx"&gt;article&lt;/a&gt;.&lt;br /&gt;
&lt;br /&gt;
http://www.codeproject.com/KB/WPF/DPsInUserControl.aspx&lt;img src="http://feeds.feedburner.com/~r/CCWindowsOtherRamblings/~4/G10kNcsES0U" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/CCWindowsOtherRamblings/~3/G10kNcsES0U/exploring-use-of-dependency-properties.html</link><author>noreply@blogger.com (Pete Barber)</author><thr:total>0</thr:total><feedburner:origLink>http://petebarber.blogspot.com/2011/07/exploring-use-of-dependency-properties.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-2918646278142295649.post-8208269465814139336</guid><pubDate>Tue, 21 Jun 2011 21:20:00 +0000</pubDate><atom:updated>2011-06-21T14:22:20.990-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Dilbert</category><title>Am I living in Dilbert?</title><description>I was in a lift at work yesterday.  Unusually I was in the Sales building.  I entered the lift on the ground floor and pressed the button for the second floor.  The lift stopped at the first floor and a salesman entered.  He proceeded to ask me "are you going down?".  I replied "no" which I expected to be the end of the conversation, well at least concerning my very immediate travel plans.  However, this was not to be and you can probably guess what came next: "are you going up?".  A little to close to Dilbert for comfort:-)&lt;img src="http://feeds.feedburner.com/~r/CCWindowsOtherRamblings/~4/07ea62Peax4" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/CCWindowsOtherRamblings/~3/07ea62Peax4/am-i-living-in-dilbert.html</link><author>noreply@blogger.com (Pete Barber)</author><thr:total>0</thr:total><feedburner:origLink>http://petebarber.blogspot.com/2011/06/am-i-living-in-dilbert.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-2918646278142295649.post-3424729796460233790</guid><pubDate>Sun, 12 Jun 2011 16:27:00 +0000</pubDate><atom:updated>2011-06-12T09:27:52.543-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">MVVM</category><category domain="http://www.blogger.com/atom/ns#">event</category><category domain="http://www.blogger.com/atom/ns#">EventCommand</category><category domain="http://www.blogger.com/atom/ns#">WPF</category><category domain="http://www.blogger.com/atom/ns#">event to command</category><category domain="http://www.blogger.com/atom/ns#">C#</category><category domain="http://www.blogger.com/atom/ns#">Data Context</category><category domain="http://www.blogger.com/atom/ns#">DataContext</category><category domain="http://www.blogger.com/atom/ns#">start-up</category><category domain="http://www.blogger.com/atom/ns#">event-to-command pattern</category><category domain="http://www.blogger.com/atom/ns#">CodeProject</category><category domain="http://www.blogger.com/atom/ns#">SizeChanged</category><category domain="http://www.blogger.com/atom/ns#">EventToCommand</category><title>Getting WPF SizeChanged Events at start-up when using MVVM and DataContext</title><description>Like lots of people working with WPF I've been writing my own MVVM framework. &amp;nbsp;I started using this in an application I was writing. &amp;nbsp;One of the things it needed to do was obtain the dimensions of a Canvas object. &amp;nbsp;As such a subscription to the SizeChanged event was used. &amp;nbsp;The connection was formed using DataBinding to my implementation of an event-to-command mapper.&lt;br /&gt;
&lt;br /&gt;
The code below are the classes from the MVVM framework plus a sample application that demonstrates the problem. &amp;nbsp;This is just a button within a Canvas that when pressed pops up a dialog displaying the Canvas's dimensions.&lt;br /&gt;
&lt;br /&gt;
&lt;pre style="color: blue;"&gt;&amp;lt;&lt;span style="color: #a31515;"&gt;Window&lt;/span&gt;&lt;span style="color: red;"&gt; x&lt;/span&gt;:&lt;span style="color: red;"&gt;Class&lt;/span&gt;="SizeChangedEventTest2.MainWindow"&lt;span style="color: red;"&gt;
        xmlns&lt;/span&gt;="http://schemas.microsoft.com/winfx/2006/xaml/presentation"&lt;span style="color: red;"&gt;
        xmlns&lt;/span&gt;:&lt;span style="color: red;"&gt;x&lt;/span&gt;="http://schemas.microsoft.com/winfx/2006/xaml"&lt;span style="color: red;"&gt;
        Title&lt;/span&gt;="MainWindow"&lt;span style="color: red;"&gt; Height&lt;/span&gt;="350"&lt;span style="color: red;"&gt; Width&lt;/span&gt;="525"&lt;span style="color: red;"&gt;
  xmlns&lt;/span&gt;:&lt;span style="color: red;"&gt;mvvm&lt;/span&gt;="clr-namespace:PABLib.MVVM;assembly=PABLib.MVVM"&lt;span style="color: red;"&gt;
  xmlns&lt;/span&gt;:&lt;span style="color: red;"&gt;local&lt;/span&gt;="clr-namespace:SizeChangedEventTest2"&amp;gt;
 &amp;lt;&lt;span style="color: #a31515;"&gt;Canvas&lt;/span&gt;&lt;span style="color: red;"&gt; mvvm&lt;/span&gt;:&lt;span style="color: red;"&gt;EventCommand.Name&lt;/span&gt;="SizeChanged"&lt;span style="color: red;"&gt; 
   mvvm&lt;/span&gt;:&lt;span style="color: red;"&gt;EventCommand.Command&lt;/span&gt;="{&lt;span style="color: #a31515;"&gt;Binding&lt;/span&gt;&lt;span style="color: red;"&gt; SizeChanged&lt;/span&gt;}"&amp;gt;
  &amp;lt;&lt;span style="color: #a31515;"&gt;Button&lt;/span&gt;&lt;span style="color: red;"&gt; Content&lt;/span&gt;="Hello"&lt;span style="color: red;"&gt; Command&lt;/span&gt;="{&lt;span style="color: #a31515;"&gt;Binding&lt;/span&gt;&lt;span style="color: red;"&gt; PressMe&lt;/span&gt;}"/&amp;gt;
 &amp;lt;/&lt;span style="color: #a31515;"&gt;Canvas&lt;/span&gt;&amp;gt;
&amp;lt;/&lt;span style="color: #a31515;"&gt;Window&lt;/span&gt;&amp;gt;&lt;/pre&gt;&lt;br /&gt;
The code below shows my basic implementation of the command-to-event pattern. &amp;nbsp;I would have left it out but seeing but how it's used is crucial to the explanation of the problem and the solution.  Please note that EventCommand is actually in the PABLib.MVVM namespace as referred to in the XAML above but I've left it out of the C# to save space.&lt;br /&gt;
&lt;br /&gt;
&lt;pre style="color: black;"&gt;&lt;span style="color: blue;"&gt;public class&lt;/span&gt;&lt;span style="color: #2b91af;"&gt; EventCommand&lt;/span&gt;
{
 &lt;span style="color: blue;"&gt;public static&lt;/span&gt; DependencyProperty CommandProperty = DependencyProperty.RegisterAttached(&lt;span style="color: #a31515;"&gt;"Command"&lt;/span&gt;,
    &lt;span style="color: blue;"&gt;typeof&lt;/span&gt;(ICommand),
    &lt;span style="color: blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color: #2b91af;"&gt;EventCommand&lt;/span&gt;));

 &lt;span style="color: blue;"&gt;public static void&lt;/span&gt; SetCommand(DependencyObject target, ICommand value)
 {
  target.SetValue(&lt;span style="color: #2b91af;"&gt;EventCommand&lt;/span&gt;.CommandProperty, value);
 }

 &lt;span style="color: blue;"&gt;public static&lt;/span&gt; ICommand GetCommand(DependencyObject target)
 {
  &lt;span style="color: blue;"&gt;return&lt;/span&gt; (ICommand)target.GetValue(CommandProperty);
 }

 &lt;span style="color: blue;"&gt;public static&lt;/span&gt; DependencyProperty EventNameProperty = DependencyProperty.RegisterAttached(&lt;span style="color: #a31515;"&gt;"Name"&lt;/span&gt;,
    &lt;span style="color: blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color: blue;"&gt;string&lt;/span&gt;),
    &lt;span style="color: blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color: #2b91af;"&gt;EventCommand&lt;/span&gt;),
    &lt;span style="color: blue;"&gt;new&lt;/span&gt; FrameworkPropertyMetadata(NameChanged));

 &lt;span style="color: blue;"&gt;public static void&lt;/span&gt; SetName(DependencyObject target, &lt;span style="color: blue;"&gt;string&lt;/span&gt; value)
 {
  target.SetValue(&lt;span style="color: #2b91af;"&gt;EventCommand&lt;/span&gt;.EventNameProperty, value);
 }

 &lt;span style="color: blue;"&gt;public static string&lt;/span&gt; GetName(DependencyObject target)
 {
  &lt;span style="color: blue;"&gt;return&lt;/span&gt; (&lt;span style="color: blue;"&gt;string&lt;/span&gt;)target.GetValue(EventNameProperty);
 }

 &lt;span style="color: blue;"&gt;private static void&lt;/span&gt; NameChanged(DependencyObject target, DependencyPropertyChangedEventArgs e)
 {
  UIElement element = target &lt;span style="color: blue;"&gt;as&lt;/span&gt; UIElement;

  &lt;span style="color: blue;"&gt;if&lt;/span&gt; (element != &lt;span style="color: blue;"&gt;null&lt;/span&gt;)
  {
   &lt;span style="color: green;"&gt;// If we're putting in a new command and there wasn't one already hook the event&lt;/span&gt;&lt;span style="color: blue;"&gt;
   if&lt;/span&gt; ((e.NewValue != &lt;span style="color: blue;"&gt;null&lt;/span&gt;) &amp;amp;&amp;amp; (e.OldValue == &lt;span style="color: blue;"&gt;null&lt;/span&gt;))
   {
    EventInfo eventInfo = element.GetType().GetEvent((&lt;span style="color: blue;"&gt;string&lt;/span&gt;)e.NewValue);

    Delegate d = Delegate.CreateDelegate(eventInfo.EventHandlerType, &lt;span style="color: blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color: #2b91af;"&gt;EventCommand&lt;/span&gt;).GetMethod(&lt;span style="color: #a31515;"&gt;"Handler"&lt;/span&gt;, BindingFlags.NonPublic | BindingFlags.Static));

    eventInfo.AddEventHandler(element, d);
   }
   &lt;span style="color: green;"&gt;// If we're clearing the command and it wasn't already null unhook the event&lt;/span&gt;&lt;span style="color: blue;"&gt;
   else if&lt;/span&gt; ((e.NewValue == &lt;span style="color: blue;"&gt;null&lt;/span&gt;) &amp;amp;&amp;amp; (e.OldValue != &lt;span style="color: blue;"&gt;null&lt;/span&gt;))
   {
    EventInfo eventInfo = element.GetType().GetEvent((&lt;span style="color: blue;"&gt;string&lt;/span&gt;)e.OldValue);

    Delegate d = Delegate.CreateDelegate(eventInfo.EventHandlerType, &lt;span style="color: blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color: #2b91af;"&gt;EventCommand&lt;/span&gt;).GetMethod(&lt;span style="color: #a31515;"&gt;"Handler"&lt;/span&gt;));

    eventInfo.RemoveEventHandler(element, d);
   }
  }
 }

 &lt;span style="color: blue;"&gt;static void&lt;/span&gt; Handler(&lt;span style="color: blue;"&gt;object&lt;/span&gt; sender, EventArgs e)
 {
  UIElement element = (UIElement)sender;
  ICommand command = (ICommand)element.GetValue(&lt;span style="color: #2b91af;"&gt;EventCommand&lt;/span&gt;.CommandProperty);

  &lt;span style="color: blue;"&gt;var&lt;/span&gt; src = Tuple.Create(sender, e);

  &lt;span style="color: blue;"&gt;if&lt;/span&gt; (command != &lt;span style="color: blue;"&gt;null&lt;/span&gt; &amp;amp;&amp;amp; command.CanExecute(src) == &lt;span style="color: blue;"&gt;true&lt;/span&gt;)
   command.Execute(src);
 }
}&lt;/pre&gt;&lt;br /&gt;
The bindings used in the XAML refer to properties in Window's ViewModel.  This is defined as follows:&lt;br /&gt;
&lt;br /&gt;
&lt;pre style="color: black;"&gt;&lt;span style="color: blue;"&gt;class&lt;/span&gt;&lt;span style="color: #2b91af;"&gt; MainWindowViewModel&lt;/span&gt;
{
 &lt;span style="color: blue;"&gt;public&lt;/span&gt; ICommand PressMe { &lt;span style="color: blue;"&gt;get&lt;/span&gt;; &lt;span style="color: blue;"&gt;private set&lt;/span&gt;; }
 &lt;span style="color: blue;"&gt;public&lt;/span&gt; ICommand SizeChanged { &lt;span style="color: blue;"&gt;get&lt;/span&gt;; &lt;span style="color: blue;"&gt;private set&lt;/span&gt;; }

 &lt;span style="color: blue;"&gt;private int&lt;/span&gt; m_width = 0;
 &lt;span style="color: blue;"&gt;private int&lt;/span&gt; m_height = 0;

 &lt;span style="color: blue;"&gt;public&lt;/span&gt; MainWindowViewModel()
 {
  SizeChanged = &lt;span style="color: blue;"&gt;new&lt;/span&gt; PABLib.MVVM.RelayCommand&amp;lt;&lt;span style="color: blue;"&gt;object&lt;/span&gt;&amp;gt;((x) =&amp;gt;
  {
   SizeChangedEventArgs args = (SizeChangedEventArgs)((Tuple&amp;lt;&lt;span style="color: blue;"&gt;object&lt;/span&gt;, EventArgs&amp;gt;)x).Item2;
   m_width = (&lt;span style="color: blue;"&gt;int&lt;/span&gt;)args.NewSize.Width;
   m_height = (&lt;span style="color: blue;"&gt;int&lt;/span&gt;)args.NewSize.Height;
  });

  PressMe = &lt;span style="color: blue;"&gt;new&lt;/span&gt; PABLib.MVVM.RelayCommand&amp;lt;&lt;span style="color: blue;"&gt;object&lt;/span&gt;&amp;gt;((x) =&amp;gt;
  {
   MessageBox.Show(&lt;span style="color: blue;"&gt;string&lt;/span&gt;.Format(&lt;span style="color: #a31515;"&gt;"Width:{0}, Height:{1}"&lt;/span&gt;, m_width, m_height));
  });
 }
}&lt;/pre&gt;&lt;br /&gt;
For the sake of completeness here is the implementation of RelayCommand.  This is pretty much the basic version as originally created by Josh Smith.&lt;br /&gt;
&lt;br /&gt;
&lt;pre style="color: blue;"&gt;public class&lt;span style="color: #2b91af;"&gt; RelayCommand&lt;/span&gt;&lt;span style="color: black;"&gt;&amp;lt;T&amp;gt; : ICommand
{
 Action&amp;lt;T&amp;gt; _Execute { &lt;/span&gt;get&lt;span style="color: black;"&gt;; &lt;/span&gt;set&lt;span style="color: black;"&gt;; }
 Predicate&amp;lt;T&amp;gt; _CanExecute { &lt;/span&gt;get&lt;span style="color: black;"&gt;; &lt;/span&gt;set&lt;span style="color: black;"&gt;; }

 &lt;/span&gt;public&lt;span style="color: black;"&gt; RelayCommand(Action&amp;lt;T&amp;gt; execute, Predicate&amp;lt;T&amp;gt; canExecute = &lt;/span&gt;null&lt;span style="color: black;"&gt;)
 {
  _Execute = execute;
  _CanExecute = canExecute;
 }

 &lt;/span&gt;public bool&lt;span style="color: black;"&gt; CanExecute(&lt;/span&gt;object&lt;span style="color: black;"&gt; parameter)
 {
  &lt;/span&gt;if&lt;span style="color: black;"&gt; (_CanExecute == &lt;/span&gt;null&lt;span style="color: black;"&gt;)
   &lt;/span&gt;return true&lt;span style="color: black;"&gt;;
  &lt;/span&gt;else
   return&lt;span style="color: black;"&gt; _CanExecute((T)parameter);
 }

 &lt;/span&gt;public void&lt;span style="color: black;"&gt; Execute(&lt;/span&gt;object&lt;span style="color: black;"&gt; parameter)
 {
  &lt;/span&gt;if&lt;span style="color: black;"&gt; (_Execute != &lt;/span&gt;null&lt;span style="color: black;"&gt;)
   _Execute((T)parameter);
 }

 &lt;/span&gt;public event&lt;span style="color: black;"&gt; EventHandler CanExecuteChanged
 {
  &lt;/span&gt;add&lt;span style="color: black;"&gt; { CommandManager.RequerySuggested += &lt;/span&gt;value&lt;span style="color: black;"&gt;; }
  &lt;/span&gt;remove&lt;span style="color: black;"&gt; { CommandManager.RequerySuggested -= &lt;/span&gt;value&lt;span style="color: black;"&gt;; }
 }
}&lt;/span&gt;&lt;/pre&gt;&lt;br /&gt;
However, rather than just obtaining the dimensions when changed these were also required when the Canvas was first shown.&amp;nbsp;&amp;nbsp;The problem was that when using my MVVM framework it was only capturing events if the window was resized but not the initial sizing event. &amp;nbsp;For the sample app. this meant pressing the button the first time yielded results of 0 for both width and height. &amp;nbsp;I switched back to a conventional code-behind page approach as a sanity check.  This worked!&lt;br /&gt;
&lt;br /&gt;
At this point I started debugging the code more and discovered that the initial SizeChanged event was being fired and handled by the EventCommand code. &amp;nbsp;However, when it came to invoke the ICommand associated with the EventCommand this was null (in the Handler method of EventCommand). &amp;nbsp;The strange thing here was that that the event name had been successfully passed to EventCommand but the command hadn't. &amp;nbsp;Both of these are stored as Attached Properties (as is normal for event-to-command implementations). &lt;br /&gt;
&lt;br /&gt;
The difference between the event name and the command is that event name was a hard-coded string in the XAML whereas the command was being obtained using data binding to the main window's ViewModel. &amp;nbsp;Therefore the culprit appeared to be that the binding hadn't executed. &amp;nbsp;There was no problem with the validity of the binding as all the SizeChanged events bar the initial were being&amp;nbsp;received&amp;nbsp;and in debug mode VS was not reporting an issues with the binding.&lt;br /&gt;
&lt;br /&gt;
The only thing I could think of is that the initial event was being fired before the binding had been processed. &amp;nbsp;This was confirmed by extending the Attached Property definition for the CommandProperty to include an CommandChanged callback e,.g.&lt;br /&gt;
&lt;br /&gt;
&lt;pre style="color: black;"&gt;&lt;span style="color: blue;"&gt;public static&lt;/span&gt; DependencyProperty CommandProperty = DependencyProperty.RegisterAttached(&lt;span style="color: #a31515;"&gt;"Command"&lt;/span&gt;,
   &lt;span style="color: blue;"&gt;typeof&lt;/span&gt;(ICommand),
   &lt;span style="color: blue;"&gt;typeof&lt;/span&gt;(EventCommand),
   &lt;span style="color: blue;"&gt;new&lt;/span&gt; FrameworkPropertyMetadata(CommandChanged));

&lt;span style="color: blue;"&gt;private static void&lt;/span&gt; CommandChanged(DependencyObject target, DependencyPropertyChangedEventArgs e)
{
}&lt;/pre&gt;&lt;br /&gt;
A break point set on CommandChanged showed this wasn't invoked until after the event had fired confirming that the binding hadn't occurred.&lt;br /&gt;
&lt;br /&gt;
The way the ViewModel was set as the Data Context for the main Window was by removing the StartupUri element from the Application element in App.xaml.cs, e.g.&lt;br /&gt;
&lt;br /&gt;
&lt;pre style="color: blue;"&gt;&amp;lt;&lt;span style="color: #a31515;"&gt;Application&lt;/span&gt;&lt;span style="color: red;"&gt; x&lt;/span&gt;:&lt;span style="color: red;"&gt;Class&lt;/span&gt;="SizeChangedEventTest2.App"&lt;span style="color: red;"&gt;
             xmlns&lt;/span&gt;="http://schemas.microsoft.com/winfx/2006/xaml/presentation"&lt;span style="color: red;"&gt;
             xmlns&lt;/span&gt;:&lt;span style="color: red;"&gt;x&lt;/span&gt;="http://schemas.microsoft.com/winfx/2006/xaml"&amp;gt;
    &amp;lt;&lt;span style="color: #a31515;"&gt;Application.Resources&lt;/span&gt;&amp;gt;
         
    &amp;lt;/&lt;span style="color: #a31515;"&gt;Application.Resources&lt;/span&gt;&amp;gt;
&amp;lt;/&lt;span style="color: #a31515;"&gt;Application&lt;/span&gt;&amp;gt;&lt;/pre&gt;&lt;br /&gt;
and modifying App.xaml.cs to be:&lt;br /&gt;
&lt;br /&gt;
&lt;pre style="color: black;"&gt;&lt;span style="color: blue;"&gt;public partial class&lt;/span&gt;&lt;span style="color: #2b91af;"&gt; App&lt;/span&gt; : &lt;span style="color: #2b91af;"&gt;Application&lt;/span&gt;
{
 &lt;span style="color: blue;"&gt;protected override void&lt;/span&gt; OnStartup(&lt;span style="color: #2b91af;"&gt;StartupEventArgs&lt;/span&gt; e)
 {
  &lt;span style="color: blue;"&gt;base&lt;/span&gt;.OnStartup(e);

  &lt;span style="color: #2b91af;"&gt;MainWindowViewModel&lt;/span&gt; vm = &lt;span style="color: blue;"&gt;new&lt;/span&gt;&lt;span style="color: #2b91af;"&gt; MainWindowViewModel&lt;/span&gt;();
  &lt;span style="color: #2b91af;"&gt;MainWindow&lt;/span&gt; win = &lt;span style="color: blue;"&gt;new&lt;/span&gt;&lt;span style="color: #2b91af;"&gt; MainWindow&lt;/span&gt;();
  win.DataContext = vm;

  &lt;span style="color: blue;"&gt;this&lt;/span&gt;.MainWindow = win;
  &lt;span style="color: blue;"&gt;this&lt;/span&gt;.MainWindow.Show();
 }
}&lt;/pre&gt;&lt;br /&gt;
After some searching I noticed other projects setting the DataContext of the main window (to the ViewModel) in different ways. &amp;nbsp;This got me to thinking that perhaps the DataContext was being established too late.&lt;br /&gt;
&lt;br /&gt;
To address this App.xaml and App.xaml.cs were put back to their initial states and instead the ViewModel created and attached in the constructor for MainWindow, e.g.&lt;br /&gt;
&lt;br /&gt;
&lt;pre style='color:#000000'&gt;&lt;span style='color:#0000ff'&gt;public partial class&lt;/span&gt;&lt;span style='color:#2b91af'&gt; MainWindow&lt;/span&gt; : &lt;span style='color:#2b91af'&gt;Window&lt;/span&gt;
{
 &lt;span style='color:#0000ff'&gt;public&lt;/span&gt; MainWindow()
 {
  &lt;span style='color:#0000ff'&gt;this&lt;/span&gt;.DataContext = &lt;span style='color:#0000ff'&gt;new&lt;/span&gt;&lt;span style='color:#2b91af'&gt; MainWindowViewModel&lt;/span&gt;();

  InitializeComponent();
 }
}&lt;/pre&gt;&lt;br /&gt;
This fixed the problem! &amp;nbsp;As an experiment InitializeComponent() was moved to top of the constructor. &amp;nbsp;It stopped working. I didn't particularly like creating the ViewModel here so instead this code was removed and instead it was created in XAML as follows:&lt;br /&gt;
&lt;br /&gt;
&lt;pre style="color: blue;"&gt;&amp;lt;&lt;span style="color: #a31515;"&gt;Window&lt;/span&gt;&lt;span style="color: red;"&gt; x&lt;/span&gt;:&lt;span style="color: red;"&gt;Class&lt;/span&gt;="SizeChangedEventTest2.MainWindow"&lt;span style="color: red;"&gt;
        xmlns&lt;/span&gt;="http://schemas.microsoft.com/winfx/2006/xaml/presentation"&lt;span style="color: red;"&gt;
        xmlns&lt;/span&gt;:&lt;span style="color: red;"&gt;x&lt;/span&gt;="http://schemas.microsoft.com/winfx/2006/xaml"&lt;span style="color: red;"&gt;
        Title&lt;/span&gt;="MainWindow"&lt;span style="color: red;"&gt; Height&lt;/span&gt;="350"&lt;span style="color: red;"&gt; Width&lt;/span&gt;="525"&lt;span style="color: red;"&gt;
  xmlns&lt;/span&gt;:&lt;span style="color: red;"&gt;mvvm&lt;/span&gt;="clr-namespace:PABLib.MVVM;assembly=PABLib.MVVM"&lt;span style="color: red;"&gt;
  xmlns&lt;/span&gt;:&lt;span style="color: red;"&gt;local&lt;/span&gt;="clr-namespace:SizeChangedEventTest2"&amp;gt;
 &amp;lt;&lt;span style="color: #a31515;"&gt;Window.DataContext&lt;/span&gt;&amp;gt;
  &amp;lt;&lt;span style="color: #a31515;"&gt;local&lt;/span&gt;:&lt;span style="color: #a31515;"&gt;MainWindowViewModel&lt;/span&gt;/&amp;gt;
 &amp;lt;/&lt;span style="color: #a31515;"&gt;Window.DataContext&lt;/span&gt;&amp;gt;
 &amp;lt;&lt;span style="color: #a31515;"&gt;Canvas&lt;/span&gt;&lt;span style="color: red;"&gt; mvvm&lt;/span&gt;:&lt;span style="color: red;"&gt;EventCommand.Name&lt;/span&gt;="SizeChanged"&lt;span style="color: red;"&gt; mvvm&lt;/span&gt;:&lt;span style="color: red;"&gt;EventCommand.Command&lt;/span&gt;="{&lt;span style="color: #a31515;"&gt;Binding&lt;/span&gt;&lt;span style="color: red;"&gt; SizeChanged&lt;/span&gt;}"&amp;gt;
  &amp;lt;&lt;span style="color: #a31515;"&gt;Button&lt;/span&gt;&lt;span style="color: red;"&gt; Content&lt;/span&gt;="Hello"&lt;span style="color: red;"&gt; Command&lt;/span&gt;="{&lt;span style="color: #a31515;"&gt;Binding&lt;/span&gt;&lt;span style="color: red;"&gt; PressMe&lt;/span&gt;}"/&amp;gt;
 &amp;lt;/&lt;span style="color: #a31515;"&gt;Canvas&lt;/span&gt;&amp;gt;
&amp;lt;/&lt;span style="color: #a31515;"&gt;Window&lt;/span&gt;&amp;gt;&lt;/pre&gt;&lt;br /&gt;
This too worked. &amp;nbsp; This is where I'm currently at. &amp;nbsp;From this I conclude that it is critically important to make sure that a View's DataContext is properly created and attached before the underlying Window is displayed otherwise initial events will be missed.&lt;img src="http://feeds.feedburner.com/~r/CCWindowsOtherRamblings/~4/NXlBmgS_o9Q" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/CCWindowsOtherRamblings/~3/NXlBmgS_o9Q/getting-wpf-sizechanged-events-at-start.html</link><author>noreply@blogger.com (Pete Barber)</author><thr:total>12</thr:total><feedburner:origLink>http://petebarber.blogspot.com/2011/06/getting-wpf-sizechanged-events-at-start.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-2918646278142295649.post-7249190897915413124</guid><pubDate>Sun, 29 May 2011 08:40:00 +0000</pubDate><atom:updated>2011-05-29T01:48:05.268-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">IPad2</category><category domain="http://www.blogger.com/atom/ns#">tactile</category><category domain="http://www.blogger.com/atom/ns#">cover</category><title>Some thoughts on the iPad 2 actual feel</title><description>After using the demo iPad 2s in various shops I decided to take plunge and get one.  I'd been reading so much stuff on the Internet especially RSS feeds on the iPhone that I wanted a larger screen and to be able to read longer articles in comfort.&lt;br /&gt;
&lt;br /&gt;
This isn't a review but something I've noticed during my first week of ownership.  Along with the iPad I also bought one of the new covers.  When playing in the shops I'd only used the bare the metal version which was very pleasant to hold and manipulate.&lt;br /&gt;
&lt;br /&gt;
However, I am now rather averse to using the iPad without the cover.  I tend to hold the iPad in book mode and having the cover folded underneath the feel is of a natural fabric rather than metal.  This has almost turned the iPad from a machine into something else: almost a book or another kind of natural object.  It's an interesting sensory experience.&lt;br /&gt;
&lt;br /&gt;
I occasionally remove the cover, usually to quickly reattach it which shows the other neat aspect which is how easily it self-aligns.  The only thing it's missing is when folded underneath is the ability to 'stick' to the underneath so it does feel like a paperback folded back on itself with only a single page visible fighting to flatten itself.&lt;img src="http://feeds.feedburner.com/~r/CCWindowsOtherRamblings/~4/2Mdg-tdMcV4" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/CCWindowsOtherRamblings/~3/2Mdg-tdMcV4/some-thoughts-on-ipad-2-actual-feel.html</link><author>noreply@blogger.com (Pete Barber)</author><thr:total>0</thr:total><feedburner:origLink>http://petebarber.blogspot.com/2011/05/some-thoughts-on-ipad-2-actual-feel.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-2918646278142295649.post-7550695023459501304</guid><pubDate>Mon, 23 May 2011 17:49:00 +0000</pubDate><atom:updated>2011-05-23T14:30:33.479-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">WPF</category><category domain="http://www.blogger.com/atom/ns#">Control</category><category domain="http://www.blogger.com/atom/ns#">TreeView</category><category domain="http://www.blogger.com/atom/ns#">Graph</category><category domain="http://www.blogger.com/atom/ns#">C#</category><title>First ever CodeProject article</title><description>I've been playing around with the WPF TreeView control trying to get it to draw a connected line org. chart style view of a tree. &amp;nbsp;I was going to write it up here but it got a bit long and formatting for the blog is a little tricky so I turned it into a Code Project article, my first one. &amp;nbsp;You can find it&amp;nbsp;&lt;a href="http://www.codeproject.com/KB/WPF/GraphTreeStyleWPFTreeView.aspx"&gt;here&lt;/a&gt;.&lt;img src="http://feeds.feedburner.com/~r/CCWindowsOtherRamblings/~4/ujch5KiZhXo" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/CCWindowsOtherRamblings/~3/ujch5KiZhXo/first-ever-codeproject-article.html</link><author>noreply@blogger.com (Pete Barber)</author><thr:total>0</thr:total><feedburner:origLink>http://petebarber.blogspot.com/2011/05/first-ever-codeproject-article.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-2918646278142295649.post-1970962972643049658</guid><pubDate>Tue, 17 May 2011 18:07:00 +0000</pubDate><atom:updated>2011-05-21T09:13:56.149-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Fluent Functor</category><category domain="http://www.blogger.com/atom/ns#">CodeProject</category><category domain="http://www.blogger.com/atom/ns#">Spirit</category><category domain="http://www.blogger.com/atom/ns#">Fluent</category><category domain="http://www.blogger.com/atom/ns#">C++</category><category domain="http://www.blogger.com/atom/ns#">Fluent Programming</category><title>Fluent Functors</title><description>I've been learning about&amp;nbsp;&lt;a href="http://boost-spirit.com/home/"&gt;BOOST Spirit&lt;/a&gt;;&amp;nbsp;a C++ expression based compiler generator. &amp;nbsp;One of the &lt;a href="http://www.boost.org/doc/libs/1_46_0/libs/spirit/doc/html/spirit/qi/tutorials/roman_numerals.html"&gt;examples&lt;/a&gt;&amp;nbsp;is for a Roman Numeral parser. &amp;nbsp;This contained the following interesting code for pre-loading a symbol table.&lt;br /&gt;
&lt;span class="Apple-style-span" style="font-family: sans-serif;"&gt;&lt;/span&gt;&lt;br /&gt;
&lt;pre class="programlisting" style="border-bottom-color: rgb(220, 220, 220); border-bottom-style: solid; border-bottom-width: 1px; border-left-color: rgb(220, 220, 220); border-left-style: solid; border-left-width: 1px; border-right-color: rgb(220, 220, 220); border-right-style: solid; border-right-width: 1px; border-top-color: rgb(220, 220, 220); border-top-style: solid; border-top-width: 1px; display: block; font-size: 9pt; margin-bottom: 0pc; margin-left: 4%; margin-right: 4%; margin-top: 1pc; padding-bottom: 0.5pc; padding-left: 0.5pc; padding-right: 0.5pc; padding-top: 0.5pc;"&gt;&lt;span class="keyword" style="color: #0000aa;"&gt;struct&lt;/span&gt; &lt;span class="identifier" style="color: black;"&gt;ones_&lt;/span&gt; &lt;span class="special" style="color: #707070;"&gt;:&lt;/span&gt; &lt;span class="identifier" style="color: black;"&gt;qi&lt;/span&gt;&lt;span class="special" style="color: #707070;"&gt;::&lt;/span&gt;&lt;span class="identifier" style="color: black;"&gt;symbols&lt;/span&gt;&lt;span class="special" style="color: #707070;"&gt;&amp;lt;&lt;/span&gt;&lt;span class="keyword" style="color: #0000aa;"&gt;char&lt;/span&gt;&lt;span class="special" style="color: #707070;"&gt;,&lt;/span&gt; &lt;span class="keyword" style="color: #0000aa;"&gt;unsigned&lt;/span&gt;&lt;span class="special" style="color: #707070;"&gt;&amp;gt;&lt;/span&gt;
&lt;span class="special" style="color: #707070;"&gt;{&lt;/span&gt;
    &lt;span class="identifier" style="color: black;"&gt;ones_&lt;/span&gt;&lt;span class="special" style="color: #707070;"&gt;()&lt;/span&gt;
    &lt;span class="special" style="color: #707070;"&gt;{&lt;/span&gt;
        &lt;span class="identifier" style="color: black;"&gt;add&lt;/span&gt;
            &lt;span class="special" style="color: #707070;"&gt;(&lt;/span&gt;&lt;span class="string" style="color: teal;"&gt;"I"&lt;/span&gt;    &lt;span class="special" style="color: #707070;"&gt;,&lt;/span&gt; &lt;span class="number" style="color: teal;"&gt;1&lt;/span&gt;&lt;span class="special" style="color: #707070;"&gt;)&lt;/span&gt;
            &lt;span class="special" style="color: #707070;"&gt;(&lt;/span&gt;&lt;span class="string" style="color: teal;"&gt;"II"&lt;/span&gt;   &lt;span class="special" style="color: #707070;"&gt;,&lt;/span&gt; &lt;span class="number" style="color: teal;"&gt;2&lt;/span&gt;&lt;span class="special" style="color: #707070;"&gt;)&lt;/span&gt;
            &lt;span class="special" style="color: #707070;"&gt;(&lt;/span&gt;&lt;span class="string" style="color: teal;"&gt;"III"&lt;/span&gt;  &lt;span class="special" style="color: #707070;"&gt;,&lt;/span&gt; &lt;span class="number" style="color: teal;"&gt;3&lt;/span&gt;&lt;span class="special" style="color: #707070;"&gt;)&lt;/span&gt;
            &lt;span class="special" style="color: #707070;"&gt;(&lt;/span&gt;&lt;span class="string" style="color: teal;"&gt;"IV"&lt;/span&gt;   &lt;span class="special" style="color: #707070;"&gt;,&lt;/span&gt; &lt;span class="number" style="color: teal;"&gt;4&lt;/span&gt;&lt;span class="special" style="color: #707070;"&gt;)&lt;/span&gt;
            &lt;span class="special" style="color: #707070;"&gt;(&lt;/span&gt;&lt;span class="string" style="color: teal;"&gt;"V"&lt;/span&gt;    &lt;span class="special" style="color: #707070;"&gt;,&lt;/span&gt; &lt;span class="number" style="color: teal;"&gt;5&lt;/span&gt;&lt;span class="special" style="color: #707070;"&gt;)&lt;/span&gt;
            &lt;span class="special" style="color: #707070;"&gt;(&lt;/span&gt;&lt;span class="string" style="color: teal;"&gt;"VI"&lt;/span&gt;   &lt;span class="special" style="color: #707070;"&gt;,&lt;/span&gt; &lt;span class="number" style="color: teal;"&gt;6&lt;/span&gt;&lt;span class="special" style="color: #707070;"&gt;)&lt;/span&gt;
            &lt;span class="special" style="color: #707070;"&gt;(&lt;/span&gt;&lt;span class="string" style="color: teal;"&gt;"VII"&lt;/span&gt;  &lt;span class="special" style="color: #707070;"&gt;,&lt;/span&gt; &lt;span class="number" style="color: teal;"&gt;7&lt;/span&gt;&lt;span class="special" style="color: #707070;"&gt;)&lt;/span&gt;
            &lt;span class="special" style="color: #707070;"&gt;(&lt;/span&gt;&lt;span class="string" style="color: teal;"&gt;"VIII"&lt;/span&gt; &lt;span class="special" style="color: #707070;"&gt;,&lt;/span&gt; &lt;span class="number" style="color: teal;"&gt;8&lt;/span&gt;&lt;span class="special" style="color: #707070;"&gt;)&lt;/span&gt;
            &lt;span class="special" style="color: #707070;"&gt;(&lt;/span&gt;&lt;span class="string" style="color: teal;"&gt;"IX"&lt;/span&gt;   &lt;span class="special" style="color: #707070;"&gt;,&lt;/span&gt; &lt;span class="number" style="color: teal;"&gt;9&lt;/span&gt;&lt;span class="special" style="color: #707070;"&gt;)&lt;/span&gt;
        &lt;span class="special" style="color: #707070;"&gt;;&lt;/span&gt;
    &lt;span class="special" style="color: #707070;"&gt;}&lt;/span&gt;

&lt;span class="special" style="color: #707070;"&gt;}&lt;/span&gt; &lt;span class="identifier" style="color: black;"&gt;ones&lt;/span&gt;&lt;span class="special" style="color: #707070;"&gt;;&lt;/span&gt;&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
So,&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;struct ones_ is &lt;/span&gt;a new class definition.&lt;/li&gt;
&lt;li&gt;&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;ones_()&lt;/span&gt; is the constructor&lt;/li&gt;
&lt;li&gt;The call to &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;add("I", 1)&lt;/span&gt; is a call to the member function &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;add &lt;/span&gt;associating the string "I" with the value 1 by adding them to the symbol table.&lt;/li&gt;
&lt;/ul&gt;&lt;div&gt;There's nothing particularly strange there. &amp;nbsp;However, the continuation, i.e. &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;add()()()()()...&lt;/span&gt; looked a little odd and puzzled me for a minute or so. &amp;nbsp;Then I realized &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;add()&lt;/span&gt; must be returning &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;*this&lt;/span&gt; and the other ()s were invoking the &amp;nbsp;parenthesis operator, i.e. in this case &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;ones_&amp;amp; operator()(const char*, const int);&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;
&lt;/div&gt;&lt;div&gt;Following this little&amp;nbsp;revelation&amp;nbsp;to confirm the theory I constructed the following program which sums the numbers 1-6 printing 21.&lt;/div&gt;&lt;div&gt;&lt;pre class="programlisting" style="border-bottom-color: rgb(220, 220, 220); border-bottom-style: solid; border-bottom-width: 1px; border-left-color: rgb(220, 220, 220); border-left-style: solid; border-left-width: 1px; border-right-color: rgb(220, 220, 220); border-right-style: solid; border-right-width: 1px; border-top-color: rgb(220, 220, 220); border-top-style: solid; border-top-width: 1px; display: block; margin-bottom: 0pc; margin-left: 4%; margin-right: 4%; margin-top: 1pc; padding-bottom: 0.5pc; padding-left: 0.5pc; padding-right: 0.5pc; padding-top: 0.5pc;"&gt;&lt;span class="special" style="font-size: 12px;"&gt;&lt;span class="Apple-style-span" style="color: #707070;"&gt;#include &amp;lt;iostream&amp;gt;

class Func
{
private:
    int m_sum;

public:
    Func(const int n) : m_sum(n) { /* Empty */ }

    const int Sum() const { return m_sum; }

    Func&amp;amp; operator()(const int n)
    {
 m_sum += n;

 return *this;
    }

    static Func add(int n) { return Func(n); }
};

int main()
{
    std::cout &amp;lt;&amp;lt; Func::add(1)(2)(3)(4)(5)(6).Sum() &amp;lt;&amp;lt; std::endl;
}&lt;/span&gt;&lt;/span&gt;&lt;/pre&gt;&lt;div style="margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px;"&gt;&lt;/div&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;
&lt;/div&gt;&lt;div&gt;All that's needed is a seed function, in this case &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;add()&lt;/span&gt; which returns &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;*this&lt;/span&gt; followed by &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;operator()()&lt;/span&gt;. &amp;nbsp;It would work fine without the named seed function using just &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;operator()()&lt;/span&gt; but then it would loose a little meaning.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;
&lt;/div&gt;&lt;div&gt;This isn't really that helpful and in most circumstances probably constitutes &lt;a href="http://en.wikipedia.org/wiki/International_Obfuscated_C_Code_Contest"&gt;obfuscated code&lt;/a&gt;. &amp;nbsp;However it's certainly cute and where overloading is done fully and with meaning of which Spirit is a case in point then it becomes an effective and&amp;nbsp;usable&amp;nbsp;syntax.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;
&lt;/div&gt;&lt;div&gt;As &lt;a href="http://en.wikipedia.org/wiki/Fluent_interface"&gt;Fluent Programming&lt;/a&gt; seems to be on rise this another demonstration of it within C++, just like iostreams. &amp;nbsp;The added&amp;nbsp;Syntactical&amp;nbsp;Sugar&amp;nbsp;provided by C++'s Functor mechanism makes for Fluent Functors.&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/CCWindowsOtherRamblings/~4/f3_Uh2DhQkM" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/CCWindowsOtherRamblings/~3/f3_Uh2DhQkM/fluent-functors.html</link><author>noreply@blogger.com (Pete Barber)</author><thr:total>0</thr:total><feedburner:origLink>http://petebarber.blogspot.com/2011/05/fluent-functors.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-2918646278142295649.post-4753351461859600975</guid><pubDate>Wed, 28 Feb 2007 21:03:00 +0000</pubDate><atom:updated>2011-05-23T14:44:12.638-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">enumerator</category><category domain="http://www.blogger.com/atom/ns#">IEnumerable</category><category domain="http://www.blogger.com/atom/ns#">enumeration</category><category domain="http://www.blogger.com/atom/ns#">IEnumerator</category><category domain="http://www.blogger.com/atom/ns#">CodeProject</category><category domain="http://www.blogger.com/atom/ns#">Updated</category><category domain="http://www.blogger.com/atom/ns#">C#</category><category domain="http://www.blogger.com/atom/ns#">.NET 2.0</category><title>Evolution of C# enumerators</title><description>&lt;h1&gt;Introduction&lt;/h1&gt;I needed a very simple tree data structure the other day.  Unfortunately C#/.NET doesn’t provide one so I implemented a simple one.  The need was to create a hierarchy of folders from a flat data structure where each node contained a unique id and its parent id.  The list wasn’t particularly ordered, i.e. not by depth or breadth however parent nodes always preceded child nodes so that when a node was added to the tree the parent was guaranteed to already be there.  This wasn’t the important part of the exercise.  The main thing I wanted to accomplish was to perform a depth first search displaying the node’s contents indented to reflect the depth that it occurred in the tree.&lt;br /&gt;
&lt;br /&gt;
As this was written in C# and .NET collections are expected to support the IEnumerable interface I didn’t just want to implement a basic tree walker but do it in such a way that it conforms to the .NET paradigm.  As it’s a while since I’ve implemented a tree and this is the first time I’ve used C# 2.0 enumerators I ended up going through 3 iterations of enumerator until I had what I thought was proper .NET style enumerator.  This article describes this evolution.  Please note that thread safety is not considered and little attention is paid to error handling or invalid conditions.&lt;br /&gt;
&lt;br /&gt;
The following code shows the minimal implementation of the tree bar any enumeration code.&lt;br /&gt;
&lt;br /&gt;
&lt;pre&gt;class Node
{
  public static Node MakeRoot() 
  {
    return new Node(0); 
  }
  private Node(int id) { id_ = id; }
  public bool Add(int id, int parentId)
  {
    if (parentId == id_)
    {
      children_.Add(new Node(id));
      return true;
    }
    else
    {
      foreach (Node child in children_)
        if (child.Add(id, parentId) == true)
          return true;
      return false;
    }
  }

  public int Id { get { return id_; } }
  private int id_ = -1;
  ArrayList children_ = new ArrayList();
}
&lt;/pre&gt;The main program just loads a simple tree. &lt;br /&gt;
&lt;br /&gt;
&lt;pre&gt;Node root = Node.MakeRoot();

root.Add(1, 0);
root.Add(2, 0);
root.Add(3, 0);
root.Add(11, 1);
root.Add(12, 1);
root.Add(13, 1);
root.Add(121, 12);
root.Add(122, 12);
root.Add(1211, 121);
root.Add(12111, 1211);
&lt;/pre&gt;&lt;h1&gt;C Approach&lt;/h1&gt;Performing a depth first search is not difficult.  The easiest way to implement this is to use recursion.  The following is a quick implementation that proved the tree was functioning correctly.&lt;br /&gt;
&lt;br /&gt;
Note that this is a member of the Node class.&lt;br /&gt;
&lt;br /&gt;
&lt;pre&gt;public void Walk(int level)
{
  for (int i = 0; i &amp;lt; level; ++i)
    Console.Write("\t");

  Console.WriteLine(id_);

  foreach (Node node in children_)
    node.Walk(level + 1);
}
&lt;/pre&gt;This implementation is how a tree would have been walked in the era of C programming.  In the OO and .NET world it has a number of problems: &lt;br /&gt;
&lt;ol&gt;&lt;li&gt;Breaks encapsulation as the application code, i.e. the display code is mixed with that of the data structure. Using straight C this code could be fixed by having the method take a function pointer as an argument which would be invoked for each node to display the node.  In C++ this could be improved by using a functor or by implementing the whole thing as an STL compatible iterator.&lt;/li&gt;
&lt;li&gt;The method runs until completion, i.e. it is not possible to obtain an item from the tree and perform some action on it then retrieve the next or abandon the walk altogether.  However, the method could be extended to provide a mechanism to terminate early depending on the return value of the invoked method.&lt;/li&gt;
&lt;li&gt;.NET 2.0 collections are expected to implement the IEnumerable&lt;type&gt; interface which means they must provide a IEnumertor&lt;type&gt; GetEnumerator(). &amp;nbsp;This allows the collection to be used by any .NET entity that recognizes the standard enumeration interfaces in particular the foreach keyword which is recognized as the best mechanism for enumerating a collection.&lt;/type&gt;&lt;/type&gt;&lt;/li&gt;
&lt;/ol&gt;&lt;h1&gt;C# 1.0 Approach&lt;/h1&gt;These issues can be addressed by implementing the tree walker as an enumerator.  The main difficulty in doing this is that an enumerator is an iterative operation which means a separate call is made to advance the iterations whereas the tree walker is called once and only returns when the traversal is complete. &lt;br /&gt;
&lt;br /&gt;
An enumerator for data structures that are suited to recursive traversal can be implemented using various techniques.  Firstly on the initial call the enumerator could walk the tree recursively and build up a linear data structure that is ideally suited to iteration, i.e. create a list of depth first traversal whose members reference the actual nodes of the tree then iterate over members of the list. &lt;br /&gt;
&lt;br /&gt;
The method I choose was to mimic recursion by maintaining context in the enumerator that upon the following call would take the enumerator back to where it left off.  The enumerator is implemented in a separate class which can hold the state and as per the iterator pattern allow multiple instances to co-exist.  The following code shows the implementation but note that even though not explicitly shown this is a nested class so has access to Node’s private members and is not visible to the caller which works only against the IEnumerator interface.  It is this interface that requires the implementation of MoveNext(), Current &amp;amp; Reset(). &lt;br /&gt;
&lt;br /&gt;
&lt;pre&gt;class WalkNode : IEnumerator
{
  public WalkNode(Node root)
  {
    root_ = root;
  }
  bool IEnumerator.MoveNext()
  {
    if (current_ == null)
    {
      current_ = root_;            
      activeIts_.Push(root_.children_.GetEnumerator());
      return true;
    }
    else
    {
      while (activeIts_.Count &amp;gt; 0)
      {
        IEnumerator it = (IEnumerator)activeIts_.Pop();
        if (it.MoveNext() == true)
        {
          current_ = (Node)it.Current;
          activeIts_.Push(it);
          activeIts_.Push(current_.children_.GetEnumerator());
          return true;
        }
      }

      return false;
    }
  }
  object IEnumerator.Current
  {
    get 
    { 
      // Need to handle invalid current_
      return new NodeAndLevel(current_, activeIts_.Count - 1); 
    }
  }
  void IEnumerator.Reset() { current_ = null; activeIts_.Clear(); }
  Node root_;
  Node current_;
  Stack activeIts_ = new Stack();
}
&lt;/pre&gt;The interesting stuff happens in MoveNext().  This is called to advance the enumerator and must be called to set the enumerator to the first item before actually using its value, i.e. calling the Current property. &lt;br /&gt;
&lt;br /&gt;
On the first call the current node is set to the root node.  This means that if the Current property is called then the root node will be returned.  Secondly it sets the enumerator up for the subsequent call by obtaining an enumerator to the root node’s children and pushing it onto a stack stored in the enumerator.  It is this stack that effectively mimics the recursion as it persists the enumerator for the current node and those in the branch above across each call and so maintains a reference to the next node to visit and which one to return to when there are no more children. &lt;br /&gt;
&lt;br /&gt;
On the next (non-root node) and all subsequent calls a test is made to see if the stack contains any items.  If it doesn’t then this means there are no more nodes to visit and the tree has been fully traversed.  When called the second time the stack will contain the enumerator for the root node’s children.  Due to the nature of the Node class a node will always be able to provide a enumerator even if doesn’t have any children but the first call to MoveNext() on it will return false indicating the end of the children, i.e. none.  If the root has no children then this will be case as the enumerator (for its children) obtained from the stack will return false, the stack count will be zero so the loop will terminate and the main MoveNext() will return false indicating an end of the traversal.  This will also be case when all the children of the root have been traversed.&lt;br /&gt;
&lt;br /&gt;
The other case is that the root does have children in which case the internal call to MoveNext(), i.e. using the enumerator from the stack will return true in which case the member variable current_ used to implement the Current property will be set to the child node obtained from the Current property of the internal enumerator.  As this is a depth first search the next node to be traversed should be the first child of this node so the current enumerator is pushed onto the stack along with the newly obtained internal enumerator for the current node’s children so on the next call its children will be enumerated.  True is then returned. &lt;br /&gt;
&lt;br /&gt;
In the case of the bottom of a branch being reached the internal call to MoveNext() from the just popped enumerator will return false.  As the stack still has the parent enumerators on it the loop will not terminate unlike the case of a root node without children or having traversed its last.  This then causes the current node’s parent’s enumerator to become the current enumerator allowing the next child along to be traversed if there is one.  This continues until the stack has been popped so that current internal enumerator is that of the root node.  If this contains more children the each of these nodes is traversed deeply until no more children are found causing the loop to terminate as the stack is empty and finally returning false indicating the end of the traversal. &lt;br /&gt;
&lt;br /&gt;
The downside of the mimicking approach is the number of live internal enumerators that are kept alive on the stack whilst traversing deeper children.  If the deepest point of the tree was 100 nodes deep then this would require 100 active internal enumerators to be on the stack.  The deepest enumerator, i.e. number 100 would be for the leaf node and will yield no children. &lt;br /&gt;
&lt;br /&gt;
Rather than returning the reference to a node an instance of a wrapper type is returned which allows the additional level information to be supplied.  The definition of this is shown below. &lt;br /&gt;
&lt;br /&gt;
&lt;pre&gt;class NodeAndLevel
{
  public NodeAndLevel(Node node, int level)
  {
    node_ = node;
    level_ = level;
  }

  public Node Contents { get { return node_; } }
  public int Level { get { return level_; } }

  readonly Node node_;
  readonly int level_;
} 
&lt;/pre&gt;The other modification is that Node implements the IEnumerable interface which means it must implement the GetEnumerator() method which it does.  This creates an instance of the WalkNode enumerator that we have just discussed as can be seen below. &lt;br /&gt;
&lt;br /&gt;
&lt;pre&gt;IEnumerator IEnumerable.GetEnumerator()
{
  return new WalkNode(this);
}
&lt;/pre&gt;&lt;h1&gt;C# 2.0 Approach&lt;/h1&gt;Version 2.0 of C# added language support to make the implementation of enumerators simpler.  This allows the implementation of this particular enumerator to be reduced and simplified dramatically. &lt;br /&gt;
&lt;br /&gt;
&lt;pre&gt;class Node : IEnumerable&lt;nodeandlevel&gt;
{
  IEnumerator&lt;nodeandlevel&gt; IEnumerable&lt;nodeandlevel&gt;.GetEnumerator()
  {
    return GetEnumeratorWithLevel(0);
  }
  private IEnumerator&lt;nodeandlevel&gt; GetEnumeratorWithLevel(int level)
  {
    yield return new NodeAndLevel(this, level);
    foreach (Node node in children_)
    {
      using (IEnumerator&lt;nodeandlevel&gt; it = node.GetEnumeratorWithLevel(level + 1))
      {
        while (it.MoveNext())
          yield return it.Current;
      }
    }
  }
  System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
  {
    return this.GetEnumeratorWithLevel(0);
  }

… the rest is the same as Node at the beginning
&lt;/nodeandlevel&gt;&lt;/nodeandlevel&gt;&lt;/nodeandlevel&gt;&lt;/nodeandlevel&gt;&lt;/nodeandlevel&gt;&lt;/pre&gt;&lt;br /&gt;
The entire enumerator code has now been reduced to the implementation of GetEnumerator(), well almost.  The helper GetEnumeratorWithLevel() is also required so an additional argument can be passed.  As GetEnumerator() is implementing the interface IEnumerable&amp;lt;&amp;gt; as inherited by Node its signature cannot vary hence why it calls the helper method.  As IEnumerable&amp;lt;&amp;gt; derives from the C# 1.0 interface IEnumerable as used in the previous example the weakly typed IEnumerable.GetEnumerator()  must also be implemented but as can be seen this is done by calling the strongly typed version.&lt;br /&gt;
&lt;br /&gt;
As generics is available the tree code has switched to using generics.  This is a good thing as the caller of the enumerator is dealing with strongly typed objects that don’t require a runtime cast any more.&lt;br /&gt;
&lt;br /&gt;
The enumerator class hasn’t really gone away rather the compiler has implemented it for us as a nested class just as we had to do by hand in the previous version.  Again, just like the C# 1.0 implementation which used a stack to maintain the recursive state the generated code also maintains state.  The key to allowing the compiler to do this is the yield return statements.  This informs the compiler where the enumerator should return and that the subsequent call to MoveNext() should begin immediately after it. &lt;br /&gt;
&lt;br /&gt;
In this example, the enumerator is initially called with the root node.  This then yields (returns) immediately, creating a new instance of NodeLevel which will be accessible via the generated Current property. &lt;br /&gt;
&lt;br /&gt;
The next call causes the enumerator to create an internal enumerator (as before in the C# 1.0 implementation) of the current node’s children, i.e. from the children_ list.  This will then call MoveNext() on this internal enumerator.  If the root node has no children then it will terminate and false will be returned indicating that the traversal is complete.  If there are children then the yield will cause a return true and the current node will become that child.  As the enumerator was created by calling GetEnumeratorWithLevel() this is effectively a recursive call but with the yield causing the return with the generated code maintaining the state including storing the references to all the internal enumerators. &lt;br /&gt;
&lt;br /&gt;
Even though the generated code is hard to read and full of gotos using &lt;a href="http://www.lutzroeder.com/dotnet/"&gt;Reflector&lt;/a&gt; allows the generated code to be seen.  As this implements IEnumerator&amp;lt;&amp;gt; and the derived IEnumerator Current is implemented for both and Reset for the latter.  In addition, as IEnumerator&amp;lt;&amp;gt; is also derived from IDisposable Dispose is also created.  This is why the apparent recursive call to GetEnumeratorWithLevel() wraps the resulting call with a using statement so that Dispose() is called. &lt;br /&gt;
&lt;br /&gt;
The generated code still has to do everything the hand-coded version did including keeping open any active enumerators.  As it’s generated it might be faster too but I haven’t tested this.  However, it has freed us from having to write &amp;amp; maintain this code.&lt;img src="http://feeds.feedburner.com/~r/CCWindowsOtherRamblings/~4/CTEQ0xXZqrE" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/CCWindowsOtherRamblings/~3/CTEQ0xXZqrE/evolution-of-c-enumerators.html</link><author>noreply@blogger.com (Pete Barber)</author><thr:total>1</thr:total><feedburner:origLink>http://petebarber.blogspot.com/2007/02/evolution-of-c-enumerators.html</feedburner:origLink></item></channel></rss>
