Is C++/CLI a Second Class Language with Microsoft?

The post frequency on the Visual C++ team blog is reasonably high. Some posts deal with new features that were added to VC++ 2008.


But, is Visual C++ a second-class citizen in the Visual Studio product group?  Recently the Visual Studio 2008 Product Comparison was released (don’t ask me why it wasn’t released at the same time as the products…).  In the product comparisons VC++ Express has an inordinate number of features that only it doesn’t have.  When you look at the Visual C++ 2008 Express Edition product sites, it seems pretty clear that it’s geared towards native-only software development.  Despite this the product comparison shows VC++ Express has Managed Debugging, Mixed-Mode Debugging and Compiler Support for any CPU (which details “…compile your managed application…”).  But, VC++ 2008 Express is the only edition that doesn’t support adding reference to WCF services (“Service Reference”), Code Snipped Manager, Code Snippets, Rename Refactoring, Text File (you can’t create a plain text file with VC++ 2008 Express?), and one of two editions that doesn’t include support for XML File (create a blank XML file), and SQL Server 2005 Compact Edition.  As well, only VC++ 2008 doesn’t include managed-only features like Object Browser, Object Relational Designer, and SQLMetal (the last two deal with .NET-only LINQ-to-SQL.


C++ has stagnated as a language for quite some time, but Visual C++ 2008 includes new language features like C++0x and TR1 that help evolve the language for the parallel future.  But, despite assurances that native development is still a focus at Microsoft, there is the appearance that VC++ just isn’t getting the same resources as the other editions.  Makes you wonder how much longer will Microsoft keep it in the Visual Studio family…

"Object is currently in use elsewhere" error.

I was debugging what I thought was a strange exception the other day.  The exception was an InvalidOperationException and the message was “Object is currently in use elsewhere”.  Unless you’re familiar with this exception, it really doesn’t offer much as to why the exception is occurring.  There seems to be several stale threads on the Web about this issue, so I’d thought I’d post about it.


As it turns out it had to do with some code that was PInvoking some native graphics functions and the interaction with the WinForm that was hosting the drawing surface was to blame.


What’s really happening with “Object is currently in use elsewhere” is that GDI+ is complaining that the device context (DC) that it is trying to use is already “in use”.  With WinForms, this generally means there is a recursive Graphics.GetHdc occurring.  GetHdc must match a ReleaseHdc before any other GetHdc.  Recursive means you have something like GetHdc->GetHdc->ReleaseHdc->ReleaseHdc, instead of GetHdc->ReleaseHdc->GetHdc->ReleaseHdc.  Another possibility is that there is a missing call to ReleaseHdc. (i.e. GetHdc->GetHdc->ReleaseHdc)


Now, in my case there was some seemingly innocuous code like this:



    SafeNativeMethods.DrawSomeStuff(e.Graphics.GetHdc(), parameters);



    e.Graphics.DrawString(text, this.Font, Brushes.Black, point);


…no matching ReleaseHdc(), before the DrawString call.


The fix turned out to be really simple:




    try


    {


        SafeNativeMethods.DrawSomeStuff(e.Graphics.GetHdc(), parameters);


    }


    finally


    {


        e.Graphics.ReleaseHdc();


    }


    e.Graphics.DrawString(text, this.Font, Brushes.Black, point);


You can also encounter this exception if you’re drawing to a form from multiple threads.  You’ll likely also be encountering a cross-threading exception as well.  The solution in this case is to not use multiple threads when accessing a form, including drawing.

Observation as Scientific Proof

A while ago I had a bit of a rant about how some people seemed to think “working” only needed to be concerned with <99% of the time.


Lately, I’ve been seeing a few bright people talk about how observation of something is proof of something else.  It’s a logical falalcy that observation of something working means it works in all circumstances.  Only the opposite is true, observation of something not working is proof that it doesn’t work in certain circumstances.  Yet, these people use it to justify or validate specific logic or API usage.  It’s a bit scary.


I my other rant I showed some C++ code that let’s you observe certain behaviour.  Certain behaviour of bad code.  It’s bad code because it will eventually fail given certain circumstances.


I’m not going to “out” anyone; but it appears despite various initiatives, the software development craft still has a long way to go…

Formatting/parsing for a specific culture redux

In recent blog post I detailed how creating a culture via the CultureInfo constructor could actually create a user-overridden culture–which could be completely different than the culture that you’ve requested by name.  Fortunately there’s a way of overriding the user override (apologies for overloading “override”) by supplying the boolean value “false” in a CultureInfo overload.


As Greg Beech commented, there’s another method to create a culture–System.Globalization.CultureInfo.CreateSpecificCulture.  This sounds like it does exactly what you might expect and creates a “specific” culture.  Unfortunately, this method too violates the principle of least astonishment and creates a culture that uses the user-overridden values when the culture name matches that of the user’s current culture.


CreateSpecificCulture does not, as far as I can tell, have an overload/alternative to you allow to to force a “specific” culture, so the problem is much worse with CreateSpecificCulture.  I’ve gone ahead and logged a bug for it on Connect: https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=321241


In case you’re wondering why this is more serious, consider the following following block of code that formats a date value as text:




    System.Globalization.CultureInfo ci;


    String text;


    ci = System.Globalization.CultureInfo.CreateSpecificCulture(“en-us”);


    text = String.Format(ci, “{0:d}”, DateTime.Now);


And that text is transmitted to another application (or another session of the same application, e.g. serialization), potentially in another locale, to be parsed with the following block of code:



    System.Globalization.CultureInfo ci;


    ci = System.Globalization.CultureInfo.CreateSpecificCulture(“en-us”);


    String text = ReadRecord();



    DateTime now = DateTime.Parse(text, ci);


If either (or) the user’s current culture is set to “English (United States)” and they’ve overridden the currency format the short date (say from “M/d/yyyy” to “d/M/yyyy”) will randomly result in the wrong date.


 

BDD vs TDD.

 


Seems like an innocent question: which is better behaviour-driven development or test-driven development.


It’s a trick question.  I don’t think either is better, they’re related but orthogonal.


Object-oriented programming at the design level deals with the abstraction and encapsulation of behaviours and attributes.  At the lowest level that’s creating classes to model “real-world” object.  That’s a pretty shallow or one-dimensional view of OO.  Methodologies like Agile attempt to keep the stakeholders involved throughout the development process.  The difficulty with that has been the tendancy of software developers to completely abstract themselves at the macro level from the stakeholders: “You tell me what you want, and I’ll go away for a while and do it”.  At the application-level this has proven to have issues.  Depending on the complexity of what the developers are working on, by the time they deliver it may be irrelavent.  Agile attempts to compress that tendancy into iterations–where an application will contain several iterations, allowing the developers to involve the stakeholders through the lifecycle gaining valuable feedback and becoming responsive to change.  The issue now is how to manage what each iteration involves and how to sucessfully deliver those iterations.


Concepts like Domain-Driven Design (DDD) attempt to make better use of object-orientation by bringing encapsulation and abstraction into the design process by better abstracting the implementation details from the stakeholders.  Abstraction is done by continually evolving a domain model. 


Test-driven development at the very simplest means writing test before writing code and was incubated by Agile methodologies.


Behaviour-driven development is an adjunct to TDD in that it adds a level of testing between “unit” and “integration” to test the behaviour of objects.  Unit testing should continue to be done: testing the specifications of methods and classes. 

Compilation of LINQ Expressions and Separation of Concerns.

I was reading Rico Mariani’s latest performance quiz (#13) involving compilation of LINQ expressions.  One point that I got from his comments on the solution is that swapping to/from compiled queries is likely to cause the code to “break even very easily”.  So, you end up making the decision to compile or not not based on observed metrics but:




  1. is there any re-use at all


  2. how much uglier is the compiled code pattern and is the benefit worth the hassle

Completely valid; and considering the savings you get, probably a fairly benign decision.


But, there’s more object-oriented ways to approach this type of concern.  My use of “concern” should give part of it away.  The choice between whether an expression is compiled or not shouldn’t be the concern of the method/class that is executing the LINQ expression.  The Strategy Pattern is an object-oriented pattern the ensure abstraction, Separation of Concern, and the Single Responsibility Principle (and probably more).  i.e. the choice between compilation or not is the responsibility of another class.


The Strategy Pattern can be implemented as a form of Inversion of Control or Dependency Injection.  In this case we want to decouple the dependency on compiled/uncompiled LINQ statements from the method that executes it.  The compiled/uncompiled strategy is injected into the class at construction or execution of the method and that class either makes (or made) the choice or acts as a proxy to execute the expression (compiling it first, with the compilation strategy).


Now, before I get too deep into doing this with a LINQ query (and you’ll understand why in a bit) I’ll show an example of implementing the Strategy Pattern.


One example of the Strategy Pattern involves choice of sorting techniques.  Let’s say we have an integer array that we need to sort, but how it is sorted needs to be runtime-selectable.  We may do something like this:


    public interface ISortStrategy
    {
        void Sort(ref int[] data);
    }
    public class BubbleSort : ISortStrategy
    {
        public void Sort(ref int[] data)
        {
            //…
        }
    }
    public class HeapSort : ISortStrategy
    {
        public void Sort(ref int[] data)
        {
            //…
        }
    }

And an example of using these classes:


        static void SortData(ref int[] data)
        {
            ISortStrategy sortStrategy = Configuration.Create<ISortStrategy>();
            sortStrategy.Sort(ref data);
        }

 Fairly straightforward, SortData is now decoupled from the type of sort and is freely able to change by whatever means to be detected at runtime.  Configuration.Create may make the decision whether to use BubbleSort or HeapSort based on something in app.config, something in user configuration settings, etc.  The point is, SortData is not coupled to the instantiation of a particular sorting class.


Now, back to LINQ.  The example queries that Rico presented were:


 



            var q = (from o in nw.Orders


                    select new


                    {


                        OrderID = o.OrderID,


                        CustomerID = o.CustomerID,


                        EmployeeID = o.EmployeeID,


                        ShippedDate = o.ShippedDate


                    }).Take(5);


And



            var cq = CompiledQuery.Compile


            (


                (Northwinds nw) =>


                        (from o in nw.Orders


                        select new


                        {


                            OrderID = o.OrderID,


                            CustomerID = o.CustomerID,


                            EmployeeID = o.EmployeeID,


                            ShippedDate = o.ShippedDate


                        }).Take(5)


            );


These queries make use of an anonymous type.  In order to either compile & execute this query or just execute a single query we need be able to declare a single query that can be compiled an executed.  Unfortnately there’s appears to be no way to do this.  The call to CompiledQuery.Compile accept an Expression<> object and compiles it,


 

Why is immutability important.

There’s been some discussion about the adding the ability for immutable types in a future CLR and C# (I assume other .NET languages in the same timeframe would follow suit; but, to be honest, I don’t follow the other popular ones).  But, some of you are wondering, “why?”


Is this simply just an off-shoot of C++’s “const”?  Not really.  The proposed immutabilities would be compile and run-time enforced.  C++’s const can be casted-away.


There’s a few techniques to writing thread-safe/concurrent/parallel code, amongst them: messenging and locking/synchronization.  Messenging works because each thread is supposed operate on a copy of the data or each thread is part of a work-flow waiting on a message from another to do its work.  This works in two parts: one no thread is operating with same data at the same time as another, and dependant threads awaken/start another thread as they sleep/stop via a message.  Unless your programming language supports/implements this method of threading, you have to write a large and complex framework for it to work.  The other technique, which is most prevalent with C#, is locking/synchronization.  Each thread let’s other thread know that it’s working on specific data by taking a lock.  No other threads can take the lock, so whatever that lock is guarding (yes, that assumes both threads do anything with that data lock the same lock) causes data access to be “synchronized” amongst the threads.  This works; but locking is really slow.  .NET includes the Monitor class specifically to get a user-mode synchronization primitive.  Using the Windows synchronization objects (like mutexes) require a kernal mode round-trip which is really expestive.  This is why you see other techniques like “low-lock”.  Locking is more diffuclt than messenging because any thread is free to have multiple locks.  “Lock-leveling” is a way to compensate for this, but it’s still very difficult and time-consuming to get right.


I’m a big fan of being explicit when I’m designing and programming.  In C#, If I haven’t designed a class to be a base class, I declare sealed and the compiler will raise an error if someone tries to derive from that class.  In C++, if I don’t modify the value of a parameter I declare it const; if the code was changed to modify the value, the compiler will raise an error.  If I’ve designed a class to be immutable, it would be nice to be able to declare it immutable and be enforced.


There are a few benefits to being able to declare a class immutable.  One is that I can then be free not to worry about using an instance of that type by multipe threads–it is thread-safe.  You can write code /now/ to create a type that exhibits immutability; but if you work with many different developers like I do, you have no way to enforce that (to the point where the compiler will raise an error and poke the person who made the change and reenforce my design constraints).  Another is the ability to embrace functional programming paradigms.  Much of the functional programming space hinges on immutable data.  And yet another is the ability to declare a type with true value semantics. 


There are other benefits, but they mostly relate to being able to enforce a design constraint, like implementing temporal object pattern, etc.


Could immutability simply be another contract in an ability to enforce design contracts?  Sure, that’s one way of doing it.  It requires a contract framework to support it (Spec#) but it could be part of that.  Could it live all on it’s own?  Of course, you could do something similar to other run-time and compile-time features (get a reference)

Microsoft Symbol Server EULA Circa VS 2005

TERMS OF USE FOR MICROSOFT SYMBOLS AND BINARIES


These Terms of Use govern your access to and use of computer files obtained from Microsoft Corporation (“Microsoft”) via the Internet (collectively, “Files”).  By clicking on “Yes” below or by accessing or using any Files, you agree to these Terms of Use.  If you do not agree, then you may not access or use any Files.  These Terms of Use also govern any support services that Microsoft may provide in connection with Files.  You can find a copy of these Terms of Use at http://www.microsoft.com/whdc/ddk/debugging/symsrvTOU2.mspx.


1. Ownership, License and Limitations.  All Files are the copyrighted work of Microsoft and/or its suppliers.  Microsoft grants you the right to use Files solely in the ordinary operation of debugging software for the purpose of debugging a validly licensed copy of a Microsoft operating system or one or more applications running on a validly licensed copy of a Microsoft operating system.  Any rights not expressly granted herein are reserved.  Without limiting the generality of the foregoing sentence, you may not make additional copies of any Files or post or distribute any Files to others.  Reverse engineering, decompiling, or disassembling the Files is prohibited, except and only to the extent that such activity is expressly permitted by applicable law notwithstanding this limitation.  Microsoft is not obligated to provide any Files or any support services in connection with Files, and Microsoft reserves the right to discontinue providing Files or any support services at any time in its sole discretion.


2. No Malicious Use.  As a condition of your use of Files, you may not request or use any Files in any manner that could damage, disable, overburden or impair any Microsoft server or the network(s) connected to any Microsoft server, or could interfere with any other party’s use of any Files.  You may not attempt to gain unauthorized access to any Files, accounts, computer systems or networks connected to any Microsoft server.  You may not obtain or attempt to obtain any materials or information through any means not intentionally made available by Microsoft.


3. DISCLAIMER OF WARRANTIES.  TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, MICROSOFT AND ITS SUPPLIERS PROVIDE FILES AND ANY SUPPORT SERVICES AS IS AND WITH ALL FAULTS, AND HEREBY DISCLAIM ALL OTHER WARRANTIES AND CONDITIONS, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, ANY (IF ANY) IMPLIED WARRANTIES, DUTIES OR CONDITIONS OF MERCHANTABILITY, OF FITNESS FOR A PARTICULAR PURPOSE, OF RELIABILITY OR AVAILABILITY, OF ACCURACY OR COMPLETENESS OF RESPONSES, OF RESULTS, OF WORKMANLIKE EFFORT, OF LACK OF VIRUSES, AND OF LACK OF NEGLIGENCE, ALL WITH REGARD TO FILES AND THE PROVISION OF OR FAILURE TO PROVIDE FILES OR OTHER SERVICES, INFORMATION, SOFTWARE OR RELATED CONTENT OR OTHERWISE ARISING OUT OF THE USE OF FILES.  ALSO, THERE IS NO WARRANTY OR CONDITION OF TITLE, QUIET ENJOYMENT, QUIET POSSESSION, CORRESPONDENCE TO DESCRIPTION OR NON-INFRINGEMENT WITH REGARD TO FILES.


4. EXCLUSION OF INCIDENTAL, CONSEQUENTIAL AND CERTAIN OTHER DAMAGES.  TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, IN NO EVENT WILL MICROSOFT OR ITS SUPPLIERS BE LIABLE FOR ANY SPECIAL, INCIDENTAL, PUNITIVE, INDIRECT OR CONSEQUENTIAL DAMAGES WHATSOEVER (INCLUDING, BUT NOT LIMITED TO, DAMAGES FOR LOSS OF PROFITS OR CONFIDENTIAL OR OTHER INFORMATION, FOR BUSINESS INTERRUPTION, FOR PERSONAL INJURY, FOR LOSS OF PRIVACY, FOR FAILURE TO MEET ANY DUTY INCLUDING OF GOOD FAITH OR OF REASONABLE CARE, FOR NEGLIGENCE, AND FOR ANY OTHER PECUNIARY OR OTHER LOSS WHATSOEVER) ARISING OUT OF OR IN ANY WAY RELATED TO THE USE OF OR INABILITY TO USE FILES, INFORMATION, SOFTWARE OR RELATED CONTENT THROUGH THE FILES OR OTHERWISE ARISING OUT OF THE USE OF FILES OR OTHERWISE UNDER OR IN CONNECTION WITH ANY PROVISION OF THESE TERMS OF USE, EVEN IN THE EVENT OF THE FAULT, TORT (INCLUDING NEGLIGENCE), MISREPRESENTATION, STRICT LIABILITY, BREACH OF CONTRACT OR BREACH OF WARRANTY OF MICROSOFT OR ANY SUPPLIER, AND EVEN IF MICROSOFT OR ANY SUPPLIER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.


5. LIMITATION OF LIABILITY AND REMEDIES.  NOTWITHSTANDING ANY DAMAGES THAT YOU MIGHT INCUR FOR ANY REASON WHATSOEVER (INCLUDING, WITHOUT LIMITATION, ALL DAMAGES REFERENCED HEREIN AND ALL DIRECT OR GENERAL DAMAGES IN CONTRACT OR ANYTHING ELSE), THE ENTIRE LIABILITY OF MICROSOFT AND ANY OF ITS SUPPLIERS UNDER ANY PROVISION OF THESE TERMS OF USE AND YOUR EXCLUSIVE REMEDY HEREUNDER SHALL BE LIMITED TO US$5.00.  THE FOREGOING LIMITATIONS, EXCLUSIONS AND DISCLAIMERS (INCLUDING SECTIONS 3, 4 AND 5) WILL APPLY TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, EVEN IF ANY REMEDY FAILS OF ITS ESSENTIAL PURPOSE.


6. RESTRICTED RIGHTS LEGEND.  Any Files downloaded for or on behalf of the United States of America, its agencies and/or instrumentalities (“U.S. Government”), are provided with Restricted Rights.  Use, duplication or disclosure by the U.S. Government is subject to restrictions as set forth in subparagraph (c)(1)(ii) of the Rights in Technical Data and Computer Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and (2) of the Commercial Computer Software – Restricted Rights at 48 CFR 52.227-19, as applicable.  Manufacturer is Microsoft Corporation, One Microsoft Way, Redmond, WA 98052-6399.


7. APPLICABLE LAW; ENTIRE AGREEMENT; SEVERABILITY.  These Terms of Use are governed by the laws of the State of Washington and constitute the entire agreement between you and Microsoft relating to Files and any support services, and supersede all prior or contemporaneous oral or written communications, proposals and representations with respect to the Software or any other subject matter covered by these Terms of Use.  If any provision of these Terms of Use is held to be void, invalid, unenforceable or illegal, the other provisions shall continue in full force and effect.


asdf