How to use Unity – Dependency Container thread Safe

First I will Try to define the Problem : The Constructor Injection pattern is easy to understand until a follow-up question comes up:

Where should we compose object graphs?

It’s easy to understand that each class should require its dependencies through its constructor, but this pushes the responsibility of composing the classes with their dependencies to a third party. Where should that be?

It seems to me that most people are eager to compose as early as possible, but the correct answer is:

As close as possible to the application’s entry point.

This place is called the Composition Root of the application and defined like this:

A Composition Root is a (preferably) unique location in an application where modules are composed together.

This means that all the application code relies solely on Constructor Injection (or other injection patterns), but is never composed. Only at the entry point of the application is the entire object graph finally composed.

The appropriate entry point depends on the framework:

  • In console applications it’s the Main method
  • In ASP.NET MVC applications it’s global.asax and a custom IControllerFactory
  • In WPF applications it’s the Application.OnStartup method
  • In WCF it’s a custom ServiceHostFactory
  • etc

The Composition Root is an application infrastructure component.Only applications should have Composition Roots. Libraries and frameworks shouldn’t.

The Composition Root can be implemented with Poor Man’s DI, but is also the (only) appropriate place to use a DI Container.

A DI Container should only be referenced from the Composition Root. All other modules should have no reference to the container.

Using a DI Container is often a good choice. In that case it should be applied using the Register Resolve Release pattern entirely from within the Composition Root.

Read more in Dependency Injection in .NET.

Having seen the benefits of a Composition Root over the Service Locator anti-pattern global That entailed an Unity container,

The solution Consists of two classes. DependencyFactory is the public wrapper for an internal class,  DependencyFactoryInternal. The outer class presents easy-to-use static methods and acquires the right kind of lock (read or write) for whatever operations you’re Trying to do .

First time you access the container, the code Will the load-type registrations in your. Config file. You can register aussi kinds programmatically with the static RegisterInstance method.

DependencyFactory.RegisterInstance <IMyType> ( new MyConcreteType ());

To resolve a type use the static Resolve method

var myObject = DependencyFactory.Resolve <IMyTypeType> ();

Finally, the static FindRegistrationSingle method exposed an existing ContainerRegistration .

public sealed class DependencyFactory : IDisposable
    {
        #region Properties
        /// <summary>
        /// Get the singleton Unity container.
        /// </summary>
        public IUnityContainer Container
        {
            get { return DependencyFactoryInternal.Instance.Container; }
        }
        #endregion

        #region Constructors
        /// <summary>
        /// Default constructor. Obtains a write lock on the container since this is the safest policy.
        /// Also uses a relatively long timeout.
        /// </summary>
        public DependencyFactory()
            : this(true, 10000)
        {
        }

        /// <summary>
        /// Construct an object that can access the singleton Unity container until the object is Disposed.
        /// </summary>
        /// <param name="allowContainerModification">True to allow modification of the container.
        /// The caller is responsible for behaving according to this pledge!
        /// The default is to allow modifications, which results in a write lock rather than
        /// the looser read lock. If you're sure you're only going to be reading the container, 
        /// you may want to consider passing a value of false.</param>
        /// <param name="millisecondsTimeout">Numer of milliseconds to wait for access to the container,
        /// or -1 to wait forever.</param>
        internal DependencyFactory(bool allowContainerModification, int millisecondsTimeout = 500)
        {
            if (allowContainerModification)
                DependencyFactoryInternal.Instance.EnterWriteLock(millisecondsTimeout);
            else
                DependencyFactoryInternal.Instance.EnterReadLock(millisecondsTimeout);
        }
        #endregion

        #region Methods
        /// <summary>
        /// Resolves a type in the static Unity container.
        /// This is a convenience method, but has the added benefit of only enforcing a Read lock.
        /// </summary>
        /// <param name="overrides">Overrides to pass to Unity's Resolve method.</param>
        /// <typeparam name="T">The type to resolve.</typeparam>
        /// <returns>An concrete instance of the type T.</returns>
        /// <remarks>
        /// If you already have a DependencyFactory object, call Resolve on its Container property instead.
        /// Otherwise, you'll get an error because you have the same lock on two threads.
        /// </remarks>
        static public T Resolve<T>(params ResolverOverride[] overrides)
        {
            using (var u = new DependencyFactory(false, 10000))
            {
                return u.Container.Resolve<T>(overrides);
            }
        }

        /// <summary>
        /// Convenience method to call RegisterInstance on the container.
        /// Constructs a DependencyFactory that has a write lock.
        /// </summary>
        /// <typeparam name="T">The type of register.</typeparam>
        /// <param name="instance">An object of type T.</param>
        static public void RegisterInstance<T>(T instance)
        {
            using (var u = new DependencyFactory())
            {
                u.Container.RegisterInstance<T>(instance);
            }
        }

        /// <summary>
        /// Find the single registration in the container that matches the predicate.
        /// </summary>
        /// <param name="predicate">A predicate on a ContainerRegistration object.</param>
        /// <returns>The single matching registration. Throws an exception if there is no match, 
        /// <remarks>
        /// Only uses a read lock on the container.
        /// </remarks>
        /// or if there is more than one.</returns>
        static public ContainerRegistration FindRegistrationSingle(Func<ContainerRegistration, bool> predicate)
        {
            using (var u = new DependencyFactory(false,10000))
            {
                return u.Container.Registrations.Single(predicate);
            }
        }

        /// <summary>
        /// Acquires a write lock on the Unity container, and then clears it.
        /// </summary>
        static public void Clear()
        {
            using (var u = new DependencyFactory())
            {
                DependencyFactoryInternal.Instance.Clear();
            }
        }
        #endregion

        #region IDisposable Members
        /// <summary>
        /// Dispose the object, releasing the lock on the static Unity container.
        /// </summary>
        public void Dispose()
        {
            if (DependencyFactoryInternal.Instance.IsWriteLockHeld)
                DependencyFactoryInternal.Instance.ExitWriteLock();
            if (DependencyFactoryInternal.Instance.IsReadLockHeld)
                DependencyFactoryInternal.Instance.ExitReadLock();
        }
        #endregion
    }

Internal class

 /// This class is internal; consumers should go through DependencyFactory.
    /// </remarks>
    internal class DependencyFactoryInternal
    {
        #region Fields
        // Lazy-initialized, static instance member.
        private static readonly Lazy<DependencyFactoryInternal> _instance
            = new Lazy<DependencyFactoryInternal>(() => new DependencyFactoryInternal(),
            true /*thread-safe*/ );

        private ReaderWriterLockSlim _lock = new ReaderWriterLockSlim();
        #endregion

        #region Properties
        /// <summary>
        /// Get the single instance of the class.
        /// </summary>
        public static DependencyFactoryInternal Instance
        {
            get { return _instance.Value; }
        }

        IUnityContainer _container = null;
        /// <summary>
        /// Get the instance of the Unity container.
        /// </summary>
        public IUnityContainer Container
        {
            get
            {
                try
                {
                    return _container ?? (_container = new UnityContainer().LoadConfiguration());
                }
                catch (Exception ex)
                {
                    throw new InvalidOperationException("Could not load the Unity configuration.", ex);
                }
            }
        }

        /// <summary>
        /// Tells whether the underlying container is null. Intended only for unit testing. 
        /// (Note that this property is internal, and thus available only to this assembly and the
        /// unit-test assembly.)
        /// </summary>
        internal bool ContainerIsNull 
        { 
            get { return _container == null; } 
        }

        /// <summary>
        /// Tell whether the calling thread has a read lock on the singleton.
        /// </summary>
        internal bool IsReadLockHeld { get { return _lock.IsReadLockHeld; } }

        /// <summary>
        /// Tell whether the calling thread has a write lock on the singleton.
        /// </summary>
        internal bool IsWriteLockHeld { get { return _lock.IsWriteLockHeld; } }
        #endregion

        #region Constructor
        /// <summary>
        /// Private constructor. 
        /// Makes it impossible to use this class except through the static Instance property.
        /// </summary>
        private DependencyFactoryInternal()
        {
        }
        #endregion

        #region Methods
        /// <summary>
        /// Enter a read lock on the singleton.
        /// </summary>
        /// <param name="millisecondsTimeout">How long to wait for the lock, or -1 to wait forever.</param>
        public void EnterReadLock(int millisecondsTimeout)
        {
            if (!_lock.TryEnterReadLock(millisecondsTimeout))
                throw new TimeoutException(Properties.Resources.TimeoutEnteringReadLock);
        }

        /// <summary>
        /// Enter a write lock on the singleton.
        /// </summary>
        /// <param name="millisecondsTimeout">How long to wait for the lock, or -1 to wait forever.</param>
        public void EnterWriteLock(int millisecondsTimeout)
        {
            if (!_lock.TryEnterWriteLock(millisecondsTimeout))
                throw new TimeoutException(Properties.Resources.TimeoutEnteringWriteLock);
        }

        /// <summary>
        /// Exit the lock obtained with EnterReadLock.
        /// </summary>
        public void ExitReadLock()
        {
            _lock.ExitReadLock();
        }

        /// <summary>
        /// Exit the lock obtained with EnterWriteLock.
        /// </summary>
        public void ExitWriteLock()
        {
            _lock.ExitWriteLock();
        }

        /// <summary>
        /// Clear the Unity container and the lock so we can restart building the dependency injections.
        /// </summary>
        /// <remarks>
        /// Intended for unit testing.
        /// </remarks>
        public void Clear()
        {
            if (_container != null)
                _container.Dispose();
            _container = null;
            while (_lock.IsWriteLockHeld)
                _lock.ExitWriteLock();
            while (_lock.IsReadLockHeld)
                _lock.ExitReadLock();
        }
        #endregion
    }
Advertisements

How to create C++ Apps with XAML

This blog post will help explain how XAML and C++ work together in the build system to make a Windows Store application that still respects the C++ language build model and syntax.  (Note: this blog post is targeted towards Windows Store app developers.)

The Build Process

From a user-facing standpoint, Pages and other custom controls are really a trio of user-editable files.  For example, the definition of the class MainPage is comprised of three files: MainPage.xaml, MainPage.xaml.h, and MainPage.xaml.cpp.  Both mainpage.xaml and mainpage.xaml.h contribute to the actual definition of the MainPage class, while MainPage.xaml.cpp provides the method implementations for those methods defined in MainPage.xaml.h.  However, how this actually works in practice is far more complex.

This drawing is very complex, so please bear with me while I break it down into its constituent pieces.

Every box in the diagram represents a file.  The light-blue files on the left side of the diagram are the files which the user edits.  These are the only files that typically show up in the Solution Explorer.  I’ll speak specifically about MainPage.xaml and its associated files, but this same process occurs for all xaml/h/cpp trios in the project.

The first step in the build is XAML compilation, which will actually occur in several steps.  First, the user-edited MainPage.xaml file is processed to generate MainPage.g.h.  This file is special in that it is processed at design-time (that is, you do not need to invoke a build in order to have this file be updated).  The reason for this is that edits you make to MainPage.xaml can change the contents of the MainPage class, and you want those changes to be reflected in your Intellisense without requiring a rebuild.  Except for this step, all of the other steps only occur when a user invokes a Build.

Partial Classes

You may note that the build process introduces a problem: the class MainPage actually has two definitions, one that comes from MainPage.g.h:

 partial ref class MainPage : public ::Windows::UI::Xaml::Controls::Page,
      public ::Windows::UI::Xaml::Markup::IComponentConnector
{
public:
   void InitializeComponent();
   virtual void Connect(int connectionId, ::Platform::Object^ target);

private:
   bool _contentLoaded;

};

And one that comes from MainPage.xaml.h:

public ref class MainPage sealed
{
public:
   MainPage();

protected:
   virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
};

This issue is reconciled via a new language extension: Partial Classes.

The compiler parsing of partial classes is actually fairly straightforward.  First, all partial definitions for a class must be within one translation unit.  Second, all class definitions must be marked with the keyword partial except for the very last definition (sometimes referred to as the ‘final’ definition).  During parsing, the partial definitions are deferred by the compiler until the final definition is seen, at which point all of the partial definitions (along with the final definition) are combined together and parsed as one definition.  This feature is what enables both the XAML-compiler-generated file MainPage.g.h and the user-editable file MainPage.xaml.h to contribute to the definition of the MainPage class.

Compilation

For compilation, MainPage.g.h is included in MainPage.xaml.h, which is further included in MainPage.xaml.cpp.  These files are compiled by the C++ compiler to produce MainPage.obj.  (This compilation is represented by the red lines in the above diagram.)  MainPage.obj, along with the other obj files that are available at this stage are passed through the linker with the switch /WINMD:ONLY to generate the Windows Metadata (WinMD) file for the project. This process is denoted in the diagram by the orange line.  At this stage we are not linking the final executable, only producing the WinMD file, because MainPage.obj still contains some unresolved externals for the MainPage class, namely any functions which are defined in MainPage.g.h (typically the InitializeComponent and Connect functions).  These definitions were generated by the XAML compiler and placed into MainPage.g.hpp, which will be compiled at a later stage.

MainPage.g.hpp, along with the *.g.hpp files for the other XAML files in the project, will be included in a file called XamlTypeInfo.g.cpp.  This is for build performance optimization: these various .hpp files do not need to be compiled separately but can be built as one translation unit along with XamlTypeInfo.g.cpp, reducing the number of compiler invocations required to build the project.

Data Binding and XamlTypeInfo

Data binding is a key feature of XAML architecture, and enables advanced design patterns such as MVVM.  C++ fully supports data binding; however, in order for the XAML architecture to perform data binding, it needs to be able to take the string representation of a field (such as “FullName”) and turn that into a property getter call against an object.  In the managed world, this can be accomplished with reflection, but native C++ does not have a built-in reflection model.

Instead, the XAML compiler (which is itself a .NET application) loads the WinMD file for the project, reflects upon it, and generates C++ source that ends up in the XamlTypeInfo.g.cpp file.  It will generate the necessary data binding source for any public class marked with the Bindable attribute.

It may be instructive to look at the definition of a data-bindable class and see what source is generated that enables the data binding to succeed.  Here is a simple bindable class definition:

[Windows::UI::Xaml::Data::Bindable]
public ref class SampleBindableClass sealed {
public:
   property Platform::String^ FullName;
};

When this is compiled, as the class definition is public, it will end up in the WinMD file as seen here:

This WinMD is processed by the XAML compiler and adds source to two important functions within XamlTypeInfo.g.cpp:CreateXamlType and CreateXamlMember.

The source added to CreateXamlType generates basic type information for the SampleBindableClass type, provides an Activator (a function that can create an instance of the class) and enumerates the members of the class:

if (typeName == L"BlogDemoApp.SampleBindableClass")
{
  XamlUserType^ userType = ref new XamlUserType(this, typeName, GetXamlTypeByName(L"Object"));
  userType->KindOfType = ::Windows::UI::Xaml::Interop::TypeKind::Custom;
  userType->Activator =
   []() -> Platform::Object^
   {
     return ref new ::BlogDemoApp::SampleBindableClass();
   };
  userType->AddMemberName(L"FullName");
  userType->SetIsBindable();
  return userType;
}

Note how a lambda is used to adapt the call to ref new (which will return a SampleBindableClass^) into the Activator function (which always returns an Object^).

From String to Function Call

As I mentioned previously, the fundamental issue with data binding is transforming the text name of a property (in our example, “FullName”) into the getter and setter function calls for this property.  This translation magic is implemented by the XamlMemberclass.

XamlMember stores two function pointers: Getter and Setter.  These function pointers are defined against the base type Object^(which all WinRT and fundamental types can convert to/from).  A XamlUserType stores a map<String^, XamlUserType^>; when data binding requires a getter or setter to be called, the appropriate XamlUserType can be found in the map and its associatedGetter or Setter function pointer can be invoked.

The source added to CreateXamlMember initializes these Getter and Setter function pointers for each property.  These function pointers always have a parameter of type Object^ (the instance of the class to get from or set to) and either a return parameter of type Object^ (in the case of a getter) or have a second parameter of type Object^ (for setters).

if (longMemberName == L"BlogDemoApp.SampleBindableClass.FullName")
{
  XamlMember^ xamlMember = ref new XamlMember(this, L"FullName", L"String");
  xamlMember->Getter =
  [](Object^ instance) -> Object^
  {
    auto that = (::BlogDemoApp::SampleBindableClass^)instance;
    return that->FullName;
  };

  xamlMember->Setter =
  [](Object^ instance, Object^ value) -> void
  {
    auto that = (::BlogDemoApp::SampleBindableClass^)instance;
    that->FullName = (::Platform::String^)value;
  };
  return xamlMember;
}

The two lambdas defined use the lambda ‘decay to pointer’ functionality to bind to Getter and Setter methods.  These function pointers can then be called by the data binding infrastructure, passing in an object instance, in order to set or get a property based on only its name.  Within the lambdas, the generated code adds the proper type casts in order to marshal to/from the actual types.

Final Linking and Final Thoughts

After compiling the xamltypeinfo.g.cpp file into xamltypeinfo.g.obj, we can then link this object file along with the other object files to generate the final executable for the program.  This executable, along with the winmd file previously generated, and your xaml files, are packaged up into the app package that makes up your Windows Store Application.

A note: the Bindable attribute described in this post is one way to enable data binding in WinRT, but it is not the only way.  Data binding can also be enabled on a class by implementing either the ICustomPropertyProvider interface or IMap<String^,Object^>.  These other implementations would be useful if the Bindable attribute cannot be used, particularly if you want a non-public class to be data-bindable.

For additional info, I recommend looking at this walkthrough, which will guide you through building a fully-featured Windows Store Application in C++/XAML from the ground up.  The Microsoft Patterns and Practices team has also developed a large application which demonstrates some best practices when developing Windows Store Applications in C++: project Hilo.  The sources and documentation for this project can be found at http://hilo.codeplex.com/

.NET code review checklist

 

You can try to work with your team/coworkers to build up a checklist of good questions to ask yourself while reviewing each other’s code, ideally tailoring it to the languages you code in, the projects you work on, the domains in which your code runs, etc. In practice, I don’t think it’s reasonable to expect developers to pull out a spreadsheet and check it off every time they review code, but I think it’s a good exercise to periodically do nonetheless. Additionally, if all code review "results"/responses are sent to the entire team, you can learn from the sorts of things that more experienced developers look for and spot during code reviews. (It also tends to lead to pretty good discussion.) At a few points, my team actually all got together to go through a sample code review, comparing each of the comments we had privately made.

  • Ensure the code meets standards (set by your department perhaps)
  • Proper formatting
  • Syntax errors (these are the worst – the person must, at the very least, have compiled their code)
  • Logical errors (actual errors in the logical flow of the code)
  • Risky/Fragile/Error-prone code
  • Code that is hard to maintain
  • Software antipatterns
  • Bad practices/Code smells
  • Improper naming of variables/methods (self-documenting code is important; I make sure I name my methods and variables properly)
  • Race conditions (in multithreaded code)
  • Buffer overflows
  • Infinite recursion
  • Edge cases that have not been handled
  1. Are exceptions used to indicate error rather than returning status or error codes?
  2. Are all classes and public methods commented with .NET style comments?  Note that <summary> comments should discuss the "what" of public methods.  Discussion of "how" should be in <remarks> blocks or in-line with the code in question.
  3. Are method arguments validated and rejected with an exception if they are invalid?
  4. Are Debug.Asserts used to verify assumptions about the functioning of the code?  Comments like, "j will be positive" should be rewritten as Asserts.
  5. Do classes that should not be instantiated have a private constructor?
  6. Are classes declared as value types only infrequently used as method parameters, returned from methods or stored in Collections?
  7. Are classes, methods and events that are specific to an assembly marked as internal?
  8. Are singletons that may be accessed by multiple threads instantiated correctly?  See the Enterprise Solution Patterns book, p. 263.
  9. Are methods that must be overriden by derived classes marked as abstract?
  10. Are classes that should not be overriden marked as sealed?
  11. Is "as" used for possibly incorrect downcasts?
  12. Do classes override ToString instead of defining a Dump method for outputting the object’s state?
  13. Are log messages sent to the logging component instead of Console?
  14. Are finally blocks used for code that must execute following a try?
  15. Is foreach used in preference to the for(int i…) construct?
  16. Are properties used instead of implementing getter and setter methods?
  17. Are readonly variables used in preference to properties without setters?
  18. Is the override keyword used on all methods that are overriden by derived classes?
  19. Are interface classes used in preference to abstract classes?
  20. Is code written against an interface rather than an implementing class?
  21. Do all objects that represent "real-world" or expensive resources implement the IDisposable pattern?
  22. Are all objects that implement IDisposable instantiated in a using block?
  23. Is the lock keyword used in preference to the Monitor.Enter construct?
  24. Are threads awakened from wait states by events or the Pulse construct, rather than "active" waiting such as Sleep()?
  25. If equals is overridden, is it done correctly?  The rules for overriding equals are complex, see Richter p153-160 for details.
  26. If == and != are overridden, so they redirect to Equals?
  27. Do all objects that override Equals also provide an overloaded version of GetHashCode that provides the same semantics as Equals?  Note that overrides to GetHashCode should takeadvantage of the object’s member variables, and must return an unchanging hash code.
  28. Do all exception classes have a constructor that takes a string and and another constructor that takes a string and an exception?
  29. Do all exception classes derive from the base Matrix exceptions and fit correctly into the exception hierarchy?
  30. Are all classes that will be marshaled or remoted marked with the Serializable attribute?
  31. Do all classes marked with the Serializable attribute have a default constructor?  This includes Exception and EventArgs classes.
  32. Do all classes that explicitly implement ISerializable provide both the required GetObjectData and the implied constructor that takes a SerializationInfo and a StreamingContext?
  33. When doing floating point calculations, are all constants doubles rather than integers?
  34. Do all delegates have a void return type and avoid using output or ref parameters?
  35. Do all delegates send the sender (publisher) as the first argument?  This allows the subscriber to tell which publisher fired the event.
  36. Are all members of derived EventArg classes read-only?  This prevents one subscriber from modifying the EventArgs, which would affect the other subscribers.
  37. Are delegates published as events?  This prevents the subscribers from firing the event, see Lowy, p. 102 for details.
  38. Is common setup and teardown nUnit code isolated in Setup and Teardown methods that are marked with the appropriate attribute?
  39. Do negative nUnit tests use the ExpectedException attribute to indicate that an exception must be thrown?

References:

Juval Lowy, "Programming .NET Components"

Jeffrey Richter, "Applied Microsoft .NET Framework Programming"

"Enterprise Solution Patterns using Microsoft .NET" – available in published form or as a free pdf

C++ days in München with Boris Jabes & Visual Studio 11 Training Kit

 

The Visual Studio team at Microsoft has released the next version of Visual Studio as a developer preview .

It is available as a free download for everyone here .

IMAG0070

 

In brief , Visual Studio 11 provides an integrated development experience that spans the entire lifecycle of software creation from architecture to code creation, testing and beyond. This release adds support for Windows 8 and HTML 5, enabling you to target platforms across devices, services and the cloud . To get an in-depth walkthrough of the new features and enhancements in Visual Studio 11 , check out this video at the BUILD event that happened last month .

Alternatively , you can read about all the VS 11 highlights right here on MSDN .

Apart from this , the Visual Studio 11 Developer Preview Training Kit is also out now . This kit includes hands-on labs to help you understand how to take advantage of the variety of enhancements in Visual Studio 11 and the .NET Framework 4.5, how to support and manage the entire application lifecycle and how to build Windows Metro style apps .

So get started with coding and developing on the new VS 11 environment , and hope you have fun using it !!

What’s New for Visual C++ in Visual Studio 11 Developer Preview

 

 

Standard Template Library

As part of the added support in Visual Studio 11 Developer Preview for the C++11 specification, the Standard Template Library (STL) support in Visual Studio is extended to provide the additional programming constructs that specification requires. Highlights include the following:

  • Support for new headers <atomic>, <chrono>, <condition_variable>, <filesystem>, <future>, <mutex>, <ratio>, and <thread>.

  • To optimize memory resource usage, all containers are now smaller given their current representations. For example, in x86 release mode with default settings, std::vector has shrunk from 16 bytes in Visual C++ 2010 to 12 bytes in Visual C++ in Visual Studio 11 Developer Preview, and std::map has shrunk from 16 bytes in Visual C++ 2010 to 8 bytes in Visual C++ in Visual Studio 11 Developer Preview.

Other C++11 Enhancements
  • SCARY iterators: As permitted but not required by the C++11 Standard, SCARY iterators have been implemented. For more information, see the PDF document SCARY Iterator Assignment and Initialization.

  • Stateless lambdas, which is code beginning with an empty lambda-introducer [] and capturing no local variables, are now implicitly convertible to function pointers as required by the C++11 Standard.

  • Scoped enumerations support. The C++ enum class enum-key is now supported.

Visual C++ Compiler and Linker


  • Auto-vectorizer. One of the biggest potential performance gains is doing things in parallel instead of sequentially. Visual Studio 11 Developer Preview provides not only parallelism on the task level, but also at the loop level, automatically. The C++ compiler will automatically vectorize loops if it is possible. Vectorization reorganizes a loop, for example, a summation loop, so that the CPU can execute multiple iterations at the same time. By using auto-vectorization, loops can be up to 8 times faster when executed on CPUs that support SIMD instructions. For example, most modern processors support SSE2 instructions, which allow the compiler to instruct the processor to do math operations on 4 numbers at a time.

    Because the compiler recognizes loops that can be vectorized when you compile your code, this occurs automatically. Note that this differs from parallelization, which is described in the next list item.

  • Auto-parallelizer. Visual Studio 11 Developer Preview is improving the way you can take advantage of multiprocessor and multi-core hardware. With the the auto-parallelizer, a loop is reorganized so that it can be executed on multiple threads at the same time. This means that your application can take advantage of multi-core CPUs and multiprocessors to distribute chunks of the work to all available processors. The parallelizer automatically reorganizes loops and executes multiple tasks, all without the need for you to add any new code to your application. You can tell the compiler which loops to parallelize with the #pragma parallelize directive.

    There are some key differences between auto-vectorization and auto-parallelization. First, auto-vectorization is always on and requires no user interaction, while auto-parallelization requires the programmer to decide which loops will be parallelized. Also, vectorization improves the performance of loops on single-core CPUs that support SIMD instructions, while parallelization improves the performance of the loop on multiple CPUs and multi-core CPUs. The two features can work together so that a vectorized loop is then parallelized across multiple processors.

  • C++ Accelerated Massive Parallelism (AMP) Support. C++ AMP accelerates the execution of your C++ code by taking advantage of the data parallel hardware that is ordinarily present as a GPU on a discrete graphics card. The C++ AMP programming model includes multidimensional arrays, indexing, memory transfer, tiling, and a mathematical function library. C++ AMP language extensions and compiler restrictions enable you to control how data is moved from the CPU to the GPU and back. For more information, see C++ Accelerated Massive Parallelism (C++ AMP).

Visual C++ Libraries


Parallel Programming Improvements

With hardware moving to multi-core and many-core architectures, developers can no longer rely on ever-increasing clock speeds of single cores to enhance application performance. The parallel programming support in the C++ concurrency namespace enables developers to take advantage of these new architectures.

In Visual Studio 2010, we saw the introduction of powerful C++ parallelization libraries such as the Parallel Patterns Library. We also introduced concepts to take advantage of concurrency by expressing sophisticated dataflow pipelines. In Visual Studio 11 Developer Preview, these libraries have been extended to provide better performance, more control, and richer support for the parallel patterns developers need most. The breadth of the offering now includes:

  • Parallel patterns library, which supports fork-join parallelism (parallel_for, parallel_for with affinity, parallel_for_each, parallel_sort, parallel_reduce, parallel_transform).

  • A rich task-based programming model that supports asynchrony and continuations.

  • Agents and Messaging, which lets developers express dataflow pipelines that naturally decompose into concurrent units.

  • Concurrency-safe containers package, which provides thread-safe versions of std:: data structures such as priority_queue, queue, vector and map.

  • Customizable scheduler and resource manager to facilitate the smooth composition of the previously-listed patterns.

IDE


In Visual C++ in Visual Studio 11 Developer Preview, the integrated development environment (IDE) has significant improvements in tools to help you be more productive coding in C++. For more information about other IDE enhancements, see Product Highlights for Visual Studio 11 Developer Preview.

  • Visual Studio Templates support. You can now author C++ project and item templates using the Visual Studio Templates technology. This was previously unsupported for C++.

  • C++/CLI IntelliSense. C++/CLI now has full IntelliSense support. All the IntelliSense features such as Quick Info, Parameter Help, List Members, and Auto Completion now work for C++/CLI. In addition, the new IntelliSense and IDE enhancements listed in this topic also work for C++/CLI.

  • C++ Code Snippets. Skeleton code is available for basic code constructs, such as switch, if-else, and for loop, among others, in the List Members drop-down. Select a code snippet from the list to insert it into your code and then fill in the required logic. You can also create your own custom code snippets for use in the editor. For more information, see Code Snippets.

  • List Members Enhancements. The List Members drop-down appears automatically as you type code into the code editor. Results are filtered, so that only relevant members are displayed as you type. You can control the type of filtering logic used by the Member List in the Options dialog box under Text Editor, C/C++, Advanced. For more information, see Using IntelliSense.

  • Semantic Colorization. Additional C++ tokens, such as types, enumerations, and macros, among others, now have colorization. By default, this colorization is enabled. Parameters appear in italic. You can specify additional token colorizations in the Options dialog box under Environment, Fonts and Colors. For more information, see Code and Text Editor.

  • Reference Highlighting. Placing your pointer on a symbol now highlights all instances of the symbol in the current file. Press CTRL + SHIFT + UP ARROW or CTRL + SHIFT + DOWN ARROW to move among the highlighted references. You can turn this feature off in the Options dialog box under Text Editor, C/C++, Advanced.

Code Quality Tools


Parallel Debugging

In addition to the Parallel Tasks window and Parallel Stacks window available in Visual Studio 2010, Visual Studio 11 Developer Preview offers a new Parallel Watch window that lets you observe the values of an expression across all threads and processes, perform sorting and filtering on the result, and extend the window with your own visualizers. You will also be able to take advantage of the new multi-process support across all tool windows.

C++ Accelerated Massive Parallelism (AMP) Debugging and Profiling

Debugging. For applications that use C++ AMP to target the GPU, the familiar CPU debugging experience of Visual Studio is offered. This includes the new parallel debugging additions previously mentioned. Debugging C++ AMP apps is just like debugging any C++ app.

Profiling. There is now profiling support for GPU activity supporting C++ AMP and other Direct3D-based programming models.

Static Code Analysis

Static analysis for C++ has been updated to provide richer error context information, more analysis rules and better analysis results in the new Code Analysis window. In this window, you can now filter messages by keyword, project, and severity. Selecting a message in the window highlights the line in the source code editor where the message was triggered. For certain C++ warnings, the message will list source lines to show you the execution path that led to the warning.

Other code analysis enhancements include the following:

  • New concurrency warnings to help you make sure that the correct locking disciplines in multithreaded C/C++ programs. The analyzer detects several concurrency bugs. These include potential race conditions, lock order inversions, caller/callee locking contract violations, and mismatched synchronization operations.

  • You can specify the C++ analysis rules that you want to apply to code analysis runs by creating or using rule sets.

  • In the Code Analysis window, you can insert a pragma into the source code that suppresses a selected warning.

For more information, see Analyzing Application Quality by Using Code Analysis Tools.

Updated Unit Test Framework

Use the new C++ unit test framework in Visual Studio to write C++ unit tests. Add a new unit test project to your existing C++ solution by locating the C++ Unit Test Project template under the Visual C++ category in the New Project dialog box. Start writing your unit tests in the generated TEST_METHOD code stub in the Unittest1.cpp file. Once the test code is written, you can discover tests automatically as follows: Build the solution, and then open a Unit Test Explorer Window by clicking View->Other Windows->Unit Test Explorer. Run the tests by right-clicking the test case in Unit Test Explorer, and select Run selected test. You can then view test results and additional stack trace information in the same window after the test run finishes.

Architecture Dependency Graphs

To understand your code better, you can now generate dependency graphs for binary, class, namespace, and include files in your C++ solution or projects. Open menu Architecture->Generate Dependency Graph->Project or Solution to generate a dependency graph for your whole solution or a selected project. Once the graph generation is complete, you can explore the diagram by expanding each node, learn dependency relationships by moving between nodes, and browse source code by right-clicking the node and selecting View Content. To generate a dependency graph for include files, right-click a *.cpp source code file or *.h header file and select Generate Graph of Include Files.

Layer Diagrams

Use layer diagrams to validate architecture design against implementation code written in C++. Create a new layer diagram by selecting menu Architecture->New Diagram->Layer Diagram. Start drawing the architecture by dragging and dropping shapes from the Toolbox window and then link projects, or by dragging and dropping existing projects from Solution Explorer onto the diagram directly. Once the architecture diagram is finished, right-click the diagram and select Validate Architecture to run validation against code. View results in theError List window (open from View menu). You can also generate dependencies with a right-click on the diagram and select Generate Dependencies. You can then visualize the actual code dependency on the layer diagram.

Architecture Explorer

The architecture explorer lets you explore the assets in your C++ solution, projects, or files. Find architecture explorer from the menu Architecture -> Windows -> Architecture Explorer. Click on nodes you are interested in; for example, Class View. Then the tool window will be expanded on the right side with a list of all namespaces. Continue by selecting one namespace and a new column will be created on the right side to show a list of the classes, structs, and enums in this namespace. Continue to explore the assets by selecting nodes, or go back to the column on the far left to restart the query.

Code Coverage

Code coverage has been updated to dynamically instrument binaries at runtime, which gives you lower configuration overhead and provides better performance. You can also collect code coverage data from unit tests for C++ applications within Visual Studio. Please see Unit Test Framework section of this topic to learn more about how to create and run unit tests. Once you have created C++ unit tests, you can use Unit Test Explorer to discover tests in your solution automatically. In Unit Test Explorer, select Analyze Code Coverage, which will run the unit tests and collect code coverage data for these tests. View the code coverage results in the Code Coverage Results window (Test->Windows->Code Coverage Results).

New ALM Tools for VC++ Developers Announced

 

    Application Lifecycle Management (ALM) tools for Visual C++ development teams. ALM tools are critical for planning, development, testing, and maintenance of native code bases of every size. Visual Studio Ultimate offers many “out of the box” features for efficiently and easily managing a C++ code base. At Tech Ed North America, Terry Leeper and Rong Lu will be showing off these useful features and giving C++ developers a sneak peak at what’s coming

You should definitely check out the session if you are at Tech Ed. If not, you can watch the full session right here in a couple of days.
Can’t wait that long? Well, no problem. Terry and Rong came to the C9 Studio a few days ago to share some of what they’ll be talking about at Tech Ed in Atlanta. They’ve done some great work in VC10, but ALM tools for C++ developers in the next version of Visual Studio will be better, taking architectural visualization, unit testing (yes!),andmore to the next level for C++ developers.

What will be WinC++ ?

S. Somasegar mentioned some info’s about the new reorg. in Microsoft Dev. Division form last weeks, that give us an hint regarding future of C++ from Microsoft point of view and expected in Visual Studio 2012 – can be September Beta Smile

“Parallel Computing and Tools led by Steve Teixeira, David Callahan and Shahrokh Mortazavi will move to a combined WinC++, PCP, and UX organization under Mohsen.”

more details in Jo Foley’s blog http://www.zdnet.com/blog/microsoft/microsofts-plan-to-increase-its-focus-on-developers-the-full-internal-memo/9327

confirmed also in an job description

http://www.microsoft-careers.com/job/Redmond-Software-Development-Engineer-in-Test-ll-Job-WA-98052/1161369/

I will speak on ADC2011 c++

 

I will hold 2 sessions about  Native Interoperability with web  services and Windows Azure.

It is in Germany – near Apls on Chiemsee on 05-06 Mai 2011, an keynote by Boris Jabes – Senior Program Manager im Visual C++-Team @ Microsoft .

Check the other details here http://cpp.adc2011.de/

What’s new for VC++ in Visual Studio 2010

 

Visual Studio 2010 is Now Available

Visual Studio 2010 is now officially available! The formal announcement can be found on Soma’s blog and you can download VS 2010 from here.

Visual Studio 2010 is a great release for C++ developers. Top reasons you should look at VS2010:

1. Performance and productivity on large C++ source bases

First off, Is an completely revamped IntelliSense to make it more accurate and more robust on a large and complex C++ code. An IntelliSense parse of a core header file now only takes seconds instead of minutes. Also are added new features that make it easier for you to work with larger sources. My favorites are: “Navigate To” which allows you to quickly navigate to any file or symbol definition from anywhere in your source code, and “C++ Squiggles” which highlights errors in your source code without having to wait for a rebuild. Moreover, with the move to MSBuild as the build engine for C++, you get more flexibility and extensibility in configuring and diagnosing your build process.

2. Windows 7 support in MFC

MFC has been extended to add support for key Windows innovations. For example, make it easier for you to add a Windows ribbon and design its interface using the integrated Ribbon designer. Added support for key Windows features such as multi-touch, restart manager, high DPI and Shell preview and thumbnails. It’s also a lot easier now to add support for your documents in Windows search as well as integrate with the Windows 7 taskbar.  Oh, and if you’re a VC6 fan, you’ll love that brought back the MFC Class Wizard (now with integrated search!).

3. Concurrency

VS2010 provides new libraries and tools that make it easier for C++ developers to write applications that leverage the power of multi-processors. The new Parallel Patterns Library exposes a higher level of abstraction to dealing with concurrency than raw Operating System threads. It also adds new thread-safe containers (similar to STL) that can be used in a multi-threaded application. Also improved are  the debugger and profiler to make it easier for you to diagnose concurrency problems.

4. C++ language conformance

Are also implemented some key language and library features from the proposed C++0x standard that make it easier for you to write better and more modern C++ code. Some of my favorites are the ‘auto’ and ‘decltype’ keywords for automatic type inference as well as the support for lambda expressions (which works really well together with the parallel patterns library).

And the list goes on! If you wish to know more about the new features in VS2010 for C++ developers, check out Sumit Kumar’s latest MSDN magazine article here.

have fun