Category Archives: Technology

Solving cross-assembly WPF Resource problems once and for all

I wrote several posts about WPF weakness when it comes to sharing resources. Our use case, at my at work, where we load multiple versions of an assembly into a single app domain this problem has been felt most acutely. As I wrote previously, using the most documented way of loading resource dictionaries, unless you specify a version of an assembly when loading a resource dictionary you are running the risk of loading a wrong resource dictionary because you may have multiple versions of same library loaded into an app domain. And such problems are notoriously difficult to catch and understand.

At least now, it’s easy to solve. I am glad to announce that I found a definitive way to share resources across assembly boundaries without running into versioning issues. The key to doing this is to never load resource dictionary from another assembly using cross-assembly Uris. I did not know that there was another way until recently. All the examples of loading resource dictionaries, that I can recall, use the Source=”{PackUri}” method of loading, but there’s a way to reference resource dictionary using code.

A ResourceDictionary, just like any other class that can be defined in Xaml, can also contain the “code behind” portion, a source code file associated with the main Xaml file. If you already have resources defined in a resource dictionary somewhere in your assembly, you don’t have to change it. Instead you’ll create a brand new resource dictionary which you would use to export the resource for sharing. For example, let’s say you have a resource dictionary defining the colors of the stoplight. It lives in an assembly called ResourceSharing, in a namespace ResourceSharing.Resources in a file called Resources.xaml.

<ResourceDictionary xmlns=""
    <SolidColorBrush x:Key="Go" Color="Green"/>
    <SolidColorBrush x:Key="Stop" Color="Red"/>
    <SolidColorBrush x:Key="PrepareToStop" Color="Yellow"/>

To export this ResourceDictionary, create a new Resource Dictionary for export. Let’s call it ResourceSharing.Resources.ExportResourceDictionary. I’ll consist of the xaml and the C# portions

<ResourceDictionary xmlns="" 
        <ResourceDictionary Source="Resources.xaml"/>

Notice the Class definition on line 2.

The code behind class looks like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ResourceSharing.Resources
    public partial class ExportResourceDictionary
        //Expose it as singleton to avoid multiple instances of this dictionary
        private static readonly ExportResourceDictionary _instance = new ExportResourceDictionary();

        public static ExportResourceDictionary Instance
            get { return _instance; }

        public ExportResourceDictionary()

Let’s also create a namespace we can use to make it easier to reference these resources from another assembly using namespaces

using System.Windows.Markup;

[assembly:XmlnsDefinitionAttribute("", "ResourceSharing.Resources")]

How to Share

Here’s how to consume the resources exported from the ResourceSharingAssembly. For this example, I had an executable assembly called ResourceSharingClient, where I am referencing exported resource right in the Main Window. Notice the use of the exported namespaces in line 2 and the way that I am referencing a static instance of the ExportResourceDictionary. Such references are version-proof because .NET knows the version of the dependent assemblies. There’s no need to dynamically discover the dependent assembly and the code actually looks a lot neater too. I know that such approach requires a bit more work, but the final result is a lot safer. I only wished that such approach had been advertised by Microsoft WPF evangelists from the beginning.

        Title="MainWindow" d:DesignWidth="111.5" d:DesignHeight="109.5" Width="120" Height="130">
                <x:Static Member="rs:ExportResourceDictionary.Instance"/>
    <Border BorderBrush="Black" BorderThickness="2" HorizontalAlignment="Center" VerticalAlignment="Center" Padding="2" CornerRadius="2" Background="Silver">
        <StackPanel Orientation="Vertical">
            <Ellipse Width="20" Height="20" Fill="{DynamicResource Stop}" Stroke="Black" StrokeThickness="1"/>
            <Ellipse Width="20" Height="20" Fill="{DynamicResource PrepareToStop}" Stroke="Black" StrokeThickness="1"/>
            <Ellipse Width="20" Height="20" Fill="{DynamicResource Go}"  Stroke="Black" StrokeThickness="1"/>

Launching ClickOnce Application with parameters from a shortcut

ClickOnce is a handy technology from Microsoft that makes it easy to deploy desktop Windows applications using the web browser. IE is naturally supported out of the box, Firefox and Chrome have add-ons and apps respectively to make ClickOnce work.

When installed, ClickOnce created shortcuts for the application under user’s Start Menu (Windows 7 and 10) in the folder whose name matches the name of the company specified in the manifest of the application. But the shortcuts to ClickOnce applications are not your typical *.lnk files, they are .appref-ms files. An appref-ms file is a text file saved in UTF-16 or “UCS2 Little Endian” format. Format is important getting it wrong will make the file unrecognizable to the system.

Here’s a typical text from the appref-ms file., Culture=neutral, PublicKeyToken=f89fd69c4bd8bc85, processorArchitecture=x86

It consists of 4 parts separated by comas:

  1. Url#Name – I noticed that the URL is not important, but the bame is – it has to match the name of the application in the manifest
  2. Culture – in the format “Culture=”
  3. PublicKeyToken – in the format “PublicKeyToken=”
  4. Target CPU – in the format “processorArchitecture=”
  5. To pass parameters to the clickonce application you must invoke the file either from the command line with parameters. I was hoping to create a real shortcut (lnk) file with the file as a target along with arguments, but Windows does not make it easy. It’s a lot easier to manage shortcuts to normal executable files, so that’s the approach I would recommend in this solution.

    You can add a second windows executable file to your solution. It’s job would be to generate a temporary file on the fly and launch it with parameters using .NET’s Process.Start command. When your real app starts, make sure to copy this helper executable to user’s %appdata%\YourAppName location or ClickOnce’s ApplicationDeployment.CurrentDeployment.DataDirectory (will only be available once properly deployed). Then you can create a shortcut to the executable anywhere you like and even add command line arguments to it. Your executable then will generate the file on the fly somewhere in temp directory, and launch it along with the arguments you specified. You can get the parts necessary to generate this file from the ApplocationIdentity object:

    Hope this works for you.

    PS. Don’t forget to delete the dummy file you generate after your app launches.

Microsoft mechanism to load WPF resources is broken. (looking for a better title)

I’ve been using WPF along with .NET and have been a staunch supported of the technology for years now. The pattern of separating presentation from logic gained a lot of traction. Technologies such as iOS’s cocoa touch, JavaFX and others follow same model. Even HTML5 forced all the pure presentation/layout markup out from HTML and into CSS. So the idea is sound. But what about execution.

WPF implements this pattern using XAML. XAML markup is used to design the visual this xaml is stored in the xaml file, whose name usually matches the name of the class. For example, MyWindow.xaml. During compilation, an auto-generated file marries the code that defines the visual (MyWindow.xaml.cs) and the xaml file itself (MyWindow.xaml.cs). The autogenerate file would be named MyWindow.g.i.cs and it would contain the implementation of the InitializeComponent() method that’s referenced in the main MyWindow.xaml.cs class. The contents of the method looks something like this:

[System.CodeDom.Compiler.GeneratedCodeAttribute(&quot;PresentationBuildTasks&quot;, &quot;;)]
public void InitializeComponent() {
	if (_contentLoaded) {
	_contentLoaded = true;
	System.Uri resourceLocater = new System.Uri(&quot;/MyLibrary;component/mainwindow.xaml&quot;, System.UriKind.Relative);
	#line 1 &quot;..\..\MainWindow.xaml&quot;
	System.Windows.Application.LoadComponent(this, resourceLocater);
	#line default
	#line hidden

So far so good right. OK, let’s talk about some of the advanced uses of .Net. Specifically support for having multiple versions of same assembly (dll) to be loaded in a single AppDomain. Such use case comes handy in a framework use case. A framework supports multiple plug-in modules, each can be developed by other developers who may rely on different versions of common libraries. I am not talking about things like log4net, I am talking about shared assemblies that define common logic and can be reused by each module. If 2 modules are loaded into a single app-domain and both depend on their ‘private’ version of the common assembly, a good framework should not force both modules to share latest version of the library, because

  • ‘latest’ does not mean backwards-compatible
  • ‘latest’ may have bugs that ‘earlier’ version did not
  • …I can go on for a while on this one. It’s 2014, dll hell is well known to software developers of the 20th century.

Now, let’s say that 2 different versions of the shared library called MyLibrary are loaded and one version is used by Module1 and another version is used by Module2. During compilation, assembly name along with the version are recorded in modules’ manifests so that when .NET encounters request to execute code defined in MyLibrary the source module will tell .Net which version of MyLibrary contains the code it wants executed. This is a basic building block of .NET and a very attractive feature.

Now, what about WPF? Well that’s not that clear is it? Look at Line #8 above: System.Uri resourceLocater = new System.Uri(“/MyLibrary;component/mainwindow.xaml”, System.UriKind.Relative). It defines what it calls a resourcelocator which the system will use to find the xaml resouce in an assembly called MyLibrary. I don’t know how WPF resolves the assembly, but if I were to write the logic for resolution, I would not have enough information to find a proper assembly MyLibrary, because I don’t know which version to load. I would have to guess. And as we know in any science guessing is bad. Computer Science is an exact… well… science. Guessing, hoping, holding fingers crossed or other techniques that do not produce determinate result will break at the worst possible moment! I can see how developers armed with inaccurate knowledge or with little experience make mistakes like this, but when Microsoft’s tools generated code that’s faulty, and make it impossible to intercept and fix, there is no other way to call it – they fucked up! How can they expect developers to trust their tooling if they, themselves, auto-generate code that sometimes breaks.

This breaks in a most bizarre way, too. MyLibrary version 2 was loading the MainWindow class, which then was running the InitializeComponent() method above, encountered the LoadComponent call, which asked to load the resource from the MyLibrary assembly without a version, and the code picked the wrong version of the MyLibrary assembly, which did not have the MyWindow class, nor the resource. What a way to blow up!

Such nonsense was reported to them too! This connect ticket marked as “Wont’t Fix” describes the problem: StackOverflow also has references to this problem: Luckily one of the suggestions led me to the best solution.

The Fix

We were lucky to have our builds automated via scripts which rely on MSBuild to build the solutions. All I needed to do is to modify the script and pass the /p:AssemblyInfo=$version parameter to MSBuild. ( This would tell the build system to add assembly version to the Resource reference in line 8. It now looks like the code below. Problem solved, but could have been avoided on the first place!

Shame on you, Microsoft!

[System.CodeDom.Compiler.GeneratedCodeAttribute(&quot;PresentationBuildTasks&quot;, &quot;;)]
public void InitializeComponent() {
	if (_contentLoaded) {
	_contentLoaded = true;
	System.Uri resourceLocater = new System.Uri(&quot;/MyLibrary;V1.0.23;component/mainwindow.xaml&quot;, System.UriKind.Relative);
	#line 1 &quot;..\..\MainWindow.xaml&quot;
	System.Windows.Application.LoadComponent(this, resourceLocater);
	#line default
	#line hidden

How to use .NET WebClient synchronously and still receive progress updates

Recently, I had to implement our custom package deployment mechanism for our UI framework where packages are hosted on a web-accessible URI. During the download process, the UI should display a progress bar which updates the user on the progress the download. After download is complete, the client performs a few more steps including

  • checking file integrity against its md5 hash
  • expanding the compressed file into the destination
  • cleaning up

The implementation uses TPL; for each package that user chose to upgrade, a task is created which performs the steps above. During this process, the UI displays a progress of each task.

The download portion of the process is implemented using WebClient.DownloadFile method. It’s short and sweet, hiding most of the complexity of opening a connection, getting a response stream and reading it one chunk at a time. But its simplicity comes a shortcoming: during download the thread doing the downloading is blocked an no progress is reported, so downloading a large file would cause the user to think that the system froze, because even though the wait spinner is spinning, the progress bar is stuck. What I want is to get updates on the progress of my download while waiting for download to complete.

The WebClient class has convenient DownloadProgressChanged event which seems like a perfect candidate to help me here, so I attached a delegate to it, but it was never called. Upon careful reading of the documentation, I learned that I must use the asynchronous version of the DownloadFile mehtod, DownloadFileAsync to receive any progress updates.

While I could switch my code around to accommodate new asynchronous calling pattern, I did not want to drastically redesign my existing code. It was already relying on the TPL for asynchrony, adding another asynchronous mechanism would add more complexity to my code. So I decided to try to keep the method that deals with WebClient synchronous, but still receive updates. To do this, I would need to call the DownloadFileAsync method, but then block my thread until download completes or fails. Luckily, WebClient has the DownloadFileCompleted event which would come in handy here. Since I would block my thread after calling the DownloadFileAsync method, when the DownloadFileCompleted fires, I would unblock my calling thread. Here’s the code that implements this solution

public void DownloadFile(Uri uri, string desintaion)
  using(var wc = new WebClient())
    wc.DownloadProgressChanged += HandleDownloadProgress;
    wc.DownloadFileCompleted += HandleDownloadComplete;

    var syncObject = new Object();
       wc.DownloadFileAsync(sourceUri, destination, syncObject);
       //This would block the thread until download completes

  //Do more stuff after download was complete

public void HandleDownloadComplete(object sender, AsyncCompletedEventArgs e)
      //releases blocked thread

public void HandleDownloadProgress(object sender, DownloadProgressChangedEventArgs args)
  //Process progress updates here

At the end, I still use WebClient synchronously without losing the benefits that come with its asynchronous usage.

Happy Downloading!

Powershell -match operator

I think Powershell’s -match operator deserves its own blog post because it does so much. I’ve been automating our build process using Powershell and I gained a lot of respect for this operator. The examples below, would usually refer to the SVN url parsing.


Firstly, it returns true ($true in Powershell) if the original string matches the regex expression you passed into it. For example,

$string = &amp;quot;Hello&amp;quot;
$string -match &amp;quot;Hello&amp;quot; #return true

$string -cmatch &amp;quot;hello&amp;quot; #return false, cmatch performs case-sensitive match

$string -cmatch &amp;quot;[H|h]ello&amp;quot; #return true  

Group Matching

In addition to regular matching the -match operator will populate a special $matches variable. For example

$string = &amp;quot;Hello World&amp;quot;
$string -match &amp;quot;Hello&amp;quot;

$matches[0] #prints &amp;quot;Hello&amp;quot;

$string = &amp;quot;Hello World&amp;quot;
$string -match &amp;quot;(?'first'Hello)&amp;quot;

Name    Value                                                                                                 
----    -----                                                                                                 
first   Hello                                                                                                 
0       Hello 

Group Matching and Replacing

If you are crafty enough, you can come up with a match and replace strategy for the strings you are working with. For example, if you have to figure out the full path of the svn path if you know the name of the tag, given the current branch path, you’ll do the following:

$url = &amp;quot;;quot;
$search = &amp;quot;(.*)(?'branch'branches/[^/]*)(.*)&amp;quot; #Generates 3 groups (1,2, and branch)

$url -match $search


Name     Value                                                                                                 
----     -----                                                                                                 
branch   branches/VERSION-1.0                                                                                  
2        /path/to/code                                                                                         

#use the replace method of the Match object to replace branche path with tag path:
$newUrl = $matches[0].Replace($matches['branch'], 'tags/TAG-123') #replaces branch path with new tag path


How to customize column headings in DevExpress WPF GridControl

DevExpress is one of several 3rd party .NET control providers offering a full suite of controls for WPF.  Their library of widgets is widely used in many financial firms to speed up time to market and make UI development easier.  They look good and work relatively well.  But I don’t want to advertize them too much here. If you are working with their GridControl, you probably noticed how notoriously difficult it is to certain things you thought should be a lot easier.

I recently was asked to color the background of the Grid Headers and decided I would share my pain and the solution here. Unfortunately, this exercise is not for the faint-hearted, as it requires switching your WPF project to use a custom theme that you will create using their tool.

I will show how you can modify their grid’s column heading template to inject your own Attached Properties which you can then set in your Xaml. But first, you will need to switch to a custom theme which you will create using the DevEpxress Theme Editor, which you can download here: You can read instructions on using the tool here: If you use their skins already then pick those that you use as a base when saving your own custom theme. Once you have your own custom theme project, and are successfully using it in your project, you are ready to proceed with the advanced part of this exercise.

Here’s an overview of what you will need to do.

  • Step 1. Create another dll project where you would define your own custom attached properties. YOu will need to compile the project and generate a DLL which you will later reference
  • Step 2. Open the theme projects that the DevExpress tool generated in Visual Studio and add references to the dll you created in step 1.
  • Step 3. Modify their Grid Header XAML templates to reference your new Attached Properties.
  • Step 4. Reference dll you had created in step 1 in your projects and set the Attached Properties you created in the GridColumn definitions.

DevExpress wants you to use 3 different brushes to color Grid Column Headers:

1. Normal Background Brush: used for normal state rendering
2. Hover Over Brush: used when mouse is over the column heading
3. Mouse Click Brush: used when mouse is clicked while over the column heading

To encapsulate all 3 states, we are going to create a custom Type called GridColHeaderBrushes in our custom dll project (step 1). I’ll be a DependencyObject defining 3 Attached properties.
Here’s the code.

    public class GridColHeaderBrushes : DependencyObject
        public static readonly DependencyProperty BackgroundProperty =
            new UIPropertyMetadata(null));

        public static readonly DependencyProperty MouseOverProperty =
            new UIPropertyMetadata(null));

        public static readonly DependencyProperty MousePressedProperty =
            new UIPropertyMetadata(null));

        public Brush Background
            get { return (Brush)GetValue(BackgroundProperty); }
            set { SetValue(BackgroundProperty, value); }

        public Brush MouseOver
            get { return (Brush)GetValue(MouseOverProperty); }
            set { SetValue(MouseOverProperty, value); }

        public Brush MousePressed
            get { return (Brush)GetValue(MousePressedProperty); }
            set { SetValue(MousePressedProperty, value); }

In addition we would need to create another class which would contain attached properties we would use on the grid. The two files must be in the same namespace to simplify things. Notice that I also added 2 more properties to control text alignment in column headers. This is a bonus 🙂

    public static class GridColumnHeaders
        public static readonly DependencyProperty HeaderBackgroundsProperty =

        public static readonly DependencyProperty HorizontalHeaderAlignmentProperty =

        public static readonly DependencyProperty VerticalHeaderAlignmentProperty =

        public static HorizontalAlignment GetHorizontalHeaderAlignment(DependencyObject obj)
            return (HorizontalAlignment)obj.GetValue(HorizontalHeaderAlignmentProperty);

        public static void SetHorizontalHeaderAlignment(DependencyObject obj, HorizontalAlignment value)
            obj.SetValue(HorizontalHeaderAlignmentProperty, value);

        public static VerticalAlignment GetVerticalHeaderAlignment(DependencyObject obj)
            return (VerticalAlignment)obj.GetValue(VerticalHeaderAlignmentProperty);

        public static void SetVerticalHeaderAlignment(DependencyObject obj, VerticalAlignment value)
            obj.SetValue(VerticalHeaderAlignmentProperty, value);

        public static GridColHeaderBrushes GetHeaderBackgrounds(DependencyObject obj)
            return (GridColHeaderBrushes)obj.GetValue(HeaderBackgroundsProperty);

        public static void SetHeaderBackgrounds(DependencyObject obj, GridColHeaderBrushes value)
            obj.SetValue(HeaderBackgroundsProperty, value);

After you compile the dll, place it somewhere near the custom theme projects that DevExpress tool created for you, then open the custom theme project in Visual Studio. Open the regular project first – the one without the “ThemeEditor” in its name.

You will need to modify the ColumnHeader.xaml file located under the folder that matches your custom theme name, not under the “Generic” folder. You will need to do the following:

  1. Add a namespace reference to the namespace containing the classes above:
    <ResourceDictionary ... 
  2. Find the Border classes which are used as backgrounds for grid headers. They are named
    • BackgroundBorder
    • MouseOverElement
    • MousePressedElement

    and modify their “Background” Property so they look like this below. Make sure that you replace the with the hard-coded color that was in the code before you changed it.

    <Border x:Name="BackgroundBorder" Background="{Binding Path=(dxg:BaseGridColumnHeader.GridColumn).(customui:GridColumnHeaders.HeaderBackgrounds).Background, RelativeSource={RelativeSource TemplatedParent}, FallbackValue=<what was here before>}" cs:Name="Border_0004" />
    <Border x:Name="MouseOverElement" Background="{Binding Path=(dxg:BaseGridColumnHeader.GridColumn).(customui:GridColumnHeaders.HeaderBackgrounds).MouseOver, RelativeSource={RelativeSource TemplatedParent}, FallbackValue=<what was here before>}" Opacity="0" cs:Name="Border_0005" />
    <Border x:Name="MousePressedElement" Background="{Binding Path=(dxg:BaseGridColumnHeader.GridColumn).(customui:GridColumnHeaders.HeaderBackgrounds).MousePressed, RelativeSource={RelativeSource TemplatedParent}, FallbackValue=<what was here before>}" Opacity="0" cs:Name="Border_0006" /> 	
  3. As a bonus, add the HorizontalAlignment and VerticalAlignment properties to the Grid called “PART_Content” so it looks like this:
    <Grid x:Name="PART_Content"
      HorizontalAlignment="{Binding Path=(dxg:BaseGridColumnHeader.GridColumn).(customui:GridColumnHeaders.HorizontalHeaderAlignment), Mode=OneWay, RelativeSource={RelativeSource TemplatedParent}, FallbackValue=Left}"
      VerticalAlignment="{Binding Path=(dxg:BaseGridColumnHeader.GridColumn).(customui:GridColumnHeaders.VerticalHeaderAlignment), Mode=OneWay, RelativeSource={RelativeSource TemplatedParent}, FallbackValue=Center}" >
  4. Compile and Save the project
  5. Replace the original dll that the DevExpress Theme Editor had created for your project with the new version you just compiled.

Customizing Grid Column Headers

You will need to reference the your custom dll containing the new Attached Properties in your project as well.  Once you do, you are ready to set the colors and alghment of your grid column headings. Don’t forget to add a customui namespace declaration at the top of your xaml file.

Here’s an example:

<dxg:GridControl ...>
           <customui:DrigColHeaderBrushes Background="White" MouseOver="Green" MousePressed="Orange"/>

To control alignment you can do this:

<dxg:GridControl ...>
   <dxg.GridColumn customui:GridColumnHeaders.HorizontalHeaderAlignment="Right".../>

How to lazy-load almost anything in AngularJS

I was asked to build a module web framework which would allow various teams to plug-in their parts as they become available with none or minimal affects on other existing parts. Each new part could be represented by a tab or a menu section. While each part relies on some common/shared services, frameworks or components, each also has unique dependencies. For example, all parts can rely on jquery, but the first part relies on Highcharts library for charting, while another part uses SlickGrid to represent data. Firstly, I had to pick libraries and frameworks to crate a foundation for the site. Foundation components would be either be used directly or relied upon by all the parts in the system. After careful evaluation, I picked the following

  • jQuery
  • AngularJS
  • RequireJS
  • BootstrapUI with Angular extensions

To wire up Angular and Require, I used the seed example found here: Thanks to the configuration file used by RequireJS, my main index.html file only has a single script dependency:

<script data-main="app/js/main" src="app/lib/requirejs/require.js"></script>

The app/js/main.js file defines all the script dependencies required by the website. This file would need to be modified as dependencies get added by the parts of the system. For example, if a new part coming online requires another library, that library would have to be registered in this file along with its dependencies.

	paths: {
		jquery: '../lib/{path to jquery}',
		angular: '../lib/{path to angular}',
		angularRoute: '../lib/{path to angular ui router}',
		angularBootstrap: '../lib/{path to bootstrap ui}',
		highcharts: '../lib/{path to highcharts}',
		'highcharts-export': '../lib/{path to highcharts export}',
		'highcharts-drilldown': '../lib/{path to highcharts drilldown}',
		'jquery-ui':'../lib/{path to jquery ui}',
		'jquery-drag-and-drop': '../lib/{path to jquery drag-n-drop}',
		'slickgrid-core': '../lib/{path to slickgrid core}',
		'slickgrid-cellselectionmodel': '../lib/{path to slickgrid cellselection model}',
		'slickgrid-rowmovemanager': '../lib/{path to slickgrid rowmovemanager}',
		'slickgrid-grid':'../lib/{path to slickgrid}'

//Dependencies defined below
	shim: {
		'angular' : {
			'exports' : 'angular',
			'deps': ['jquery']
		'angularRoute': ['angular'],
		'angularBootstrap': ['angular'],
		'highchart-theme': ['highcharts'],
		'highcharts-export': ['highcharts'],
		'highcharts-drilldown': ['highcharts'],
		'slickgrid-grid':['slickgrid-cellselectionmodel', 'slickgrid-rowmovemanager']
        //Not sure about the significance of this piece below
	priority: [

//After configuration, let's go running the app!


	'controllers'], function(angular, app) {
	'use strict';

	angular.element().ready(function() {

So we start by requiring Angular, App, App-Config and Controllers, which initializes angular and runs it. Most of the standard angular code has been moved into modules according to AMD specs ( used by RequireJS. The require() function call above first specifies that it needs to load angular module (defined above), app, app-config and controllers modules, which are not defined. If not explicitely defined, RequireJS will attempt to locate these modules in the same directory as this main.js file inside files whose names would same as names of the modules with ‘.js’ appended. So I must have these files:

  • app.js
  • app-config.js
  • controllers.js

Lets’ take a look at those: app.js

define ([
         ], function(angular) {

	'use strict';

	var myApp = angular.module('myApp', ['ui.bootstrap', 'ui.bootstrap.tpls', 'ui.router']);

	return myApp;

Notice that I am returning myApp from the app module. That allows me to reference it later. For example, if you look back to the main.js code, you’ll see that a parameter named app is being passed into function inside require() call (line 52). That app is the same as myApp being returned by the app module function (line 11). I need to have access to the app because I reference it from all other modules that depend on angular. The rest of the configuration is done inside the app-config module app-config.js

		, function(app) {

app.config(['$stateProvider', '$controllerProvider', '$urlRouterProvider', '$httpProvider', '$provide', '$compileProvider',
	                    function (stateProvider, cp, urlRouterProvider, httpProvider, provide, compProvider) {

		//These would be used later for lazy-loading controllers, directives and services
		app.$stateProvider = stateProvider;
		app.$controllerProvider = cp;
		app.$provide = provide;
		app.$compileProvider = compProvider;


The general function behind omitted code above is to declare states for your website. Each state would represent a part of the site that other developers would contribute. You can postpone defining all states until later by having a service retrieve your site configuration and register states based on configuration you specify in the service response. Look here for more info: . Controllers that you are declaring during normal bootstrapping of Angular site can simply be declared inside AMD modules such as this example below. Because controllers module is referenced as a dependency at startup, we can do this: controllers.js

define(['angular', 'app', './services/site-definition-service'], function(angular, app) {

	'use strict';

	app.controller('SomeController', ['$scope',
	                                 function (scope) {

Notice that the controller references something called site-definition-service. This is another javascript module which defines a service necessary to retrieve definition of the site. Such definition is a simple JSON structure which allows developers to configure states. As part of state configuration you can specify a resolve {} directive to resolve additional dependencies. Dependencies could be specified as an array of module names, which RequireJS would recognize when you configure them back in the main.js file. Here’s an example lf lazy-loading state registration:

        'services/lazy-loader'], function(app) {

//app.$stateProvider is used to lazy-register states
app.$stateProvider.state('stateName', {
			url: '/myPart',
			resolve: {
				'loadDependencies': function ($stateParams, LazyLoader) {
					return LazyLoader.loadDependencies('stateName');

and here’s what lazy loading service code would look like: lazy-loader.js

 define(['angular', 'app', 'require', './services/site-definition-service'], function (angular, app, requirejs) {

	'use strict';
	app.service('LazyLoader', ['$cacheFactory', '$http', '$rootScope', '$q', 'SiteDefinitionService',
                      function (cacheFactory, http, rootScope, q, siteDefService) {
             var self = this;

             this.loadDependencies = function(stateName) {            

               var deferred = q.defer();
               http.get('rest/sitedefinition/' + stateName).success(function (data, status, headers, config) {
                  var deps = data.dependencies; //array
                  if(deps &amp;&amp; deps instanceof Array) {
                     loadDependenciesFromArray(deps, deferred);
                  } else {

               return deferred.promise();

		this.loadDependenciesFromArray = function(depArr, deferred){
			requirejs(depArr, function() {


Examples of lazy-loading dependencies



define(['app'], function(app) {

	'use strict';
	//app.$compileProvider is used to lazy-register directives



define(['app'], function(app) {
	'use strict';

	//app.$provide is used to lazy-register services



define(['app'], function(app) {

	'use strict';
	//app.$controllerProvider is used to lazy-register controllers.  Part2Service was loaded as a dependency earlier
	app.$controllerProvider.register('Part2Controller', ['$scope', 'Part2Service',
               function (scope, svc) {

To lazy load CSS files you’ll need a custom directive. I’ll cover this in another post. This post has gotten big and convoluted. If something is unclear, please comment, I’ll adjust the content as necessary. Thank you.