Universal app / .NET Native encryption/decryption

by billkrat 15. April 2014 19:33

SOURCE CODE: http://PasswordMgr.CodePlex.com change set: 105682

The following TDD demonstrates the value of IOC for building decoupled composite applications.  The logger, encryption provider, and login implementation are registered in the initialize method - emulating how they will be initialized during application start.   

    [TestInitialize]
    public void Initialize()
    {
      _container
        .Register<ILogger, DebugLogger>()
        .Register<IEncryptionProvider, AesEncryption>()
        .Register<ILogin, LoginData>(new LifetimeSingleton());
    }

On lines 37-38 I emulate information that will be pulled from the saved configuration file (set during the password managers application setup).  The application/system login password and salt value (also input by user) will be used to encrypt the data (read more on encryption using salt cryptography).

The concept is that only the device will hold the system login and password with the data being stored in an Azure table, this way if the online table is ever compromised they will be unable to decrypt passwords without the system password and salt values. My initial thoughts are to store them in the roaming location so that all devices will be able to work with the Azure data.   Initially data will be stored on the device – storage on the internet for multi-device support will be optional.

The objective of the framework is to abstract the complexity into base classes so that we can quickly standup new applications, i.e., the actual encryption and decryption of data is accomplished in the GenericBase baseclass, all the UserData class has to do is identify which fields to encrypt, currently this is done by line 116 in the left pane.  Later, when attributes are supported I will use the [Encrypt] attribute which is in place for future support (line 57 left pane).

Note on lines 53 (right pane) and 108 (left pane) that I pass in a password in clear text, however since it is marked as encrypted the value won’t be stored in clear text (reference debug window at bottom of image).   This data is ready to be sent to a data access layer for saving.  When the user wants to see the password (the main purpose of the password manager program) we will use the GetDecrypted<T>() method on line 66 (right pane).

UnitTest

This is made possible because of the login singleton on line 46 (right pane above), I resolve the singleton and set it with the system login and salt value (one time).   Now anytime it is used any class only has to request it from the IOC container as shown below (highlighted).

Baseclass

Note: the GenericBase.Set() method invokes the PropertyChanged event (line 163) so that if XAML controls are bound to the properties the view will be updated accordingly, as with encryption/decryption, this is built-in functionality.

I use the encryption/decryption methods provided on the following link:

http://social.msdn.microsoft.com/Forums/windowsapps/en-US/df082434-08e6-4d16-96b5-ed81639b4eee/how-can-i-generate-the-exact-same-ciphertext-in-winrt-as-this-windows-phone-encryption-code-using?forum=winappswithcsharp

Event Aggregator for Universal App / .NET Native

by billkrat 13. April 2014 05:48

Event Aggregator

Source Code: http://PasswordMgr.CodePlex.com Change set: 105657

Building an IOC Container For Universal Apps/.Net Native was only half the battle in the quest to create a framework that will support decoupled composite applications in this new environment, I also require an event aggregator so that my presenters and view models won’t have to have any knowledge of each other (or any other component); they simple subscribe to available events and when one is raised will respond to it.

Fortunately Prism has a nice event aggregator which I was able to port into my PasswordManager.Shared project (with minor refactoring).  So that I could perform TDD on this project I used linked files (discussed in THIS blog).  This allowed me to create my EventAggregatorFixture and its CanUseEventAggregatorForEvents test method (line 64 of image below).

For the unit test I have the following MockEventClass – the method we are concerned with for this blog is
RaiseEvent()

public class MockEventClass : IBuildup
{
  [SettingInjection]
  public IEventAggregator EventAggregator { get; set; }

  [SettingInjection]
  public ILogger Logger { get; set; }   // not tightly coupled to DebugLogger (can be easily swapped out)

  public void RaiseEvent()
  { 
    EventAggregator.GetEvent<MockEvent>().Publish(new MockEventArgs
    {
      Data = "MockEventClass Raised Event",
      EventType = EventType.MockEvent
    });
  } 

  public void Buildup(IIocContainer container)
  {
    EventAggregator = container.Resolve<IEventAggregator>();
    Logger = container.Resolve<ILogger>();
  }
}

Below on line 74 of the image below we subscribe to the MockEvent:

public class MockEvent : CompositePresentationEvent<MockEventArgs>
{
}

As you can see this is a basic class that provides not only a unique signature for this event but also the event arguments that it will be expecting.  So on line 74 when we receive “e” we know it will be of type MockEventArgs which follows:

public enum EventType { LoggerEvent, MockEvent}

public class MockEventArgs : EventArgs
{
  public string Data { get; set; }

  public EventType EventType { get; set; }
}

This is a significant feature of decoupled communications, we don’t have to have any knowledge of the MockEventClass (the publisher) and it doesn’t have to have knowledge of any subscribers – both publisher and subscriber need only know about the MockEventArgs which can remain in a project common to subscriber/publisher components.   As you can see it will be a simple matter to create new events and their respective EventArgs to ensure we can maintain a clear separation of concerns.

Below we exercise the subscription and publishing capabilities of our event aggregator, we even subscribe to our Logger’s LoggerEvent so that we can bubble the event using the event aggregator.  Note that framework is not tightly coupled to the DebugLogger (registered on line 54) as the framework only knows of ILogger – when an instance is required, as is the case with the MockEventClass above we provide one via the IBuildup implementation.

    public void Buildup(IIocContainer container)
    {
      EventAggregator = container.Resolve<IEventAggregator>();
      Logger = container.Resolve<ILogger>(); 
    }

UnitTest

TDD for universal projects / building an IOC Container for .Net Native

by BillKrat 11. April 2014 03:36

Inversion Of Control

Source Code: http://PasswordMgr.CodePlex.com Changeset: 105644

The new universal project is an odd beast (at this stage of agile development), you can’t build it (grayed out), add references to it, or access it from any of the available unit test. It seems it can only be referenced by the Windows and Phone application associated with it. If you attempt to view the project properties you’ll find it has none (reference image below).

OddBeast
Figure 1

So how do you perform TDD and work with this new project in a manner that is familiar to you?  Linked files, a technique used for multi-targeting development.  Linked files basically means that only one project actually holds any files, the other projects link to the files but doesn’t actually contain a copy of them.

To set things up we have configured our PasswordManager.Windows application to be a .NET Native application with the notion that “if it compiles, it will run”, it is represented by the use case on the right (figure 2), it references the PasswordManager.Shared (universal) project as does the PasswordManager.Phone

I then added my “development environment” which consist of a PasswordManager application (left use case of figure 2) which references  Library.Data and Library.Common projects (both being the project template “Class Library (portable for universal apps)”.   For all practical purposes for this stage of development (TDD) I’ll only be working on the left use cases – the right merely serves as a container for the source code – and if it compiles, it will run.

ProjectReferences
Figure 2

With my projects in place it is now time for me to link the files.  Ideally, I would have liked the originals to be in the Library.Common project as this is the reusable component, however at this stage of what is available I was glad that I could use the linking feature – but the master files have to reside in the universal project as the “Add As Link” feature is only available from the Library.Common (Portable) project (reference figure 4).  

Note in figure 3 below that only the PasswordManager.Shared projects have physical files, the Library Common “links” to the actual files which is represented by a different Icon.

LinkedFiles
Figure 3

Adding a linked file is very easy, from the Library.Common (Portable) project I simply indicated that I wanted to add an existing item.  I navigated to the PasswordManager.Shared folder and selected all of the files and instead of clicking “Add” clicked the down arrow (reference figure 4) and selected “Add As Link”.  Once I can see the “linked” file in my Library.Common (Portable) project I change the namespace so that it appears to be the owner.

LinkedFIle
Figure 4  

Now I can create the Unit Test (ContainerFixture in Library.Common.Tests) and reference the Library.Common (Portable) project which will permit me to perform TDD on the files which actually reside in the universal project.   I can completely ignore the universal project for the entire process, except for when I have to add new files.

All I have to ensure is that I *create* the file in the universal project and then link from it from my Library.Common (Portable project) – a two step process however it pays for itself in development experience. 

Below figure 5 I’ll show the source code for the unit test, I want to take a moment to discuss my agile approach to supporting a feature that does not exist yet in universal applications – attributes.   Ideally, I’d like to set an attribute on my properties that need to be injected, i.e., ILogger on line 9 of figure 5 below so that the container can query for this attribute and inject the applicable implementation instance for that interface.  However, since it is not yet supported I will use an IBuildup interface and each component will have the responsibility of building up itself (minor compromise).

Later, when it is supported I simply have to go into my container and add the new code (lines 95-99 explain below) and pull out the IBuildup interface code.  Now my [SetterInjection] attribute is being used and the Buildup() method become technical debt that can be cleaned out at a later point (as practical).

TechnicalDebt
Figure 5

TDD for my IOC container reveals that I have basic functionality to start development with – next stop, logging.

image 
Figure 6

Simple Mock Class used for TDD:

using Library.Common.Container;
using Library.Common.Logger;

namespace LIbrary.Common.Tests.Mocks
{
  public class SimpleIocMock : IBuildup
  {
    [SettingInjection]
    public ILogger Logger { get; set; }

    public string Data { get; set; }

    // Work-around until Setter / Constructor injection
    // features available in .NET Native
    public void Buildup(IIocContainer container)
    {
      Logger = container.Resolve<ILogger>();
    }
  }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using Library.Common.Container;
using Library.Common.Logger;
using LIbrary.Common.Tests.Mocks;

namespace LIbrary.Common.Tests
{
  [TestClass]
  public class ContainerFixture
  {
    private const string MockTemplate = "Hello {0}";
    private const string MockParameter = "World!";
    private const string MockExpected = "Hello World!";

    private IIocContainer _container;
    [TestInitialize]
    public void Initialize()
    {
      _container = new IocContainer();
    }

    [TestMethod]
    public void CanBuildupType()
    {
      // Register ILogger with container since SimpleIocMock has
      // a dependency on it
      _container.Register<ILogger, DebugLogger>();

      // *new* up a SimpleIocMock instance
      var mock = new SimpleIocMock();
      
      Assert.IsNull(mock.Logger, "Logger should have been null");

      // Build up the instance
      _container.Buildup(mock);   

      // Mock Logger should be available now
      AssertMockIsValid(mock);    
    }

    [TestMethod]
    public void CanRegisterAndResolve()
    {
      // Register ILogger in container
      _container.Register<ILogger, DebugLogger>();

      // Resolve logger and ensure we have access to DebugLogger
      var logger = _container.Resolve<ILogger>();
      
      // Logger will return what was sent to logger
      var loggerResults = logger.Log(MockTemplate, MockParameter);
      Assert.AreEqual(MockExpected, loggerResults);
    }

    [TestMethod]
    public void DefaultRegistrationIsNewInstance()
    {
      // Register ILogger in container
      _container.Register<ILogger, DebugLogger>();

      // Resolve ILogger twice
      var logger1 = _container.Resolve<ILogger>();
      var logger2 = _container.Resolve<ILogger>();

      // Default behavior is that a new instance will be provided each time
      Assert.AreNotEqual(logger1.Id, logger2.Id);
    }

    [TestMethod]
    public void SingletonRegistrationReturnsSameInstance()
    {
      // Register ILogger in container as singleton
      _container.Register<ILogger, DebugLogger>(new LifetimeSingleton());

      // Resolve ILogger twice
      var logger1 = _container.Resolve<ILogger>();
      var logger2 = _container.Resolve<ILogger>();

      // Both results should be the same DebugLogger instance
      Assert.AreEqual(logger1.Id, logger2.Id);
    }
    
    [TestMethod]
    public void CanRegisterInstance()
    {
      // *new* up a SimpleIocMock instance
      var temp = new SimpleIocMock();
      temp.Data = "My Mock Data";
      
      // Register it with the container
      _container.RegisterInstance<SimpleIocMock>(temp);

      Assert.IsNull(temp.Logger, "Logger should be null at this point");

      // SimpleIocMock has dependency on ILogger - register before resolving
      _container.Register<ILogger, DebugLogger>();

      // Resolve the SimpleIocMock which has a dependency on ILogger
      var mock = _container.Resolve<SimpleIocMock>();

      Assert.IsNotNull(temp.Logger, "Logger should have been resolved as well");
      Assert.AreEqual("My Mock Data", mock.Data);

      AssertMockIsValid(mock);
    }
    
    [TestMethod]
    public void CanResolveAndBuildupClasses()
    {
      // Register ILogger with container since we're going to
      // resolve SimpleIocMock which has a dependency on it
      _container.Register<ILogger, DebugLogger>();

      // Resolve the *class* (versus interface)
      var mock = _container.Resolve<SimpleIocMock>();

      AssertMockIsValid(mock);
    }
    
    [TestMethod]
    public void CanResolveType()
    {
      // Resolve the DebugLogger class
      var logger = _container.Resolve<DebugLogger>();
      
      // Ensure it is not null
      Assert.IsNotNull(logger);
    }
    
    private void AssertMockIsValid(SimpleIocMock mock)
    {
      // First ensure logger is not null
      Assert.IsNotNull(mock.Logger);

      // Send template and parameter to logger
      var loggerResults = mock.Logger.Log(MockTemplate, MockParameter);

      // Ensure return results are not null and expected results
      Assert.IsNotNull(loggerResults);
      Assert.AreEqual(MockExpected, loggerResults);
    }
  }
}

OpenXml Excel Export - Calculating Column width (autofit)

by billkrat 10. April 2014 13:24

Its highly likely that if you are searching for how to calculate the column width for Excel, to create autofit functionality (which currently has to be done manually), then you’ve seen the formula below:

Truncate([{Number of Characters} * {Maximum Digit Width} + {5 pixel padding}] / {Maximum Digit Width} * 256) / 256

Seems like most folks create a blog on the topic, paste this formula in it, and then make a comment like “I don’t know how it works”.  
Which is probably true – because it doesn’t…

Fortunately the following blog takes it a step further and provides some sample code for generating values based on the formula at => http://polymathprogrammer.com/2010/01/18/calculating-column-widths-in-excel-open-xml/.  This was instrumental in helping me find what did work (after a few hours of work and some minor refactoring)…. 

Plug’n play results follow:

private const double digitWidth = 20;
private double GetColumnWidth(string text)
{
    return Math.Truncate((text.Length * (digitWidth + 5.0)) / digitWidth * 200) / 256;
}

I found the formula was missing parenthesis around the (digiWidth + 5.0) which made a big difference in the results. However, even after the fix I found that some Excel columns were wider than they needed to be while others were truncating visible text still.  I made an additional change of 256 to 200 (highlighted in red above) and I got satisfactory results; if you plug in the above code you’ll be able to bypass a lot of headache.  I (like the others) don’t know how it works but sometimes the juice is not worth the squeeze, so I’ll except the satisfactory results and save the brain-strain for the next adventure.

See output window of LinqPad below to see why I went with a digitWidth of 20.
image

LINQPAD source follows:

void Main(){
    double SimpleWidthStr = 0.0f; // graphic measure of text
    double SimpleWidth = 0.0f;
    double WidthOfZero = 0.0f;
    double DigitWidth = 0.0f;
    double MaxDigitWidth = 0.0f;
    double TextWidth = 0.0f;
    string text = "Iced Lemon Tea Is An Awesome Drink!";

    // I just need a Graphics object. Any reasonable bitmap size will do.
    var drawfont = new System.Drawing.Font("Calibri", 11);
    
    using(var g = Graphics.FromImage(new Bitmap(200,200)))
    {
        WidthOfZero = (double)g.MeasureString("Z", drawfont).Width;
        SimpleWidthStr = (double)g.MeasureString(text, drawfont).Width;
        SimpleWidth = SimpleWidthStr / WidthOfZero;
    
        for (int i = (char)'A'; i < 'Z'; ++i)
        {
            DigitWidth = (double)g.MeasureString(i.ToString(), drawfont).Width;
            if (DigitWidth > MaxDigitWidth)
                MaxDigitWidth = DigitWidth;
        }
    }
    
    // Truncate([{Number of Characters} * {Maximum Digit Width} + {5 pixel padding}] / {Maximum Digit Width} * 256) / 256
    TextWidth = Math.Truncate((text.Length * (MaxDigitWidth + 5.0)) / MaxDigitWidth * 256.0) / 256.0;
    string.Format("\t SimpleWidth \t{0} (text={1})\r\n\t"+
                  "WidthOfZero \t{2}\r\n\t\t "+
                  "DigitWidth \t{3}\r\n"+
                  "MaxDigitWidth \t{4}\r\n\t\t "+
                  "TextWidth \t{5}", 
                    SimpleWidth, SimpleWidthStr, 
                    WidthOfZero, 
                    DigitWidth, 
                    MaxDigitWidth, 
                    TextWidth).Dump("Results");

    string.Format("(Simple formula) TextWidth {0}", GetColumnWidth(text)).Dump("Simple Calc");    
}

private const double digitWidth = 20;
private double GetColumnWidth(string text)
{
    return Math.Truncate((text.Length * (digitWidth + 5.0)) / digitWidth * 200) / 256;
}

How to convert HSTRING to wchar_t* (WRL C++)

by billkrat 20. November 2013 21:01

The WRL examples will demonstrate how to pass an int as a parameter but it was surprisingly difficult to find an example of how to convert a string (HSTRING) – the samples don’t have an example.  It follows below:

const wchar_t* buffer = WindowsGetStringRawBuffer(a, nullptr);

Conversion

Tags: ,

Cpp

Referencing WRL from Javascript, C++/CX and C#

by BillKrat 16. November 2013 17:03

For this tutorial I’m going to piggy back on the Walkthrough: Creating a Basic Windows Runtime Component Using WRL tutorial – it will provide the steps necessary to create the WRL Class Library Contoso project which we will reference below.  

SOURCE: MsdnExpress (works with Visual Studio 2013 express for Windows).   Refactor note: in the C++ code I am going to rename the variable “contoso” to “calculator”

Once you have your Contoso project available you can create a Windows Store C++ application, I created an application called WsaXamlCpp (ref figure 1).  I then added the necessary XAML so that it would mirror the UI of the JavaScript tutorial referenced above (figure 3 and 4). 

In figure 1 below we see the MainPage.xaml.cpp (code-behind) where I handle the button click.  I retrieve the two values and then use contoso->add() to sum the values. The result is used to update the XAML UI.  As you can see from this code, referencing WRL from a C++/CX application is pretty straight forward. 

AddReference
Figure 1

For C# developers it may not be intuitive how to add a reference to a C++ project, as with the JavaScript project (WsaJava below) we are accustomed to seeing a “References” node where we can right click and add our reference.

image For the C++ project WsaXamlCpp you won’t find such a node.  If you right click on the project you won’t find a “References” option. 

To add a reference right click on your C++ application, select Add, and then References.  You will be greeted with the window in the top pane below where you will click [Add New Reference] and then select the WRL project.
AddReferenceII

Figure 2

Below I show C++/CX XAML application running on the left while the JavaScript tutorial runs on the right – both of them reusing the same Contoso WRL project.

SplitScreen 
Figure 3

 The code on the left is the XAML and C++/CX code from my WsaXamlCpp application.  On the right is the code from the WsaJava application (resulting from the online tutorial).

Code 
Figure 4

For the C# application (WsaXamlCpp) I copy and pasted the XAML from the above C++/CX application’s MainPage.xaml source – no change was required.   I then wrote the code in the below image (left pane).  Note that outside of the method names, there is little difference between the C# and C++ code.

CSharpCode

Tags:

Cpp

The remote server returned an error: 227 Entering Passive Mode-The requested FTP command is not supported when using HTTP proxy.

by billkrat 16. November 2013 02:10

The code below is typical of what you will find for doing an FTP upload using C#.  If you don’t have a corporate proxy in the loop I found you don’t even require lines 38-44, it just works.

My issue was that I do have a corporate proxy in the loop and these two errors cost me most of the day. 

There are more dead-ends than answers on the Internet and now that it is over I can actually look back and chuckle at one of the comments made indicating that FtpWebRequest was a joke, don’t use it – they use Code Project’s Ftp Client.  I go through the cycles with it by downloading the code and guess what, it uses FtpWebRequest and got me no closer to the answer. 

Of the two issues I encountered it was the “The requested FTP command is not supported when using HTTP proxy” that ate my lunch (and dinner) because there were more questions than answers on the internet and many of them have you setup the ftp.Proxy (which didn’t work).  The reason line 40 was so hard to find and figure out is because if you put a breakpoint on line 36 you will find that ftp.Proxy IS NULL, so you wouldn’t really think to explicitly set it to null – it is obvious now that that property does something behind the scenes when you apply a null value to it.

image

Creating a Project Template for Visual Studio 2013

by billkrat 15. November 2013 03:58

Microsoft Bug ID: 808660

I was impressed at how easily I could create a Project template for Visual Studio 2013, all I had to do was click on File, select Export Template (ref figure 3) and then select the project I wanted to create a template from. 

The problem I encountered was if I unzipped the contents, modified the template files, and then re-zipped the project – the template zip file is no longer recognized by Visual Studio.  I found a work-around (discussed below).

I required the following highlighted changes for the WRL Class Library template I’ll be using, I created the project using Visual Studio 2012 and now wanted to use it in my Visual Studio 2013 applications.   I updated both the WRLClassLibrary.CPP and .WRLClassLibrary.IDL files to include $safeprojectname$ variables so that my namespaces would be right.  This required me to set the ReplaceParameter to “true” in the vstemplate file.

image

What started me on this adventure was the following excerpt from THIS TUTORIAL:

“When these files are compressed into a .zip file and put in the correct folder, Visual Studio automatically displays them in the My Templates section of the New Project and Add New Item dialog boxes. For more information about template folders, see How to: Locate and Organize Project and Item Templates.”.  

I was stumped when my project template refused to show up, thinking I corrupted the vstemplate file I then tried something as simple as unzipping and rezipping and walla!  I found my problem because even with no changes it no longer shows up.

VS
Figure 1

The work-around was to keep the original .zip file intact.  I double-clicked the .zip file and then would cut/paste the document I needed to work on into a temporary folder.  Once my edits were done I dragged them back into the .zip and was happy to see my project template still in the list.

modify
Figure 2

NOTE: When I create the template I am sure to select the checkbox circled below and I work from the .zip file in the Templates folder – not the “My Exported Templates” folder.  I haven’t tested this process working only from the zip file from the exported templates folder.

Create
Figure 3

Tags: ,

Cpp

WRLClassLibrary for Visual Studio 2013

by BillKrat 13. November 2013 20:31
WRLClassLibrary

If you are here then odds are that you are searching for WRLClassLibrary – as of this writing it is not available for Visual Studio 2013.  I had to install Visual Studio 2012 in order to create a project to work with (I then removed VS2012).

EDITED – I created a template project that will only require you to rename the WRLClassLibrary.cpp and WRLClassLibrary.idl files (to the project name) after you select “WRL Class Library” from the project list. 

Simply drop the following template .zip file into your Libraries | Documents | Visual Studio 2013 | Templates | ProjectTemplates folder and this project template will appear next time you add a C++ project. 

Note: this didn’t work for the Express version of Visual Studio, for it you’ll have to apply the manual approach discussed in the original content of this blog (below).

TEMPLATE: WRL Class Library.zip

VS

The template already has the source code (and link) for the Walkthrough: Creating a Basic Windows Runtime Component Using WRL tutorial in the .CPP and .IDL files.   As noted above, all you’ll have to do is rename the WRLClassLibrary.cpp and WRLClassLibrary.idl to Contoso.cpp and Contoso.idl respectively.  

image

MANUAL APPROACH TO USING THE WRLClassLibrary PROJECT FOLLOWS:

Source: WRLClassLibrary.zip (generated by Visual Studio 2012)

TUTORIAL: Walkthrough: Creating a Basic Windows Runtime Component Using WRL

Note: using Visual Studio Express 2013 for Windows

1. In my Windows Explorer I highlighted WRLClassLibrary and hit CTRL-C and then CTRL-V to paste the highlighted copy of WRLClassLibrary-Copy in figure below:

Note: to comply with the tutorial steps I renamed the copied folder to “Contoso”

Step01

2. I renamed all instances of WRLClassLibrary (namespaces) to “Contoso”.  Note: the namespace must match the project name.

Step02

3. I then renamed all instances of “WinRTClass” to “Calculator” (per tutorial)

Step03

4. I rename Project and then the .CPP and .IDL files to Contoso.cpp and Contoso.idl respectively

Step04

5.  If it exists then delete the Debug folder and all WRLClassLibrary.* files  (reference red icons in image above right pane) – below is what it looked like after cleanup (showing all files)

 Step05

6. At this point the project will compile but the tutorial will fail – I found that there is a project setting that needs to be renamed from WRLClassLibrary to Contoso.  To do this right click on the Contoso (renamed from WRLClassLibrary) project and select “Unload Project”

 Step06

7. Rename the RootNameSpace from WRLClassLibrary to Contoso (in PropertyGroup Label=”Globals” below)

Step07

8. Right click Contoso project and reload it.  Below I show the updates made per tutorial

Step08

Step09

The following are the results after running the tutorial

image

C++ for C# Developers – which project template to select?

by billkrat 22. October 2013 02:49

I’ve decided to take a more patient approach to learning C++ for Windows Store Application development so I’m starting over, and this time I’m going to make more informative choices based on research.   My first stop is Test Driven Development (TDD) in the creation of a ADO.NET like wrapper for SQLite so that I, and other C# developers, can feel a wee bit more at home in working with SQLite.

Creating the Unit Test project was simple enough, but when it came time to create the C++ DLL that would hold the business and data logic layers, I was greeted with a number of options – most of them not applicable to the environment I am targeting and it was not clear to me which template was the best choice.

C++ Version distinctions

Before diving into the different project template types it is important to understand the differences between the versions of C++.   I will be targeting C++ 11 using WRL extensions.

  • C++ 98 …. Approved in 1998 :: ISO/IEC 14882:1998 – the first C++ standard
  • C++ 03 … “Technical Corrigendum” (“TC”), contained bug fixes :: ISO/IEC 14882:2003
  • TR1 …….. contains library extensions for the first standard "”Information technology – Programming 
    Languages – Technical report on C++ library extensions :: ISO/IEC TR 19768:2007 (std::trl)
  • C++ 11 … Approved in 2011 :: ISO/IEC 14882:2011 - new and second C++ Standard
  • C++ 0x … Synonymous with C++ 11 – this title was used with the expectation it would have been
    completed no later than 2009.
  • Extensions
    • C++/CLI ,…language extensions provided for targeting the CLR (.NET in figure 1)
    • C++/CX …. language extensions provided for targeting the WinRT APIs (WinRT figure 2)
      • The C++/CX does not use the CLR or a garbage collector
      • The C++/CX generates native code
    • WRL ……. Windows Runtime Library is a template library that targets Windows 8 without
                       language extensions.

Which project?

"In almost all cases, when you want to create a DLL for use in a Windows Store app, create it as a Windows Runtime component by using the project template of that name. " (see WRC below for more details)

clip_image001

 

Managed Code C++ Code

If you are creating a library that can be used by C++/CLI or any other .NET language such as C# or VB.NET, you are creating a managed assembly.

 

Native C++ code - DLL and LIB

From a C# perspective the distinction between the DLL and a LIB (at ten thousand feet) can be compared to a C# Class Library project that is included in a solution (C++ Static Linked Library, aka LIB) versus simply added as an assembly reference (C++ Dynamic Linked Library, aka DLL). A project that is included in the solution has all of the source code and is less likely to have versioning issues should the project code change but will be larger in size and contain all source, even if only one function from the library was required.

The more technical definitions follow:

DLL - Dynamic Link Library (Windows Store App)

clip_image002

From <http://msdn.microsoft.com/en-us/library/windows/apps/hh699881.aspx>

You can use Visual Studio to create either a standard Win32 DLL or a Windows Runtime component DLL that can be consumed by Windows Store apps. A standard DLL that was created by using a version of Visual Studio or the Visual C++ compiler that's earlier than Visual Studio 2012 may not load correctly in a Windows Store app and may not pass the app verification test in the Windows Store.

LIB - Static Library (Windows Store App)

clip_image003

From <http://msdn.microsoft.com/en-us/library/windows/apps/hh771041(v=vs.120).aspx>

A static library that's used in a Windows Store app can contain ISO-standard C++ code, including STL types, and also calls to Win32 APIs that are not excluded from the Windows Store app platform. A static library consumes Windows Runtime components and may create Windows Runtime components with certain restrictions

Excerpt From http://msdn.microsoft.com/en-us/library/1ez7dh12(v=vs.120).aspx

A dynamic-link library (DLL) is an executable file that acts as a shared library of functions. Dynamic linking provides a way for a process to call a function that is not part of its executable code. The executable code for the function is located in a DLL, which contains one or more functions that are compiled, linked, and stored separately from the processes that use them. DLLs also facilitate the sharing of data and resources. Multiple applications can simultaneously access the contents of a single copy of a DLL in memory.

Dynamic linking differs from static linking in that it allows an executable module (either a .dll or .exe file) to include only the information needed at run time to locate the executable code for a DLL function. In static linking, the linker gets all of the referenced functions from the static link library and places it with your code into your executable.

Using dynamic linking instead of static linking offers several advantages. DLLs save memory, reduce swapping, save disk space, upgrade easier, provide after-market support, provide a mechanism to extend the MFC library classes, support multilanguage programs, and ease the creation of international versions.

 

WRC - Windows Runtime Component

clip_image004

From <http://msdn.microsoft.com/en-us/library/windows/apps/hh699881.aspx>

In almost all cases, when you want to create a DLL for use in a Windows Store app, create it as a Windows Runtime component by using the project template of that name. You can create a Windows Runtime component project for DLLs that have public or private Windows Runtime types. A Windows Runtime component can be accessed from apps that are written in any Windows Runtime-compatible language. By default, the compiler settings for a Windows Runtime component project use the /ZW switch. For more information, see Creating Windows Runtime Components in C++.


WRL

The WRL enables you to more easily implement and consume Component Object Model (COM) components. It provides housekeeping techniques like reference-counting to manage the lifetime of objects and testing HRESULT values to determine whether an operation succeeded or failed.

The purpose and design of the WRL is inspired by the Active Template Library (ATL), which is a set of template-based C++ classes that simplify the programming of COM objects. Because WRL uses standard C++ to wrap the Windows Runtime, you can more easily port and interact with many existing COM components written in ATL to the Windows Runtime. If you already know ATL, you might find that WRL programming is easier.


ATL

clip_image005

From <http://msdn.microsoft.com/en-us/library/3ax346b7(v=vs.90).aspx>

The Active Template Library (ATL) is a set of template-based C++ classes that let you create small, fast Component Object Model (COM) objects. It has special support for key COM features, including stock implementations, dual interfaces, standard COM enumerator interfaces, connection points, tear-off interfaces, and ActiveX controls.

My take on ATL is that it was used with MFC and is provided for backwards compatibility (I don't see new guidance on ATL in the MSDN libraries). It is important to not reference any non-WinRt API calls for the reasons noted in the following excerpt:

I have Windows library developed in C++ that uses ATL collections, ATL CString and COM interfaces with CComPtr heavily. I removed all non-winrt-allowed API calls from the library, and it builds fine, so I wrapped the library in a C++/CX ref-class and I am trying to use it from a Windows Store App. The application runs fine, but the Win-Store App certification fails with the following error: read more

 

CLR (managed)

clip_image006

From <http://msdn.microsoft.com/en-us/library/8bs2ecf4.aspx>

The .NET Framework provides a run-time environment called the common language runtime, which runs the code and provides services that make the development process easier.

Compilers and tools expose the common language runtime's functionality and enable you to write code that benefits from this managed execution environment. Code that you develop with a language compiler that targets the runtime is called managed code; it benefits from features such as cross-language integration, cross-language exception handling, enhanced security, versioning and deployment support, a simplified model for component interaction, and debugging and profiling services.

 

MFC (managed)

clip_image007

From <http://msdn.microsoft.com/en-us/library/583ya1kc(v=vs.100).aspx>

The Microsoft Foundation Class Library is an application framework for programming in Microsoft Windows. Written in C++, MFC provides much of the code necessary for managing windows, menus, and dialog boxes; performing basic input/output; storing collections of data objects; and so on. All you need to do is add your application-specific code into this framework. Given the nature of C++ class programming, it is easy to extend or override the basic functionality that the MFC framework supplies.

From <http://msdn.microsoft.com/en-us/library/aa697420(VS.71).aspx>

The Microsoft Foundation Class Library (MFC) encapsulates, or "wraps," much (but not all) of the Win32 API. MFC versions 2.x and earlier encapsulated the 16-bit Windows API. MFC supplies classes representing key Windows objects, such as windows, dialog boxes, brushes, pens, and fonts. The member functions of these classes wrap most of the important Win32 API functions associated with the encapsulated object. The MFC class member function calls the Win32 API function, and might add functionality.

 

Win32

clip_image008

From <http://msdn.microsoft.com/en-us/library/aa697420(VS.71).aspx>

The Win32 application programming interface (API) provides building blocks used by applications written for the Microsoft Windows operating system family. The Win32 API defines the 32-bit members of the Windows family from the programmer's point of view. Some members of the Windows family use the entire Win32 API, while others use subsets. For details, see Windows 95/98/Me Limitations.

Note in figure 1 below that Win32 and WinRT (Windows 8 store apps) are two separate APIs. Windows 8 APIs do include a "subset" of Win32 (ref figure 2) but it is not the actual Win32 API used by Desktop Apps.

clip_image009

Figure 1

clip_image010

Figure 2