Web Mobile Hybrid Framework Choices and Getting Started

November 30, 2015

Today, the application framework choices for web sites, web client apps (SPA), web mobile, hybrid mobile, or web desktop development are awesome.  They all provide the promise of application development using HTML5, CSS, and JavaScript.

Navigating these choices is not an easy task at times because you’re trying to match your scenarios and requirements with the available frameworks.  We developers would like to be able to pick a technology, platform, and tooling and get to work.  However, you’ll need to study the available frameworks before you can make an informed decision.  There is a great benefit in studying available options, “you learn what’s outside of your circle.” 

You really can’t be in a hurry.  Do you want to struggle later, or do you want to do your homework now?  It’s like paper prototyping vs. coding and then changing it over and over.  Pick you poison.  I favor studying and paper prototyping.

My steps for learning about a framework:

  1. Read the documentation.  RTFM – Read The Free Manual.  Don’t just breeze through the API docs; be sure to read the information about the framework, why it was created, why features were implemented they way they were, what have the developers learned and how it has evolved.  What are the happy paths for this framework.  Some frameworks, straying too far from their happy path can be costly; what I mean is, at first it looked easy and fun, then real-world use case come into play and now you have to struggle to create workarounds.
  2. Read other developer reviews.
  3. Find sample projects that other developers have authored using that framework.
  4. Watch YouTube videos on the framework.
  5. Take course on the framework, e.g. Pluralsight.
  6. Write some throwaway spikes.
  7. Extensibility and plug-ability.
  8. How are the applications built with the framework themed?  The ability to change themes and/or change the color pallet easily can be a critical requirement and can’t be overlooked.
  9. Finally, write an app that has real-world scenarios.

Ultimately you should make your choice based on your own research, your requirements, your teams capabilities, and not just what is new and shinny.

My Journey to Aurelia

I’ve been using ES5, TypeScript, AngularJS, Angular Material, and Ionic for building hybrid-mobile and SPA applications.

I was successful with each of these frameworks.  But in the back of my mind, I kept thinking, there must be an easier, more productive way for me to author these types of applications.  I had difficulties when I strayed from the happy path with Ionic and Angular Material.  At times, layout or styling issues were a real pain.

It’s not the fault,  nor a defect in these frameworks.  Framework teams are publishing an API that must meet the needs and scenarios of, well, the whole world.  I’ve used a hyperbole to illustrate their daunting tasks.

As a long-time framework and API architect-developer, I firmly believe that frameworks should not require too much goo code or ceremony to use them.  I also believe that they should not have holes in common use cases.

One consideration that plagued me was theming.  I checked out Polymer and the wide range of themes you can use day one.  This was truly a breath of fresh air.

In the end, I chose Aurelia for the following reasons:

  1. It meets my requirements for the types of apps I’ll be building.
  2. Rob Eisenburg.  His track record is flawless.  I subscribe to and write my own frameworks like he does.
  3. Aurelia has full blown corporate support if your company or team needs it.
  4. They have a very active community on glitter.im where you can interact with many developers, Rob, and the Aurelia team.
  5. It uses the very latest JavaScript language ES6 or ES2015.  It’s forward thinking will also leverage ES2016 when it’s made available.
  6. It’s tenants are simple and pervasive: view and view model pair (HTML file, JavaScript file).  Whether you’re creating a web page, a reusable template, composing some dynamic HTML, or authoring a custom element, you have the same two working together; the view and view model.
  7. It’s extensible, pluggable, and flexible.  It’s happy path is very wide and open.
  8. I can use it to create web and mobile SPA apps, hybrid apps, and JavaScript desktop (Electron) apps.
  9. I can use any tooling I want.  WebStorm, Atom, notepad, Visual Studio, Sublime, etc..
  10. I can author the applications on Windows, Mac, or Linux (including Raspberry PI)
  11. My applications are free of ceremony code.  The only time I know I’m using Aurelia is when I import a framework module in a view model.
  12. I believe that once I master Aurelia, I’ll be writing 50-70% less HTML markup and JavaScript that I would in AngularJS 1.x or 2.x.  Even if I only have a 40% saving, it will be a huge win.  Less code means, faster time to market and easier maintenance.
  13. Less framework intrusion means less onboarding time required to get junior developers productive.

My Aurelia Adoption Plan

Aurelia is in Beta 1 on the day I’m writing this.  The team is working super hard and will over the next year provide out of the box themes, components, custom elements, etc. to really simplify while at the same time, greatly expand the out of the box capabilities of Aurelia.

I don’t want to take a dependency on Bootstrap or other cool CSS library, nor jQuery.  Not that these are bad, or  are poor choices because they are not, but I’m making a decision to write clean and simple apps with less external dependencies. I do want to know all the details.  I know that in the end, my apps will be much easier to maintain over time, will be easier to write, and will be easily upgradable for years to come.

  1. Master Aurelia fundamentals such as: routing, data binding, module loading, etc..
  2. Master Aurelia components and custom elements.  (if your an Angular person, think directives)
  3. Write my own set of components and custom elements to support my scenarios.  I don’t need the kitchen sink, I only need to meet my requirements.  Think, Yagni.  You can easily extend Aurelia components or custom elements as requirements change.
    1. View data form HTML markup must be 50% less than what I’m currently writing in Angular.  This is achieved by leveraging the Aurelia component and custom element capabilities, so that I or other developers won’t have to write ceremony HTML mark up.
  4. Write my own cross-cutting concerns components and services.  For example:  dialog, toasts, logging, client error handling, server error handling, security, etc..  No developer should have to fool with one of these concerns in client-side code, ever.  A simple API provides these types of services for the entire application.
  5. Write my own SASS CSS themes for my apps.
  6. Create an one exemplar theme-able application for web, mobile web, hybrid-mobile, and desktop web that has all the UI Elements, and UI patterns that my current requirements demand.  Prove out the components, custom elements, and data validation solution.
  7. Master unit testing.
  8. Master bundling, minification, and deployment scenarios.

As you can see, I’m putting the time in up-front (in advance of a big project) to solve and master the above basic application building blocks.

My Roadmap

Password Manager

My first app that I’ll release will be a cross-platform, cross-device, password manager.  In 2008 did a Code Project Article teaching on WPF MVVM with a Cipher Text Password Manager.  I use the application everyday, some 7 years later.

I’m going to write this app using JavaScript for Windows, OS X, Linux, IOS, and Android.  The app will use Firebase as it’s data store.

This app will be published on Code Project, my blog, and github.

It will contain everything I’ve learned about Aurelia, all my components, custom elements, themes, and SASS CSS.

Crank

Crank is a cross-platform,  metadata driven, code generator.  Crank will generate any code for any language.  I’ve used the C# version of this application for many years with great success.

I won’t be able to give out the source for Crank, but the app will be free, no license fee, etc.. I will publish a book and videos and will change a small fee for these.

High Octane Online Store System

As a side-project and possible revenue stream for my family, I’ll use the above to write a online store system.  This will enable my non-technical customers to get online quickly.  It will feature the ability to manage multiple warehouses, sell to their customers online, in person at a brick and mortar store, or portable kiosk.  Each customer will have their own custom, customer facing web application.

Close

Speaking as a WPF evangelist for many years, a PM on Microsoft patterns and practices Prism Guidance, a PM on Microsoft patterns and practices Project Silk Guidance, I firmly believe using the above framework and code, I’ll be much more productive writing a JavaScript desktop application than I would be writing the same app in WPF.  I’ll will have much less view markup and much less view model code.

Best to you on your own journey with client-side, desktop, and servers-side JavaScript development.

Have a great day,

Just a grain of sand on the worlds beaches.


Electron ES6 Aurelia MongoDB

November 27, 2015

For a thousand reasons, I wanted to entitle this post, “The Bleeding Edge is Bloody.”

If you are not familiar with Electron, ES6, Aurelia, or MongoDB, this post may not make much sense to you.  However, you can read the post, and head over to the github repro and browse the code.  You’ll see that its clean and simple.  Actually wrote this using the Atom editor on my Mac.  FYI:  Atom is an Electron app.

There are links to resources in the github repro README.md for getting up to speed on these technologies if you have not seen them before or are just getting ramped up.

Introduction

It’s taken me 3 long weeks, giving up weekends and nights to finally figure out how to use Electron, ES6, Aurelia, and MongoDB in a Thick-Client application.  This blog post starts with my painful journey and then dives into how easy the solution really is.  Truest me, its so easy now that I know how to put the pieces together.

Where do I start?  Why did I need to write an Electron app?

I’ve used my Crank Meta-data Code Generation App for years to radically speed up development time building .NET Applications.  It generates all stored procs, class entities, XAML forms, XAML Infragistics Data Grids, SQL Server TVP’s, code snippets, etc..

Now that I’m doing a good bit of development on Mac (yes, Karl is still writing C# on an almost daily basis) I wanted to leverage the same tools I’ve had for years on Windows.

The requirements for my new Crank App are:

  1. Desktop app
  2. Run on Windows
  3. Run on Mac
  4. Run on Linux
  5. Local database that runs on the above platforms. 
  6. Works for a single developer or a team of developers.
  7. Allow team developers to work on a machine of their choosing: Windows, Mac, or Linux.
  8. No investment cost for anything including the data store and this app.
  9. Not a SAS app that requires me to host the application or user data.
  10. No software license fees, keys, etc.  (I didn’t want this headache)
  11. (Fine print: to get some dollars for all my time and other investments, I’ll publish a book and videos on Leanpub. The book is the instruction manual for the application and code generation.)

I chose Electron because in my opinion, it is the best tool for available writing and maintaining a cross-platform apps.  I allows me to use my HTML, CSS, and JavaScript skills I have.  Same code-base for all platforms.

I chose ES6-ES2015 because it is the latest JavaScript standard that enables me to write clean code using the latest features of the language like Promises.

I chose Aurelia because I believe that frameworks should not get in the way of the developer and not require constant ceremony code to leverage their features and capabilities. 

I’ve written production apps using Ionic, AngularJS, and Angular Material.  These apps were all successful, customers happy.  BUT, the development cost and in some cases, the learning curve was high when you didn’t follow the frameworks prescribed happy path.  When I compare the how much less code and ceremony I have to endure then writing an Aurelia apps compared to an AngularJS or AngularJS 2 app, I’m so glad Rob Eisenburg and his team wrote Aurelia.  Is Aurelia perfect? Not yet, but for a Beta 1 product, I’m having zero issues and outstanding support getting help.

I chose MongoDB because it runs on Windows, Mac, and Linux.  It can run on premise or cloud servers.  I need to support a wide range of install scenarios ranging from, single user on Mac or Windows, to large development teams with developers on various platforms.  MongoDB provides this capability. 

Data Store Journey

Initially, I had selected MongoDB but couldn’t get it to work inside an Aurelia app.  I kept getting a missing Kerberos.js file when System.js was trying to load the MongoDB ES6 module.  I spent a lot of time trying to get this to work to no avail.

I then looked at Azure DocumentDB.  I really like DocumentDB.  Simple SQL like syntax for querying the database.  It didn’t have a ES6 module for accessing the database so I wrote my own in ES6 using Promises.  I was ready to go with this but then finally figured out how much it really costs.  $25 per month, per collection.  This was an immediate non-starter for my scenario.  Great service with very cool capabilities, but too costly for this small app.

I then looked at Firebase. Like DocumentDB, Firebase simply rocks.  A 1GB or less production database is only $5 per month. No other cloud service even comes close to this number.  My initial pain points was figuring out how to write ES6 code and leverage Promises.  I wrote myself a ES6 wrapper and got this working, but the cost thing for the user was nagging me.

Giving up my Black Friday day off and motorcycle riding, I when back to give MongoDB one more try.  It was by accident that I finally figured out that System.js module loading was the problem, and not Electron or Aurelia.

Why Not Just Use a Web Service?

Yep, several developers asked me the same question. 

In the current development world, there are many requirements, scenarios and solutions for them.  That are no silver bullets, or one size fits all.  The cloud is not the answer for every application.

I like Thick-Client, two-tier applications and write them when appropriate.

Also, didn’t want to write a webapi or MEAN Stack Express api for this app. I could of and almost did. But, that’s a lot more code I have to write and maintain without any payback whatsoever. 

The Application and Solution

The application is hosted on my github Oceanware account.

I’ve provided an easy to follow readme to get you up and running on Mac or Windows.  I need to spin up a Ubuntu VM for testing on Linux.  Have not had the time yet.  If you’re on Linux, this app will run and build on that platform as well (thanks to Electron and Chromium).

The application is the simplest Electron, Aurelia app I could write. When you run the app, you’ll see a brief spinner and message and then the Home view.

“We are connected” is your success message.  You have connected to you MongoDB server from with an Electron, ES6, Aurelia app.

 screenshot

MongoService

This class was the reason I was struggling for 3 weeks.  Before I found the solution I was using the imports statement to bring in the mongodb module.  You see an example of using imports in the next section below.

This simple starter code is straight from the MongoDB documentation that is written in ES5.

Below I’ve crafted an ES6 class that first brings in mongodb using the familiar node.js required(…) method instead of using imports.

The testConnection method leverages the ES6 Promises, wrapping the MongoClient.connect method. 

IMO: Promises make the method consumer code much easier to read and write, i.e. no callback hell.

 export default class MongoService {  
  constructor() {  
   this.MongoClient = require('mongodb').MongoClient;  
  }  
  testConnection() {  
   return new Promise((resolve, reject) => {  
    this.MongoClient.connect("mongodb://localhost:27017/test", function(err, db) {  
     if(!err) {  
      resolve("We are connected");  
     } else {  
      reject(err);  
     }  
    });  
   });  
  }  
 }  
Home

The below Home class is an example of an Aurelia view model. Except for the inject feature, there is no Aurelia framework goo or ceremony, just ES6.

Modules are imported into a class by using the import statement.  The System.js module loader does all the heavy lifting.  As I’ve stated above, I tried using import and System.js to bring in mongodb, but it always failed.

The constructor takes a single argument that is injected in.  I’m injecting in the above MongoService.

The activate method is one that you would expect any navigation or routing framework to have, but not all do.  This method is invoked by the Aurelia router as part of the routing lifecycle.

You can see my super simple code for calling testConnection.  Once you’ve used Promises, you love and use them.  Clean code.

 import {inject} from 'aurelia-framework';  
 import MongoService from './mongoService'  
 @inject(MongoService)  
 export class Home {  
   constructor(db) {  
    this.db = db;  
    this.title = "Home";  
    this.connectionResults = "";  
   }  
   activate() {  
    this.db.testConnection()  
     .then((promise) => this.connectionResults = promise)  
     .catch((err) => this.connectionResults = err);  
   }  
 }  
MongoDB Node Module

An Electron App is actually simple once you understand the folder structure.  Everything in the root folder belongs to the Electron portion of your application.

Everything in the /src folder belongs to the app that Electron is hosting, in our example, its an Aurelia app.

You’ll quickly notice that there is a package.json file in the root and /src folders.  The one in the /src folder is for application dependencies that can’t be loaded using jspm from the root folder.  MongoDB is the only node module I’ve had to load in this manner.  That’s why I’ve got two package.json files.

screenshotDirectory

Close

I know that I have not done any application how to teaching, or framework explanations.  The real purpose of this blog post was to demonstrate that you can write an Electron, ES6, Aurelia, and MongoDB Thick-Client application.

Have a great day,

Just a grain of sand on the worlds beaches.


XAML IntelliSense Presenter for Visual Studio 2013

May 21, 2014

Current Version:  3.0 (21 May 2014)

The Visual Studio 2013 XAML Editor has really come a long way since Visual Studio 2010. You can read up on the new features in this blog post.

I originally released this tool in April 2010 and have rebuilt it for Visual Studio 2013.

FullControls FullProperties

FullNamespace

Features

  • Pascal case lookup
  • Optional narrowing list filter
  • Filtering based on item type
  • Toggle narrowing filter Hot Key (ALT + .)  (ALT PERIOD)
  • Toggle namespace filter Hot Key (ALT + ,)  (ALT COMMA)
  • xmlns IntelliSense options
    • Show/hide only solution assemblies
    • Show/hide schemas

Filter settings persist for the current Visual Studio session

Pascal Case Lookup

Pascal case lookup is always enabled regardless of the narrowing filter option.  When all of your text is upper case this feature kicks in to quickly locate the item you are looking for.  Note, this feature requires at least two upper case characters be entered before kicking in.

The feature locates entries that start with the first upper case character you entered, then matches on additional upper case characters.

The below image demonstrates the Pascal case lookup.

PascalLookupOne

Locating an assembly using the xmlns Pascal case IntelliSense is super fast.

PascalLookupTwo

Narrowing List Filter

When the narrowing list filter is enabled it provides two features. 

You can enable/disable this feature by clicking the Filter icon or by using the hot key (ALT + .) (ALT PERIOD).

  • Narrows the list of displayed items by only including items that contain your text
  • List item selection priority
    • Selects the first match that starts with your text
    • Selects the first entry that contains your text
Narrowing List Filter Enabled Narrowing List Filter Disabled
NarrowingEnabled NarrowingDisabled
With narrowing enabled, see how easy it is to locate Grid.Row or Grid.RowSpan.  
NarrowingEnabledTwo  

List Item Type Filter

This was my original driving force behind writing this extension.  Was found myself frustrated when a type in XAML has 2 properties, 4 events and 75 namespaces listed in the IntelliSense listing.  Problem solved.

New in version 2.0 is the addition of the namespace filter toggling hot key (ALT + .)  (ALT PERIOD).  This hot key is tied to the namespace icon, making it faster to show/hide namespaces.

Standard list of items, notice the multitude of namespaces that are listed.

Namespaces

Toggle the namespaces ToolBar button by clicking it and they are filtered for you.

NoNamespaces

The other ToolBar filter buttons work the same.  The gray background is the enabled state.  The white background with grayscale image is the disabled state.

xmlns IntelliSense

The below image demonstrates the two filter buttons in the xamls IntelliSense presenter.

  • Show only solution assemblies is enabled.
  • Remove schema entries is enabled.

xmlnsOne

Another way to locate your assemblies very quickly is demonstrated in the below image.  The two filter buttons in the default state and I entered WC to quickly find an assembly in my solution. 

This is another example of the Pascal case filtering.

xmlnsTwo

In the below image I’m taking advantage of the narrowing filter to locate all assemblies that have the word media.  When searching the text with this type of search, the entire entry line of text is searched including the assembly name inside the (…).

xmlnsThree

Extension Manager

To view your installed extensions use the Visual Studio 2010 menu, Tools, Extension Manager…

ExtensionManager

From here you can either disable or uninstall extensions.

 ExtensionManager

You can also configure settings for extensions using the Tools, Options dialog.

ToolsOptions

Requirements

Visual Studio 2013

Downloads

XAML IntelliSense Presenter on the Visual Studio Gallery

Close

Enjoy this XAML Editor extension.

Have a great day,

Just a grain of sand on the worlds beaches.


Tucking ViewModels Beneath Views in Solution Explorer in Visual Studio 2013

October 30, 2013

VMTuckedAway

Back when I was using Visual Studio 2010 a few weeks ago I had a cool macro that would allow me to select a view and viewmodel file in the Solution Explorer, run the macro and then the viewmodel would be nested nicely under the view as pictured above.

Well… Beginning with Visual Studio 2012 (which I skipped over), Visual Studio no longer support macros.  Kind of a bummer since many developers wrote macros and depended on them for automating tasks, etc.

The good news is, writing a Visual Studio 2013 VSPackage is not really that difficult and the DTE macro code can pretty much be copied and pasted and with a little editing you’re up and running again. With the VSPackage you also get the benefit of not watching that spinning and dancing macro icon that would occasionally appear in the Windows Taskbar which caused your macro to freeze for awhile.

Background

I like to tuck my viewmodels beneath the view.  To me, it makes for nice organization and condenses the number of top level files I have to view in the Solution Explorer.

Most of my viewmodels have a one-to-one relationship with its view.  For those that don’t, I don’t tuck them beneath.

I also like to name my views and viewmodels according to the above pattern. For me, it keeps things clean and consistent.

Introducing Visual Studio 2013 Extension View Model Tuck Away

The below image was captured from the “Extensions and Updates…” dialog after I installed the VSPackage.

ExtensionManager

Operation

The digitally signed package available on the Visual Studio Gallery operates like this:

  • Developer selects a view and viewmodel file in the solution explorer
  • Developer runs the ViewModel Tuck Away command

The VSPackage will verify that:

  • Two files have been selected in the Solution Explorer
  • That one file has a .xaml file extension and contains the word “view”
  • That one file has a .cs file extension and contains the word “viewmodel”

The VSPackage will then tuck the selected viewmodel beneath the selected view.

During the execution of the VSPackage command, the Visual Studio Status Bar text will be updated to reflect the success or failure of the command.

I wrote the VSPackage this way to enforce naming standards at my work and home projects.

I know that some (many) may not like this.  No problem, the source is on GitHub (see Source below) and you can very easily modify it, rebuild the solution and double click on your new VSIX file.

Surfacing the VSPackage Command in Visual Studio 2013

You can surface the VSPackage Command in three ways:

  • Tools Menu, ViewModel Tuck Away
  • Add command to a Toolbar
  • Provide shortcut key for command (not really practical since you used the mouse to select the two files, may as well click a Toolbar icon or text.)

By default the command is added to the Tools Menu as seen below:

ToolsMenu

To add the command to a Toolbar follow the numbers below. #2 below allows you to select the Toolbar you want the command to appear on.  #7 allows you to position the command on the selected Toolbar.

AddCommandToToolBar

I added my command to the Standard Toolbar and moved it to the right side as pictured below.  For me, that little icon will do.

ToolBarSetup

However you may want to see the commands text as pictured below. To do this, use the above “Modify Selection” ComboBox just below #7 above and select “Image and Text”.

ToolBarSetupWithText

What is a VSPackage and How Did You Do This?

You can read all about Visual Studio 2013 VSPackages here. According to this MSDN article:

“VSPackages are software modules that extend the Visual Studio integrated development environment (IDE) by providing UI elements, services, projects, editors, and designers.”

To author your own VSPackage you’ll need to download and install the VS 2013 SDK from here, look towards the bottom of the page in the “Additional Software” section for Visual Studio SDK. The documentation for the SDK is here.

After installing the SDK you’ll get some new templates (very good I might add). To fire up a new VSPackage follow the numbers.

NewVSPackage

I strongly suggest studying the default VSPackage that the template creates.  I adds a Tools menu command that displays a message box.  Simple, but there is a lot of plumbing code it creates for you that you pretty much don’t have to fool with. The VSPackage only has a few files of “plumbing” making it easy to understand how it all fit together.

The below code is the core functionality required to identity two selected items, figure out which is the view and viewmodel and then set the dependency.

Of interest is how much power VSPackages have access to. For example the line of code: var dte = (DTE)GetService(typeof(DTE)); provides access to the DTE.  Most macro programmers are already familiar with the power and features exposed by the DTE. Once your command is invoked, you fire up the DTE and code away.  Not a bad upgrade path from macros or Visual Studio Add-Ins which are depreciated in VS 2013.

In a similar fashion this line of code: var uiShell = (IVsUIShell)GetService(typeof(SVsUIShell)); provides the developer access to the IVsUIShell capabilities.

As I mentioned above, you can use your own custom logic for determining which selected file is the parent and which will be the new child of the parent.  There are many techniques for determining this, like I said I chose to enforce naming standards for my views and viewmodels.

Boolean IsView(String targetFileName) {
    var extension = Path.GetExtension(targetFileName);
    return !String.IsNullOrWhiteSpace(extension) && extension == ".xaml" && 
            targetFileName.IndexOf("view") > -1;
}

Boolean IsViewModel(String targetFileName) {
    var extension = Path.GetExtension(targetFileName);
    return !String.IsNullOrWhiteSpace(extension) && extension == ".cs" && 
            targetFileName.IndexOf("viewmodel") > -1;
}

/// <summary>
/// This function is the callback used to execute a command when the a menu item is clicked.
/// See the Initialize method to see how the menu item is associated to this function using
/// the OleMenuCommandService service and the MenuCommand class.
/// </summary>
void MenuItemCallback(Object sender, EventArgs e) {
    try {
        //get access to the familar DTE object.
        var dte = (DTE)GetService(typeof(DTE));

        if (dte.SelectedItems.Count == 2) {
            String fileNameOne = dte.SelectedItems.Item(1).ProjectItem.FileNames[1].ToLower();
            String fileNameTwo = dte.SelectedItems.Item(2).ProjectItem.FileNames[1].ToLower();
            ProjectItem viewProjectItem;
            ProjectItem viewModelProjectItem;

            //need to figure out which select items are the view and viewmodel
            if (IsView(fileNameOne) && IsViewModel(fileNameTwo)) {
                viewProjectItem = dte.SelectedItems.Item(1).ProjectItem;
                viewModelProjectItem = dte.SelectedItems.Item(2).ProjectItem;
            } else if (IsView(fileNameTwo) && IsViewModel(fileNameOne)) {
                viewProjectItem = dte.SelectedItems.Item(2).ProjectItem;
                viewModelProjectItem = dte.SelectedItems.Item(1).ProjectItem;
            } else {
                dte.StatusBar.Text = "Must select a view.xaml file and a viewmodel.cs " +
                                     "file in the solution explorer.";
                return;
            }

            //line of code that creates the dependency between files.
            viewProjectItem.ProjectItems.AddFromFile(viewModelProjectItem.FileNames[1]);

            //show the tucked into viewmodel
            viewProjectItem.ExpandView();
            dte.StatusBar.Text = "Your viewmodel is now dependent on its view.";
        } else {
            dte.StatusBar.Text = "Must select a view.xaml file and a viewmodel.cs file in " +
                                 "the solution explorer.";
        }
    } catch (Exception ex) {
        var uiShell = (IVsUIShell)GetService(typeof(SVsUIShell));
        var clsId = Guid.Empty;
        Int32 result;
        var message = String.Format("Exception occurred in VmTuckAway: {0}", ex);
        ErrorHandler.ThrowOnFailure(uiShell.ShowMessageBox(
            0,
            ref clsId,
            "VmTuckAway Exception",
            message,
            String.Empty,
            0,
            OLEMSGBUTTON.OLEMSGBUTTON_OK,
            OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST,
            OLEMSGICON.OLEMSGICON_INFO,
            0, // false
            out result));
    }
}

VSIX Manifest Files and VSPackage Assets

If you want to make your own VSPackages you’ll also want to understand the, “source.extension.vsixmanifest” file and how to properly edit it.

You need to read the VSIX Extension Schema 2.0 Reference found here. Very easy read with good examples.

One tip I remembered the hard way was the file property “Include in VSIX” which must be True for VSPackage assets you include in the “source.extension.vsixmanifest.”

These Large and Small icons provide a nice UI for your VSPackage in the “Extensions and updates…” dialog.

IncludeInVSIX

GitHub Source

The source code can be downloaded from GitHub here:

https://github.com/Oceanware/VmTuckAway

Download Signed VSPackage Extension on Visual Studio Gallery

http://visualstudiogallery.msdn.microsoft.com/cbe8ae32-555e-4e10-91b9-ee0d57bab037

Close

Hopes this helps someone and have a great day,

Just a grain of sand on the worlds beaches.


Prism Application Core Scenario Broken In Visual Studio 2013 XAML Designer

October 29, 2013

Since the beginning of October 2013 I’ve been doing a lot of spiking using Visual Studio 2013 and have discovered this is a great product and also has some differences between Visual Studio 2010.

Anyone following this blog knows that I love WPF and patterns & practices Prism Library. Not only the library but the documentation (guidance) for creating composite applications.

As I was converting VS 2010 solutions at work to VS 2013 I started running into problems with my Prism applications and the module views not loading in the XAML Designer and the XAML Editor displaying errors that were not in VS 2010.

I have reported my findings to the XAML Tools Team.

I have a logged a connect bug here:  https://connect.microsoft.com/VisualStudio/feedback/details/806969/prism-application-core-scenario-broken-in-visual-studio-2013-xaml-designer

After a few days I found a workaround for the problem and will share it at the bottom of this post.

Working Prism Core Scenario Visual Studio 2010

See Source Control section below.  The WorkingCoreScenario.zip file should be unzipped and opened using Visual Studio 2010 w/SP1.

A core design practice of composite applications is to break the application into discrete modules (assemblies).  The main application executable will discover the modules at runtime and load them.  The main executable does not have any references to its modules. This very loose coupling of the application and its modules is a core design principle of Prism and composite applications. See Modular Application Development chapter.

The below image shows the pieces of the scenario. Notice that the WorkingCoreScenario assembly does not have a reference to the NotReferencedFormsLibrary. This forms library represents a Prism module that would have all the views and viewmodels for a module.

PrismCoreScenarioSolution

The above App.xaml file contents are shown below.  (NOTE:  I’ve had to break the Source line below because the text is too long to fit.)

Below I’m merging a resource dictionary from the Control Library. This allows the main executable and all modules to reference resources in that compiled assembly.  I typically put images and common resources in a compiled assembly so that the XAML Designer parser does not have to keep parsing the resource dictionary each time it loads a XAML file.

<Application 
    x:Class="WorkingCoreScenario.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary 
                    Source="pack://application:,,,/ControlLibrary;component/Resources/
                            ControlLibraryResourceDictionary.xaml" />
            </ResourceDictionary.MergedDictionaries>
            <SolidColorBrush x:Key="redBrush" Color="Red" />
            <SolidColorBrush x:Key="yellowBrush" Color="Yellow" />
        </ResourceDictionary>
    </Application.Resources>
</Application>

If you open NotReferencedFormsLibrary UserControl1.xaml in the XAML Designer you’ll see:

WorkingCoreScenarioVS2010Designer

If you open NotReferencedFormsLibrary UserControl1.xaml in the XAML Editor you’ll see:

WorkingCoreScenarioVS2010XAMLEditor

Broken Prism Core Scenario Visual Studio 2013

See Source Control section below.  The BrokenCoreScenario.zip file should be unzipped and opened using Visual Studio 2013 RTM.

If you open NotReferencedFormsLibrary UserControl1.xaml in the XAML Designer you’ll see that neither of the resources App.xaml are available in the XAML Designer.

BrokenCoreScenarioVS2013Designer

If you open NotReferencedFormsLibrary UserControl1.xaml in the XAML Editor you’ll see that none of the resources in App.xaml are available.

BrokenCoreScenarioVS2013XAMLEditor

Discussion and Workaround for Visual Studio 2013

The differences between VS 2010 and VS 2013 have broken a core Prism application scenario. I really like the Prism guidance for creating modules that are not referenced by any other assembly. This very loose coupling promotes well structured and designed applications that are not brittle and will stand the test of time and change.

For now, the only workaround I’ve got to work is to have the main assembly reference each of the modules.  Adding the reference then allows the modules to have access to resources in App.xaml including merged resources.

Source Code

The two above scenarios are in separate zip files on my Oceanware GitHub account.

https://github.com/Oceanware/BrokenPrismCoreScenario

The above repro contains:

  • The BrokenCoreScenario.zip file should be unzipped and opened using Visual Studio 2013 RTM.
  • The WorkingCoreScenario.zip file should be unzipped and opened using Visual Studio 2010 w/SP1.

To create the BrokenCoreScenario solution I simply copied the WorkCoreScenario solution to a machine with VS 2013 and opened it.  No other changes were made.

NOTE:  Prism is not required to open these demo solutions.

Close

Hopes this helps someone and have a great day,

Just a grain of sand on the worlds beaches.


Moving WPF Applications From Visual Studio 2010 to 2013 – Some Gotchas and Solutions

October 24, 2013

I have spent the better part of two weeks trying to move my WPF Prism application from Visual Studio 2010 to Visual Studio 2013. As of 10 minutes ago, the application has been moved and is super shape.

Problems That Had To Be Solved

1.  The new XAML Designer would not load any resources or merged dictionary resources in App.xaml resulting in errors for all StaticResources in my views.

2.  FXCop settings from VS 2010 causes CA00053 warnings in the Code Analysis Window.  I’ve already blogged about this and possible options here:  Visual Studio 2013 Fixing CA0053 : Unable to load rule assembly

3.  I also wrote about the inability to remove source control binding in VS 2013 in the above blog post.

4.  I keep getting errors when building that my application .exe is locked. I have written that up in this blog post: System Process is Locking .exe Files that Visual Studio Builds.  Microsoft has logged a bug for this.

Moving VS 2010 Solution to new VS 2013 Folder

All of my Visual Studio 2010 applications have always had zero designer load issues.  All resources loaded and were rendered in the designer as expected. Not the case in VS 2013, let’s see what we can do about this.

I copied my VS 2010 application to a VS 2013 folder structure.

I then opened the copied solution in VS 2010 and broke it from source control.  (gets around problem $3 above)

I also uncheck the settings that invoked FxCop in all the projects.  (gets around #2 above)

I also ran the tool I created in step #2 above to clean all my .csproj files, removing the toxic legacy FxCop settings from them.

I followed the steps in #4 above to limit file locked build errors.

Built solution, all is well.

Close VS 2010.

Open solution in VS 2013.

Visit each project and target .NET 4.51.

Visit each reference in each project to ensure that the references were pointing to .NET 4.5 or 4.51 assemblies.  Many references had to be manually removed and re-added.  Some moved by themselves.

For Prism and Unity, I built my own private build of Prism 4.0 that targeted Unity 3.0 and the new Common Service Locator included in Unity 3.0. My Prism version is now Prism 4.51 that targets .NET 4.51.

Built my solution, no errors, time to open a XAML file in one of my Prism Modules.

When I open any XAML file located in a Prism Module, none of the App.xaml resources were available. (It took me almost two weeks of building spikes, debugging, troubleshooting, etc. to find the answer.)

Background: Many Prism developers do not have their Shell (main .exe) reference many assemblies, including any Prism Modules (UserControl libraries with views and viewmodels). The Prism application is composed at run-time and the modules are loaded into the application domain as part of bootstrapping the application. This type of application development is fully supported in VS 2010 at both run-time and design-time.

Getting the Visual Studio 2013 XAML Designer to Load

The above Prism development model is not supported by the VS 2013 XAML Designer.  I think it has to do with the new way the dependent resources are shadow copied and made available to the designer. Yes, the team is now aware of this scenario.

For now, what I had to do was to set a reference to all my modules from my Shell (main .exe) and set Copy Local = true.

After doing this for all your modules you must close VS 2013 and reopen your solution because that critical change is not always picked up by the XDesProx.exe side process that the XAML Designer runs in.  However, after reopening your solution, you can open any module and your App.xaml resources are available and show up in the designer.

Problem worked around.  In a future update to Visual Studio 2013, I hope that I’ll be able to remove hard references to my modules and the App.xaml resources will be made available in the designer.

Copy Local = false is Your Friend

The below image pictures the references my Contacts module requires.  The Boyd assemblies are either local to solution or are file reference to our framework.  The others you recognize.

Notice that every assembly has Copy Local = false.  Check out the \bin\Debug folder for Contacts after a build.  Only two files.

This is HUGE savings in time on builds.  Now VS does not have to copy all those files to every \bin\Debug folder for every project in the solution.

NOTE: In order to pull this off, your main .exe must reference the Boyd…, Microsoft… and System.Windows.Interactivity and set Copy Local = true so that these assemblies will be resolvable at run-time and design-time.

CopyLocalFalse

Close

Hopes this helps someone and have a great day,

Just a grain of sand on the worlds beaches.


System Process is Locking .exe Files that Visual Studio Builds

October 23, 2013

This has been happening for a while not and I decided to get to the bottom of this very annoying problem.

Problem

I build a solution in Visual Studio, then I rebuild that same solution and get the very familiar error message:

Error 1 Unable to copy file “obj\x86\Debug\MainApplication.exe” to “..\bin\MainApplication.exe”. Access to the path ‘..\bin\MainApplication.exe’ is denied. MainApplication

Root Cause

After many, many of these dumb messages I wanted to see what process would be so aggressive as to want to lock my newly compiled file.

So I fired up Process Explorer (procexp.exe).

First thing you must do is Show Details for All Processes. This action is on the File menu.

The use the Find menu, select Find Handle or DLL…. 

In the Process Explorer Search, enter the full name (no path) of the .exe reported in your above Visual Studio build error message. 

Why Is This Happening

So my questions is, why is the System process PID:4, locking my .exe file?

Currently I have to wait several minutes until the file is no longer locked.  I have noticed that if I have an instance of Windows Explorer open in the build output folder that files get locked more often.

Hint:  Don’t kill System PID:4, your computer will lock up. 

SystemLockingBuiltFiles

Solution

I started thinking about what could be doing this:  Virus, Search Indexer?  Bingo!

I searched for how to throttle the search indexer.  Turns out someone already figure this out.

http://www.sevenforums.com/tutorials/194374-indexer-backoff-enable-disable-windows-7-a.html

One last step may be required.  After performing the above steps, you may need to reboot your computer. 

(Windows team, please provide a setting on the Indexer UI to set throttling, needing a registry entry is not a good solution to this problem.)

So far, this has solved my problem by enabling Indexer Backoff as explained in the above tutorial.

Close

Hopes this helps someone and have a great day,

Just a grain of sand on the worlds beaches.


Follow

Get every new post delivered to your Inbox.

Join 255 other followers