Rich Newman

December 29, 2007

Introduction to using Financial Products Markup Language (FpML) with Microsoft .NET Tools (Part 1)

Introduction

This short series of articles will attempt to show how Microsoft’s standard .NET tools (Visual Studio and xsd.exe) can be used to investigate and use Financial products Markup Language (FpML).

This first article gives an overview of how we can use Visual Studio to examine the FpML XSDs, and use it to validate the XML examples that are provided in the FpML download.

Part 2 of the series will examine how the FpML XSDs fit together for basic trade types.

These articles assume you understand the basics of XML Schema Definition language. If you don’t there are a number of good tutorials available on the internet. For example there’s quite a good one at http://www.w3.org/TR/xmlschema-0/. These articles will reference the tutorial for the less obvious XSD structures.

FpML

Financial products Markup Language is intended as an industry-standard method of representing financial products using XML. Details can be found at www.fpml.org.

The XML representations of financial products are defined using XML Schema Definition (XSD). These can be downloaded from the site.

FpML is Complex

The FpML XSDs are intended to define XML for a very wide range of financial products. They are also intended to be easily extensible for any new products. To achieve this products are built up from small building blocks into a complex structure. This means the XML is very hierarchical (it has many layers of tags).

An alternative approach would be to represent financial products in as flat a structure as possible. By ‘flat’ we mean a simple series of name-value pairs (with associated types for the values), and no hierarchy. Even quite complex derivatives products can be represented by a flat schema (obviously such things as basket products are an exception to this). A flat structure is easier to understand, and can be easier to handle in code. It also leads to less verbose XML, and hence smaller message sizes.

However, this is not the approach FpML takes for good reasons: whilst it’s easier to deal with a flat structure, it’s hard to extend as you cannot easily re-use blocks of tags in a new structure.

As well as defining formats for a wide range of trade types, the FpML XSDs define message formats for standard trade events (e.g. confirmations, credit event notifications). They also define standard enumerations for such things as day count conventions.

As a result all this FpML is inevitably complex and difficult to understand. Furthermore there’s little free documentation available.

Visual Studio Support for XSDs

Visual Studio (combined with C#) has good support for XML and XSD. As you may know, we can load XSDs into it and it will automatically check that they are internally consistent. We can then load XML into it and validate that XML against the XSDs on the fly at design-time.

As we shall show the .NET languages also have support for validating XML using XSDs at run-time.

In addition there is an ‘XML Schema Definition Tool’ called xsd.exe that ships with Visual Studio. We can use this to automatically generate classes in a .NET language of our choice based on the XSDs. We can then load the XML data into those classes (at run-time obviously). If we don’t like the classes it’s very easy to manually tweak them to do what we want. In fact, as we shall see, xsd.exe is far from perfect and we may well need to tweak the classes to get them to work properly.

We can even usually use xsd.exe to generate DataSets from the XSDs and populate those from the XML. Of course, DataSets give us some disadvantages (e.g. speed) over plain old classes, but they allow us to track changes, and easily bind our data into grids for display and editing.

This series of articles will take us through all of the scenarios outlined above. However, as we shall see, the complexity of the FpML schemas (and some Microsoft bugs) can make handling FpML in Visual Studio challenging.

Initially we will work with Visual Studio 2005 (and .NET 2.0). Later on we’ll have a look at changes in Visual Studio 2008.

Getting Started with FpML and Visual Studio

The first thing to do if you want to learn about FpML is to download the schemas. This can be done from www.fpml.org, although you will need to register with the site. For this article I have used the FpML 4.2 Recommendation in Zip format, which you can download via the ‘Specifications’ tab.

Once you have downloaded and extracted this, create a console application project in Visual Studio. Add ALL of the XSDs found in the xml folder from your download to this project (using the Project/Add Existing Item… menu).

XSD

We are going to start with interest rate swaps. The details of these are defined in file fpml-ird-4-2.xsd. Right-click this file in Solution Explorer and select View Code. DON’T just ‘Open’ it as the default is to open with a DataSet Editor, which gives a graphical view. Note that you can change the default if you right-click/Open With. If you select the XML Editor as the default you will get the code view when you double-click in future.

You should now have the raw XSD in the document window. It’s a bit daunting, so right-click in the document window, and select Outlining/Toggle All Outlining. This collapses the XSD entirely. If you now expand it once (by clicking the ‘+’ sign) you will see that the XSD includes some other schemas, then defines some complex types, then some elements and some groups. One of the elements is called ‘swap’, which is encouraging. This is of type ‘Swap’ which we can see defined as a complex type. However it’s not clear how we get from this to XML for an interest rate swap.

Note here that Visual Studio validated the schema when you displayed it. You can see this if you deliberately break the schema. Try changing the type of the swap element mentioned above to ‘notSwap’. If you now look at the Warnings in the Error List (menu View/Error List) you’ll see Visual Studio is telling you that ‘Type ‘http://www.fpml.org/2005/FpML-4-2:notSwap’ is not declared.’ It’s also telling you the line number and the file, and you can as usual double-click the error to go to it.

notswap.jpg

Note also that Visual Studio only validates the schema when the schema file is open in the document window (try saving it and closing it with the error still in there: the warning disappears). Visual Studio will quite happily validate all of the FpML XSDs if you open them individually however.

XML

Now we will add an XML file representing an interest rate swap to our project, and get the XSDs to validate it. Our original download contains XML examples in the subfolders of the xml folder referred to above. In particular, there is a folder called interest-rate-derivatives that contains a file called ird_ex01_vanilla_swap.xml. This XML file references the XSD files we have already examined using the schemaLocation attribute. However the schemaLocation attribute says that the schemas are in a folder at a level above the XML file.

So create a folder in your solution (right-click the solution in Solution Explorer and select Add…/New Folder). Then right-click the folder, choose Add/Existing Item…, and add the ird_ex01_vanilla_swap.xml file into this folder.

Now if you open the file in Visual Studio it should validate correctly straight away: there should be no errors or warnings in the Error List. Again you can see this is working if you manually edit the XML: try changing the partyReference element near the top to ‘notpartyReference’. You will get a warning the notpartyReference is an invalid child element and ‘partyReference’ is expected.

notpartyreference.jpg

Visual Studio and XML: Navigation and Outlining

We have already seen that we can use Visual Studio’s outlining (collapsible regions) in the usual way with XSD files, and the same is true of XML files.

We can also use Visual Studio’s standard ‘Go To Definition’ functionality with both XSD and XML files. Put your cursor inside partyReference in the XML and hit F12 (or right-click, Go To Definition). Visual Studio will show the place in the XSD where partyReference is defined (which is inside file fpml-doc-4-2.xsd).

This shows that partyReference is an element in complex type TradeIdentifier. It is itself of type ‘PartyReference’. If you right-click ‘PartyReference’ and Go To Definition in the same way you can navigate within the XSD: you can see that PartyReference is an extension of base type ‘Reference’, and if you go to the definition of that you can see that it is an abstract complex type with one attribute called ‘href’ of type IDREF.

You can then navigate back through the items you’ve visited as usual in Visual Studio using the Navigate Backward toolbar button, or hitting Control + – (minus key).

It’s worth noting that the normal toolbar Comment/Uncomment buttons work fine with XML and XSD, including commenting sensibly across several lines: you don’t have to type ‘<!–‘ and ‘–>’. Also there’s good intellisense support if you are entering XML or XSD code, including code snippets on the context menu.

Finally if you load all of your XSDs into a project as described above you can (obviously) use Visual Studio’s normal Find in Files functionality (Ctrl-Shift-F) to locate items anywhere in the XSDs.

Validation in Code

We have seen how we can use Visual Studio to validate that a schema is correctly formed, and to validate an XML instance document against a schema. We can also do this validation in C# code.

Validation of a Schema in Code

To validate a schema we can load it into an XmlSchemaSet and compile it as below. Put this code in the Main method of the C# console application created above to see this working:

            XmlSchemaSet xmlSchemaSet = new XmlSchemaSet();
            xmlSchemaSet.Add("http://www.fpml.org/2005/FpML-4-2", @"..\..\fpml-main-4-2.xsd");
            xmlSchemaSet.Compile();

If the schemas are not properly formed you will get an error when you attempt to compile them.

Validation of XML Against a Schema in Code

To validate an XML instance document against the schema we use an XmlReader in association with a ValidationEventHandler as below. The code below goes in Main:

            XmlReaderSettings xmlReaderSettings = new XmlReaderSettings();
            xmlReaderSettings.Schemas.Add(xmlSchemaSet);
            xmlReaderSettings.ValidationType = ValidationType.Schema;
            xmlReaderSettings.ValidationEventHandler += new ValidationEventHandler(xmlReaderSettings_ValidationEventHandler);
 
            XmlReader xmlReader = XmlReader.Create(@"..\..\XML\ird_ex01_vanilla_swap.xml", xmlReaderSettings);
            while (xmlReader.Read()) { };
 
            Console.WriteLine("Validation complete");
 
            Console.ReadLine();

Additionally we need a ValidationEventHandler method: this will be called if there are any errors:

        static void xmlReaderSettings_ValidationEventHandler(object sender, ValidationEventArgs e)
        {
            if (e.Severity == XmlSeverityType.Warning)
            {
                Console.Write("WARNING: ");
                Console.WriteLine(e.Message);
            }
            else if (e.Severity == XmlSeverityType.Error)
            {
                Console.Write("ERROR: ");
                Console.WriteLine(e.Message);
            }
        }

The code for this example is available. To test these try deliberately breaking both the schemas and the XML and ensure you get appropriate error messages. Note that this code is based on Microsoft’s own help examples at http://msdn2.microsoft.com/en-us/library/3740e0b5(VS.80).aspx.

Note on Visual Studio 2008

The above discussion used Visual Studio 2005. Visual Studio 2008 behaves in the same way except:

  1. Visual Studio 2008 defaults to the XML Editor as the editor for XSD files, which is more sensible than the default DataSet Editor in Visual Studio 2005.
  2. Visual Studio 2008 automatically references xmlsig.xsd in Microsoft’s own schemas folder (normally c:\Program Files\Microsoft Visual Studio 9.0\xml\Schemas). xmlsig.xsd is the standard XML Signature namespace. However, the FpML files are referencing their own version of this schema, which is called xmldsig-core-schema.xsd. As a result if you open fpml-main-4-2.xsd in the designer, for instance, you get warnings about types in this schema being defined twice.To fix this bring up the Properties window for the fpml-main-4-2.xsd file, and click in the Schemas property. Click the button that appears. The screen that comes up lets you select the schemas that are automatically used for the file. Find xmlsig.xsd and in the ‘Use’ column set it to ‘Do not use this schema’ (which gives it a red cross as below). This will get rid of the warnings.

dontuseschema.jpg

Conclusion

This article has looked at some of Visual Studio’s functionality for handling XSDs and the associated FpML. Part 2 of this series will examine how the FpML fits together for a basic trade XML document.

Licensing of FpML Specifications

The FpML Specifications of this document are subject to the FpML Public License (the “License”); you may not use the FpML Specifications except in compliance with the License. You may obtain a copy of the License at http://www.FpML.org.
The FpML Specifications distributed under the License are distributed on an “AS IS” basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License.
The Licensor of the FpML Specifications is the International Swaps and Derivatives Association, Inc. All Rights Reserved.

http://www.fpml.org/documents/license.html

December 16, 2007

Foundational Modules and Names as Constants (Intro to CAB/SCSF Part 21)

Introduction

Part 19 and part 20 of this series of articles looked at business modules in the Smart Client Software Factory.

This article looks at foundational modules briefly, and also discusses the pattern for handling names in the SCSF.

Foundational Modules

In part 18 of this series of articles we saw how we can use one of the Guidance Automation Packages to add a business module to our solution. There’s also a Guidance Automation package that lets us add a ‘foundational module’ to our solution. This is on the same submenu as the ‘Add Business Module (C#)’ option we saw above. So to add a foundational module to our solution right-click the solution folder in Solution Explorer, select Smart Client Factory/Add Foundational Module (C#) and then click through the two setup screens.

A foundational module is identical to a business module except that it does not have a root WorkItem. This is because it is intended to contain supporting functionality rather than core business functionality for our solution. It is not expected that we will create business objects and add them to the various WorkItem collections.

So we are expected to create fairly generic services and supporting code in foundational modules, rather than business code. Of course we could do this in the Infrastructure projects mentioned in part 18, but a foundational module allows us to separate out supporting code into its own CAB module.

Note that we can create an interface component, ‘Module.Interface’, for our foundational module in exactly the same way as for a business module. This allows other components in the solution to use the module’s functionality without referencing it directly, as described above.

Constants Folders

In our examples above we have seen several Constants folders being set up. The main Smart Client solution has a Constants folder in both the Infrastructure.Interface component and the Shell component. Both the foundational modules and the business modules have Constants folders in both their main Module components and their Module.Interface components.

The Constants folders all contain four classes: CommandNames, EventTopicNames, UIExtensionSiteNames, and WorkspaceNames. In the Constants folders mentioned above most of these are empty by default, although Infrastructure.Interface has some constants set up in its classes.

The important thing to notice here is that the individual classes with the same name are arranged in an inheritance hierarchy. So if we have a business module in our Smart Client solution (as in the code example we have already seen) then CommandNames in the Module itself inherits from CommandNames in Module.Interface, which in turn inherits from CommandNames in Infrastructure.Interface. CommandNames in Shell also inherits from Infrastructure.Interface.

The reason these classes exist is to allow us to use standard constants throughout our solution for names, rather than having to use strings. The inheritance hierarchy lets us define these constants at the correct level in the hierarchy, but then to use any of them very simply by just accessing the class at the level the code is at.

The reason we don’t want to use strings in our code as names is they are prone to error in entry (since we can’t use intellisense) and can’t be checked by the compiler at compile-time: if we enter a string name wrongly we will get a run-time error. If we use constants to represent these strings we avoid both of these problems.

This will be clearer in an example:

We might call a Workspace on our Shell form “LeftWorkspace” when we add it to the Workspaces collection of the root WorkItem. Elsewhere in the code we may want to retrieve that workspace and interact with it, for example to call the Workspace’s Show method to display a SmartPart. Normally to do this the syntax would be, for example:

_rootWorkItem.Workspaces["LeftWorkspace"].Show(control);

The obvious difficulty with this is that we are just entering the name “LeftWorkspace” as a string, which is prone to error and the compiler can’t check.

So we add the code below to the WorkspaceNames class in Infrastructure.Interface. We add it to the Infrastructure.Interface component because the Workspace is being defined in the Infrastructure part of the solution, but we want it to be available outside of that:

public const string LeftWorkspace = "LeftWorkspace";

Now suppose we want to use this Workspace name in code in a business module. The WorkspaceNames class in the business module inherits from the WorkspaceNames class in Infrastructure.Interface, and hence the constant is available in that class. All we need do is reference that class to access any Workspace name. So we just import the appropriate namespace:

using SmartClientDevelopmentSolution.Module1.Constants;

And then we can do:

_rootWorkItem.Workspaces[WorkspaceNames.LeftWorkspace].Show(control);

Now intellisense is available when we enter the ‘LeftWorkspace’ name, and the compiler can check that what we have entered is correct.

Note that if we have a Workspace name defined just for the module (say ‘LocalWorkspace’) we can still just do WorkspaceNames.LocalWorkspace to access it.

So these Constants folders provide us with an easy way of using named constants for items in the WorkItem hierarchy throughout our code.

December 12, 2007

SCSF Business Modules: Start Up and the ControlledWorkItem (Introduction to CAB/SCSF Part 20)

Introduction

Part 19 of this series of articles discussed business modules in a Smart Client solution generated using the Smart Client Software Factory. This article continues that discussion.

The Load Method of a Business Module

As discussed in the previous article, a business module has a class called ‘Module’ which inherits from class ModuleInit. We saw in part 1 of this series of articles that this means the Load method in that class will get called at start up, provided the module has been added to the ProfileCatalog file.

The Load method of Module generated by the Smart Client Software Factory is as below:

        public override void Load()
        {
            base.Load();
 
            ControlledWorkItem<ModuleController> workItem = _rootWorkItem.WorkItems.AddNew<ControlledWorkItem<ModuleController>>();
            workItem.Controller.Run();
        }

As we can see, it’s creating a ControlledWorkItem class instance and adding it to the WorkItems collection of the root WorkItem. It’s then calling the Run method on the Controller property of this WorkItem.

ControlledWorkItem

ControlledWorkItem is a class that inherits directly from WorkItem. So a ControlledWorkItem is a WorkItem. The ControlledWorkItem also adds additional functionality to the WorkItem, and, crucially, it is a sealed class (which means we can’t inherit from it).

The idea here is that each business module should have a ControlledWorkItem as a root for its functionality. This is what we are creating in the Load method. In the overall WorkItem hierarchy each business module ControlledWorkItem is immediately below the root WorkItem for the entire solution.

Inheriting WorkItem to add Functionality

The ControlledWorkItem has been created to clarify the situation with regard to adding code to WorkItems. When we start using the CAB we quickly find that we need our WorkItems to be extended in various ways. They are intended to control business use cases, after all. For example we may want specific services instantiated at start up and added to the Services collection. Doing this in the WorkItem itself may seem like a sensible thing to do. Clearly the main WorkItem class is a CAB framework class, but we can inherit from it to give it this additional behaviour.

The reference implementations of both the CAB and the SCSF do this: each WorkItem inherits from the base WorkItem class and extend it to give the use case functionality. If you look at the CustomerWorkItem in the Bank Teller Reference Implementation you’ll see this.

Why Inheriting from WorkItem has been Deprecated

The difficulty with this is that our WorkItem class is acting as both a container for all the various WorkItem collections, as we have discussed before, AND as a place where all the code for a business use case goes.

This breaks the Single Responsibility principle, which is that every class should have just one responsibility in a system to avoid confusion.

As a result the Patterns and Practices team have decided it’s not ideal to have developers inherit from WorkItem and add functionality to the derived class. Instead a second class is created to contain the new code, and that class is associated with the WorkItem class by composition.

How ControlledWorkItem Addresses the Problem

This is what the ControlledWorkItem is doing. The ControlledWorkItem class itself inherits from WorkItem, but also has a member variable that references another class. The type of this class is generic (so the developer provides it), and the class is instantiated when the ControlledWorkItem is created.

So in the line of code below we are creating the ControlledWorkItem and adding it to the root WorkItem’s WorkItems collection. However we are also telling the ControlledWorkItem that its member class should be of type ModuleController, and that class will get instantiated and set up as the member variable.

ControlledWorkItem<ModuleController> workItem = _rootWorkItem.WorkItems.AddNew<ControlledWorkItem<ModuleController>>();

We are not expected to inherit from ControlledWorkItem itself. In fact we can’t because it is sealed: the Patterns and Practices team have done this deliberately to indicate that the pattern has changed. Instead we add our additional functionality for the WorkItem to the ModuleController class.

ModuleController

We can access the ModuleController instance from the ControlledWorkItem using the Controller property. We can then call a Run method on that class. This is the standard pattern that is generated by the Guidance Automation Package: note that the final line in the Load method above is:

workItem.Controller.Run();

So we can add start up code for the WorkItem into the ModuleController class in the Run routine.

The SCSF gives us a default ModuleController whenever we set up a Module, as we have seen. This has a default Run method. There isn’t any code that actually does anything in this method, but four empty methods are set up in ModuleController to indicate to us the sort of things we should be doing:

    public class ModuleController : WorkItemController
    {
        public override void Run()
        {
            AddServices();
            ExtendMenu();
            ExtendToolStrip();
            AddViews();
        }
...

There are also comments in these routines to describe what we should be doing inthem. To see this in more detail look in any of the ModuleController classes in the sample code.

WorkItemController Class

Note also above that our default ModuleController inherits from a class called WorkItemController, which is an abstract base class intended to be used just of these controllers. Inheriting from this ensures that we have a Run method in our derived class as there is an abstract function of this name in the base class.

The base WorkItemController also gets a reference to the associated WorkItem using our usual dependency injection pattern. This can be accessed via the WorkItem property on the WorkItemController class.

Finally the WorkItemController class has two overloaded ShowViewInWorkspace methods, which can create and show a SmartPart in a named Workspace in the WorkItem.

Obviously we don’t have to make our ModuleController inherit from WorkItemController. However, if we don’t this base class functionality will not be available.

Conclusion

This article has discussed the standard patterns generated by the Smart Client Software Factory for starting up business (and other) modules.

Part 21 of this series of articles will look briefly at foundational modules, and will also discuss the way names are handling in Smart Client Software Factory projects.

December 9, 2007

Business Modules and Interfaces in the SCSF Smart Client Solution (Introduction to CAB/SCSF Part 19)

Introduction

Part 18 gave a brief introduction to the Smart Client Software Factory. This article continues that discussion by looking at business modules, and also examining how the various modules in a Smart Client solution are expected to interact.

Recap on the Smart Client Application

In part 18 we saw that a ‘Guidance Automation’ package in the Smart Client Software Factory lets you create a base solution for a smart client program. It sets up four projects, three of which are infrastructure projects.

One of the projects is an empty ‘Infrastructure.Module’ project. Infrastructure.Module is a CAB module as described earlier in this series of articles: it isn’t directly referenced by the other projects in the solution but can be used to write infrastructural code for the solution without any tight-coupling with the rest of the solution. We’ll examine this in a little more detail below.

Business Modules

It isn’t intended that we put business logic into the Infrastructure projects discussed above. Instead we are meant to create ‘business modules’.

To create a business module we use another of the Guidance Automation packages: we right-click the solution in Solution Explorer, select Smart Client Factory/Add Business Module (C#), click ‘OK’ in the ‘Add New Project’ window and then click ‘Finish’ in the ‘Add Business Module’ window.

This gives us two new projects in the solution with default names Module1 and Interface.Module1 as below:

scsfprojectmodule.jpg

Once again here Module1 is a Composite Application Block module, and is not referenced by any other project in the solution. However, Module1.dll IS added to the ProfileCatalog (which is in Shell). This means that the Load method of a class inheriting ModuleInit in Module1 will get called by the CAB at start up, as described in part 1 of this series of articles. The class with the Load method in Module1 is called ‘Module’. We’ll look at what the Load method is doing in the next article in this series.

Note here that the Module and ModuleController classes are identical to those in Infrastructure.Module. Note also that there’s really no code at all in Module1.Interface: there are just some empty classes in a folder called Constants.

Business Module Interaction with the Rest of the Smart Client Project

As discussed in part 1 of this series, a ‘module’ is a standalone project to be used in a composite user interface. So our business module here is intended to be a slice of business functionality that can potentially be developed independently of the other modules in the application. Because the business module isn’t directly referenced by other modules a separate development team could potentially work on it and change it. It can then in theory be plugged in to the containing framework without the need for code changes in the framework. The other project’s libraries might not even need to be recompiled since they don’t actually reference the business module directly.

Clearly in practice it’s likely that the business module will have to interact with the rest of the Smart Client solution on some level. There will be a need for:

  1. The business module to use the infrastructure components: for example it might need to put a toolstrip into the Shell form.
  2. Other components in the Smart Client solution to use some of the business module functionality. As a simple example we might have a business module that deals with customers and a back-end customer database. It might have screens to show customer data and allow updates. Another business module might want to display these screens in response to a request: an Orders module might allow a double-click on a customer name to show the customer.

We want to achieve the interaction described above in a way that’s as loosely-coupled as possible, so that we can change the system easily. To do this we make sure that all interaction is through the Interface projects.

We now examine each of these possible scenarios in more detail:

1. The Business Module Using Infrastructure Components

For this scenario in our example solution Module1 references Infrastructure.Interface directly. It is set up to do this by default when you add the business module to the solution. Note that Infrastructure.Interface is intended to (mainly) contain .NET interfaces: it is not meant to contain large amounts of code.

Note that Module1 does not reference Infrastructure.Module or Infrastructure.Library directly, nor should it under any circumstances. These projects may well be under the control of a separate development team from our business module team, and they may need to be updated independently of the business modules. So we reference the interface project, and that handles our interaction with the Infrastructure libraries.

This seems to be a concept that developers working on these projects have difficulty with: almost every member of my development team at work has added one of these libraries to a business module at some stage.

I think the confusion arises because it’s not necessarily obvious how we do this. If my module just references an interface how can I actually call any functionality using just the interface? The answer is that we are once again using the dependency inversion and dependency injection concepts described in part 3 and part 4 of this series of articles.

An example here may help.

Example

We’ll use the WorkspaceLocator service that the SCSF adds into the Infrastructure.Library component when we create a Smart Client solution. The WorkspaceLocator service lets you find the Workspace a SmartPart is being displayed in, although this isn’t relevant for this discussion: all we’re interested in is how to invoke the service from a business module.

There’s a class called WorkspaceLocator that actually does the work in SmartClientDevelopmentSolution.Infrastructure.Library.Services. There’s also an interface in Infrastructure.Interface as below:

namespace SmartClientDevelopmentSolution.Infrastructure.Interface.Services
{
    public interface IWorkspaceLocatorService
    {
        IWorkspace FindContainingWorkspace(WorkItem workItem, object smartPart);
    }
}

Note that Infrastructure.Library references Infrastructure.Interface and so WorkspaceLocator can implement this interface. Note also that our business module, Module1, also references Infrastructure.Interface but NOT Infrastructure.Library. So it can’t see the WorkspaceLocator class directly and thus can’t call FindContainingWorkspace on it directly. So how do we use the service?

The answer is that this is the standard CAB dependency inversion pattern using WorkItem containers to access objects.

At start up the solution creates an instance of the WorkspaceLocator service and adds it into the Services collection of the root WorkItem, referencing it by the type of the interface:

RootWorkItem.Services.AddNew<WorkspaceLocatorService, IWorkspaceLocatorService>();

This actually happens in the new SmartClientApplication class mentioned in part 18, but all we really need to know is that the service will be available on the root WorkItem.

Now, in our module we know we can get a reference to the root WorkItem in our new module by dependency injection in a class:

        private WorkItem _rootWorkItem;
 
        [InjectionConstructor]
        public Module([ServiceDependency] WorkItem rootWorkItem)
        {
            _rootWorkItem = rootWorkItem;
        }

Our module also knows about the IWorkspaceLocator interface since it references Infrastructure.Interface. So it can retrieve the WorkspaceLocator service object from the root WorkItem using the interface, and can then call the FindContainingWorkspace method on that object:

            IWorkspaceLocatorService locator = _rootWorkItem.Services.Get<IWorkspaceLocatorService>();
            IWorkspace wks = locator.FindContainingWorkspace(_rootWorkItem, control);
            MessageBox.Show("Workspace located: " + wks.ToString());

In summary, as long as our module knows the interface to the functionality it needs, and knows how to retrieve an object that implements that interface from a WorkItem collection of some kind, it doesn’t need to have direct access to the underlying class to use the object. This was explained in more detail in earlier articles in this series.

2. Other Components Using the Business Module Functionality

For other components to use our business module functionality we are expected to work out what functionality our business module should expose to the rest of the solution. We should then define interfaces that allow access to that functionality and put them into our Module1.Interface component.

Other components in the solution can then reference Module1.Interface and call the functionality. Note that to allow them to do this we need to ensure that the correct objects are available in a WorkItem, as described above. Once again other components should NOT reference Module1. We can then change Module1 without impacting the other components.

We may of course need to change the interfaces. In this case it may be sensible to retain the old version of the interface component itself so not all other components have to upgrade, and to add a new version with the changed interfaces in as well. The old interface can then be disabled when everyone has upgraded.

Conclusion

This article has examined modules in a Smart Client solution, and discussed how they should interact.

Part 20 of this series of articles will look in a little more detail at some of the new code structures in modules in a Smart Client solution.

A Beginner’s Guide to Credit Default Swaps (Part 1)

Introduction

On our team at work we occasionally employ developers who know nothing about derivatives. It usually falls to me to give these guys a general introduction to the credit derivatives business. As part of that we usually have a session on what a credit default swap is and why it’s important. This article is based on what I say in that session, and as such is an attempt to explain the product to someone who knows very little about the financial services industry.


Government Bonds

It isn’t really possible to understand a credit default swap without having a basic understanding of bonds, so we’ll start with a discussion of what bonds are and why someone might invest in one.

Imagine I have some cash and I want to invest it for a long period. Furthermore assume that interest rates are high and I want to ensure I get a high rate of interest for the period. I would ideally like a fixed interest rate. One way of doing this would be to go to my bank and see what they have on offer. However, most banks don’t offer very generous fixed rate deposits, especially over long periods. They prefer to offer you a variable rate.

An alternative is to buy a bond from the government. To raise money almost all governments periodically issue these bonds. The way they work is that you give your money to the government. The government then pays a fixed rate of interest periodically (usually every six months) on the money you give them. The government does this for a fixed period, usually of several years. At the end of the fixed period they will give you your money back. The end of the fixed period is called the ‘maturity’ of the bond. The amount they pay interest on is called the ‘face value’, the ‘notional value’ or the ‘principal’ of the bond.

What makes this even more attractive as an option is the fact that there is a ‘secondary market’ for bonds. What that means is that there is someone who will buy the bond from me should I not want to hold it to maturity. This is like the stock market. You can buy stocks from individual companies when they issue them, and then (usually) sell them on a stock exchange when you no longer wish to hold the stock. In both cases the price you get will depend on market conditions at the time. Clearly the current level of interest rates will have a major impact on the price you can get when you come to sell your bond. Of course you can buy your bond in the secondary market in the first place, rather than buying it directly from the government.

Should you actually want to do this most of the major stockbrokers will also allow you to trade government bonds, although some cheap online brokers won’t.

So for example, if I look on the US TreasuryDirect site right now I can see that on the 15th August 2007 the US government issued a bond that has a maturity of 15th May 2037 with an interest rate of 5% per year. This is paid every six months (so I get 2.5% of the face value of the bond every six months).

Note that in the United States government bonds issued with a period to maturity of between ten and thirty years are called ‘Treasury bonds’, whilst government bonds issued with a period to maturity of two to ten years are called ‘Treasury notes’. However, these instruments all behave as described above, and are often just referred to as ‘government bonds’.


Corporate Bonds

It’s not only governments that issue bonds, companies do so as well. This is a way of raising money for them, the other alternative being to issue stock. These corporate bonds are typically very like the government bonds discussed above: the company will pay you a fixed interest rate on your money for a fixed period. There’s also a secondary market for these bonds as described above for government bonds.

If you are given the choice between a 10-year corporate bond issued by, say, General Motors (a car company) and a US government bond, which one would you prefer? If the interest rates were the same you’d be wise to go for the US government bond. This is because there’s almost no chance that the US government won’t pay you back your money. It’s going to take a world war or something similar for the US government to be in such trouble that it can’t repay (and in that case you’d probably have bigger worries than your bonds). However, companies can get into financial trouble, even big ones (think of WorldCom, or Enron). If a company goes bankrupt there’s a chance you won’t get all the money you’ve given them for the bond back.

For this reason companies are forced to pay a higher rate of interest on their bonds than the US government. Otherwise no-one will give them the money for their bonds. How much bigger the rate of interest has to be depends on how risky the company is perceived to be.

For example General Motors has issued a bond that matures on the 15th July 2033 paying 8.375%. Whilst this interest rate isn’t directly comparable with that on the US Treasury bond discussed above, if you do work out the numbers you will find that you are getting much more interest from the General Motors bond. This article isn’t going to go into the details of how to do this, as it isn’t strictly relevant to understanding credit default swaps.

Further Reading on Bonds

The sections above have given a very simple overview of bonds. These sections have not described how the secondary markets work, how we price bonds, what a yield is or what yield curves are. If you are interested in such things there are some more details at the links below:

http://www.investopedia.com/university/bonds/
http://www.riskworx.com/resources/Yield%20Curves_RiskWorX.pdf

Credit Default Swaps (CDS)

Suppose that we have invested in the General Motors bond mentioned above. Suppose our investment is $10,000,000. Suppose also that we have become worried that General Motors may be getting into financial trouble. What can we do about it? Obviously we could just sell our bond position in the secondary market. However, we can also enter into a credit default swap. The easiest way to think of a credit default swap is as an insurance contract. We are insuring against the possibility that a company might get into financial trouble and cause us to lose money on our bond position.

To enter into this insurance contract we have to find someone prepared to insure us. Note that this is NOT General Motors. The big banks are usually the people to go to.

What we can do is to pay the bank a periodic small amount of money known as a ‘premium’ (which is like an insurance premium). This is calculated as a percentage of the face value of the bond we are insuring against, which is $10m in our case. This amount (the $10m) is known as the ‘notional principal’. The premium is paid every few months (usually every three or six months) throughout the life of the contract.

In return for the premium the bank does nothing unless General Motors gets into financial difficulty. In that case the bank will pay us an amount equal to the amount we have lost on our bond position. This is likely to be a big sum relative to the small premiums that we will pay. Once this happens the contract will terminate. Otherwise the contract carries on for an agreed period (usually five years). In picture form this looks a bit as below:

cds.jpg

Here the Big Bank is the ‘protection seller’: it’s receiving money in return for providing protection against our bonds falling in value. Similarly we are ‘protection buyers’.

Clearly there are a few things that need to be sorted out before we enter into this contract. Since the Big Bank is going to make us a large payment if General Motors gets into financial difficulty we’d better define what ‘financial difficulty’ means very clearly. We’d also better sort out exactly how we’re going to calculate the amount that will be paid.

Physical Settlement and Cash Settlement

The amount to be paid is slightly the easier of the two to define. We know which bond we want insurance on (the one we are holding), and we know we want to get the reduction in its value as a result of General Motors getting into trouble. There are two ways of handling this. The first is known as ‘physical settlement’. Here we give the bond to the Big Bank, and the Big Bank gives us the full face value of the bond in return (i.e. the amount that was originally paid to General Motors for it). The bank will then try to dispose of the bond in the market. Note that it will be worth much less than the full face value. This is because General Motors is in difficulty and hence unlikely to pay back the full face value at maturity. So from our point of view we’ve given up our bond but been paid face value for it: we’ve been compensated for the reduction in the value.

The second method is known as ‘cash settlement’. Here we try to work out the reduction in value of the bond, and this is just paid from the Big Bank to us in cash. To work out the reduction in value usually a ‘calculation agent’ is appointed in the CDS contract. The calculation agent will go into the market and get a selection of quotes for the bond from which a price for settlement will be calculated in an agreed way. Often the calculation agent is the seller of protection (the Big Bank in our example).

Credit Events

Defining ‘financial difficulty’ is more problematic, and indeed has led to several lawsuits already. We don’t usually call it ‘financial difficulty’, by the way. It’s referred to as a ‘credit event’, or a ‘default’. We say a credit default swap contract is ‘triggered’ if a credit event occurs, meaning the Big Bank has to pay up in our example.

There are three broad categories of credit events that are put into the documentation of credit default swap contracts:

  1. Bankruptcy
    If a company goes into Chapter 11 (in the US) then that is a clear indicator that the company is in serious financial difficulty and that the bondholders may not get all their money back. This is an obvious thing to have trigger the payment in a CDS contract.
  2. Failure to Pay
    If a company fails to make payments it should be making, including coupon payments on the bonds, then this can be documented as a credit event.
  3. Restructuring
    This is where a company changes the payment schedules it makes on its bonds, usually with the agreement of the bondholders. It’s usually not to the bondholders advantage when this happens, and hence CDS contracts can be documented to cover this kind of restructuring as a credit event.

Of these, restructuring is the one that has proved the most problematic for the market. There are now four separate standard definitions for restructuring that can be used in CDS contracts.

Size of Premium Payment is Bigger if the Company is More Likely to Default

One question that has been asked is how large the premium will be in general (see the comments).

The Big Bank in our example is providing us with protection against the default of a company (General Motors).  We are paying them the premium for this protection.  Clearly if the company being referred to is more likely to default the Big Bank will want us to pay them more money.  So the premium rate is higher for riskier companies than for safe ones.

The Big Bank will decide which companies it thinks are risky, and hence what premium it should charge, based on a number of factors.  However, there’s already a market that reflects how risky a company is.  This is the bond market as described earlier in this article.  In the example there General Motors had to pay a higher interest rate on its bonds than the US Government because of the risk that the investor wouldn’t get their money back if General Motors defaulted.

Size of Premium Payment and How it Relates to Bond Prices 

Now consider the case where we buy a General Motors bond.  We then enter into a credit default swap to the maturity of the bond as well.  This acts as insurance against General Motors defaulting on the bond.  We receive interest from the General Motors bond, but pay some of it away in insurance on the credit default swap.

In simple terms we now have overall a bond position where we don’t lose anything if General Motors defaults.  If a default occurs we get our money back from the credit default swap.  We can then invest in another bond.

We can think of this as a risk-free bond position.  This is in many ways equivalent to a position in US Government bonds (which we can assume won’t default at all).  We’d expect our overall interest rate to be similar to that of a US Government bond.  Our overall interest rate is the rate on the General Motors bond less the premium on the credit default swap.

Now suppose the interest rate on a US Government bond is 5% and the interest rate on a General Motors bond of the same maturity is 8%.  We’d expect the premium on a credit default swap on General Motors for the same period to be about 3%.  Note that the 3% premium is also called the ‘spread’ on a credit default swap, since it is the spread between the government bond and the corporate bond interest rates.

Note that this is a very simplistic analysis.  It is broadly accurate but there are reasons why it doesn’t work exactly in practice.

Some Other Terminology Relating to Credit Default Swaps

(i) Reference Entity and Reference Obligation

Note above that General Motors is not directly involved in the credit default swap contract. General Motors as a company will not even know the contract exists. The contract is between us and the Big Bank. General Motors is just an entity that is referred to in the contract, and hence is known as the ‘reference entity’.

Similarly the contract refers to the specific bond we are insuring (General Motors 8.375% maturing 15th July 2033 in our example). However the bond isn’t directly involved in the contract. Indeed if the contract is cash settled we don’t even have to be holding the bond at any time: we can just enter into the CDS contract without it. The bond is just an obligation being referred to in the contract, and hence is known as the ‘reference obligation’.

You should know that, at least in technology, everyone’s favourite interview question about credit default swaps is ‘what’s the difference between a reference entity and a reference obligation?’

(ii) Bond Seniority

Bonds have a hierarchy of importance when a company is unable to pay its debts. Some bondholders will get their money back before others. (They ALL get their money back before the shareholders.) The exact place in the pecking order depends on the documentation of the bonds. Typically bonds are classified according to ‘seniority’. They are assigned to one of senior secured, senior unsecured, senior subordinated, subordinated and junior subordinated seniority categories. The list is in order of seniority: senior secured is the highest, junior subordinated the lowest. This means if we hold a senior secured bond we are more likely to get our money back if the company goes bankrupt than if we hold a junior subordinated bond.

When a company is being wound up the bondholders get paid in seniority order out of the cash that is remaining to the company. The bondholders with the highest seniority debt get paid first, then the bondholders with the next level of seniority debt, and so on. Bondholders will get paid in full in each seniority category until the money runs out. If at any stage the money is insufficient to pay the current seniority of bondholder in full, every bondholder of that seniority gets paid the same percentage of the face value of their bond.  So, for example, the most senior bondholders may get paid in full, one category of more junior bondholders will only get a percentage payout, and the most junior bondholders may get nothing.


(iii) Recovery Rates

The ‘recovery rate’ is the percentage of the face value of our bond that we get back if there’s a credit event. For example, suppose we hold $10m of bonds in a company, and it goes bankrupt. Assume we get $4m back for our bonds from the company after the bankruptcy. We would say our ‘recovery rate’ is 40% (4m/10m as a percentage).

Recovery rates are also one of the inputs into pricing a CDS contract (working out its value to either counterparty) prior to maturity. To price a CDS one of the things we need to know is how much the bond we are insuring will reduce in value if a credit event occurs. This is obviously important since it determines the size of the payment made as a result of the credit event. Clearly we can’t know exactly how much the bond will be worth after a credit event before the credit event has happened, so we estimate a recovery rate.

Most pricing methodologies estimate recovery rates in a very simplistic way: a percentage is assigned to the seniority of the debt of a company. So we might say General Motors Senior Unsecured debt has a recovery rate of 40%, and then use that number for pricing all GM senior unsecured credit default swaps.

Uses of Credit Default Swaps

As described above it sounds like the credit default swap is a very niche product since its primary use is to hedge bond positions against default. However, the credit default swap market has taken off and is huge. The reason is that there is a wide range of ways CDS can be used. In recent years pure speculation, largely by hedge funds, seems to have been the main driver of the market.

Geoff Chaplin’s excellent book ‘Credit Derivatives: Risk Management, Trading and Investing’ cites the following uses of CDS:

  • Directional Trading/Relative Trades (speculation on individual companies)
  • Debt Hedging (hedging bond positions as described above)
  • Sector/Portfolio Trades (speculation on groups of companies)
  • Income Generation (we can just sell protection and receive premium, provided we’re confident we won’t face defaults (credit events))
  • Regulatory Capital Reduction (if a bank has lent to a company that uses regulatory capital which can be reduced by buying CDS protection)

Issues

Below are a few further issues relating to credit default swaps:

  • The description of CDS as ‘insurance’ is not technically accurate. Insurance contracts are regulated in a different way, the documentation is different, and usually an insurance contract would require us to actually own the bond to be valid for a claim, which is not the case for a CDS.
  • As mentioned above, there’s no reason for either party to a CDS contract to actually be holding a bond (reference obligation) of the reference entity. CDS can be entered into purely as speculative positions. Even with physical settlement the buyer of protection can just go into the market and buy the appropriate bond at the time of a credit event, and doesn’t need to hold it through the life of the contract.
  • CDS contracts are usually not entered into with retail investors. You or I couldn’t actually execute a CDS on our bond position; we don’t have big enough positions to make it worthwhile in general. Hedge funds, pension funds, fund managers and insurance companies tend to be the counterparties to the banks on these contracts (as well as other banks).
  • Credit default swaps are usually documented such that a range of bonds can be ‘delivered’ (handed over in physical settlement or used to calculate losses in cash settlement). The text above implied that only one bond was ever relevant. The reference obligation cited in the contract simply defines the type of bond that can be delivered (its seniority). Usually any bond of the same seniority or higher seniority can be delivered. CDS can be traded without any reference obligation being cited: usually this means that any senior unsecured debt can be delivered.
  • This is a zero-cost instrument. The two parties to the contract just agree the details up front, and the contract starts without any initial payment being necessary. If you are a seller of protection you just get premium in without having to do anything, which can be attractive.

Summary

In summary, a credit default swap is a contract where one party to the contract pays a small periodic premium to the other, in return for protection against a credit event (financial difficulty) of a known reference entity (company).

This article was written in 2007.  Since then there have been a few developments in the credit default swap market.  A discussion of these developments can be found in part 2 of this series of articles.

December 8, 2007

Introduction to the Smart Client Software Factory (CAB/SCSF Part 18)

Filed under: .net, CAB, Composite Application Block, SCSF, Smart Client Software Factory — richnewman @ 5:45 pm

Introduction

So far in this series of articles the focus has been on the core functionality of the Composite Application Block (CAB). No mention has been made of the Smart Client Software Factory (SCSF), in spite of the fact that the series is entitled ‘An Introduction to the Composite Application Block and the Smart Client Software Factory’.

This article and the ones that follow will remedy that. They will discuss what the Smart Client Software Factory is, how it relates to the Composite Application Block, and how to use it.

Versions of the Composite Application Block and Smart Client Software Factory

The first version of the Composite Application Block was released in December 2005. This had all of the features that have been described in this series of articles so far. As was mentioned in part 1 of this series, the Composite Application Block on its own is quite difficult to understand and learn how to use. Furthermore, documentation and support in the initial version were somewhat lacking: many developers complained that they couldn’t understand how to use the new framework.

The Patterns and Practices team released a follow-up version in June 2006, and another in May 2007. However, they did not attempt to change the core Composite Application Block code. Instead they provided additional documentation and examples, as well as a way of automatically generating code for various useful patterns using the Composite Application Block. We’ll examine this in a little more detail below.

The idea behind these SCSF releases was to make it easier for developers both to learn and to use the Composite Application Block software (and other application blocks). However, as we shall see, the SCSF introduces new code and patterns on top of the CAB’s already complex structures, and the documentation could still be clearer. In many ways the Patterns and Practices team have added to the confusion with these releases rather than clarifying the situation.

Software Factories

The last two releases were branded as the ‘Smart Client Software Factory’. A ‘software factory’ is one of the latest computer industry buzzwords.

The idea behind software factories is that current software development practices depend on highly-skilled developers, who are similar to craftsmen in a pre-industrial age. The argument is that the need for highly-skilled craftsmen is the reason that many software projects fail: there are too few really good craftsmen, and they are usually hand-crafting from scratch in every new project. We need to ‘industrialize’ the software development process. Software should be created using ‘software factories’.

Like many computer industry buzzwords, what a ‘software factory’ is in practice is a little unclear. It tends to vary depending on the author, but in general a software factory should provide a means of producing code in a standard way. This may mean reusing and customizing existing code, simply following a set of guidance practices, or generating code automatically based on a model, which may be visual. It may mean a combination of all of these techniques. The phrase is also often used to describe model-driven development, possibly using domain-specific languages.

Smart Client Software Factory

Microsoft’s ‘software factory’ is slightly simpler than some of the usual definitions described above. The ‘Smart Client Software Factory’ comprises a small set of code generators plus some documentation and examples. The code generators are quite straightforward, producing code to set patterns (there’s no model to be maintained here).

The paragraph below is from the SCSF documentation:

‘The software factory provides a set of proven and integrated practices that are exposed through patterns, How-to topics, QuickStarts, a reference implementation, a Visual Studio Guidance Automation Toolkit package, and architecture documentation. The software factory guides projects through the development of smart client applications based on the architecture of the Composite User Interface Application Block.’

The Visual Studio Guidance Automation Toolkit Package

The Smart Client Software Factory includes a ‘Visual Studio Guidance Automation Toolkit Package’. This is an add-in to Visual Studio that automates certain software development tasks relating to the CAB. Some of these are added to the right-click context menu in Solution Explorer.

Probably the most useful Guidance Package, however, is the one that generates a new Smart Client Application project. This is also a good place to start when investigating what the Smart Client Software Factory can do.

This Guidance Package is available if you request a new project in the usual way inside Visual Studio after the SCSF has been installed. The New Project window has a project type of ‘Guidance Package’ available. Underneath that you can choose a new ‘Smart Client Application (C#)’:

newscsfproject.jpg

If you select this option the Guidance Package will show a screen that allows you to set some properties of your solution. In particular you need to tell the Package where the Composite Application Block libaries are, and to set some options. These include whether you want a separate module for layout of the Shell (in general you won’t want this). The Guidance Package will then set up a Smart Client solution as below:

scsfproject.jpg

The SmartClientDevelopmentSolution

This is a base solution for a smart client project using the Composite Application Block. It gives your code some basic structure. It also gives you a lot of code on top of the Composite Application Block code itself: the various projects contain about 3,000 lines of code in total.

So we have even more code to try to understand if we are to use the resulting project effectively.

As you can see we are given four basic projects:

1. Shell

This is the start-up project for the solution. It is very similar to the start-up projects in the sample applications we’ve already seen in this series of articles: it has a start-up class (ShellApplication) which (indirectly) inherits from FormShellApplication. It has a form, ShellForm, which is the containing window for the application. It has a ProfileCatalog which will contain the composite application modules to be loaded.

If you compare this the Naïve Application sample code from part 1 of this series of articles you will see the similarities.

However, there are subtle differences as well, mainly in the form of extra code constructs. For example, ShellApplication actually inherits from a class called ‘SmartClientApplication’ which in turn inherits from FormShellApplication. The SmartClientApplication class simply sets up some SCSF services.

Additionally the ProfileCatalog now allows us to specify dependencies. We also have a Constants folder with a series of class files in it. We’ll examine these extra code constructs in later articles.

2. Infrastructure.Interface

The remaining Infrastructure projects are intended to provide common functionality for all of the composite applications we add into our solution. However, we don’t want to directly reference the projects that contain the code. Instead we want to hide the code behind interfaces in a separate library and reference the interface library. Infrastructure.Interface is this interface library. It mainly contains interfaces, with some simple classes.

3. Infrastructure.Library

The Infrastructure.Library project contains the bulk of the new code that this SCSF solution gives us. In fact it contains about 2000 lines of code, including such things as the Action Catalog, and support for loading modules using sources other than ProfileCatalog.xml.

4. Infrastructure.Module

Infrastructure.Module is an empty module project. It is intended that any code that we as developers want to add to the infrastructure section of our solution will go in here. It is a CAB module, which we have seen before, and it contains a ModuleInit class as we’d expect (see part 1 of this series of articles). However, it also contains a ModuleController class, which inherits WorkItemController. This will be discussed further in the next article.

Conclusion

This article has given us an overview of the Smart Client Software Factory, and shown how one of it’s key components is the ability to create a standard solution that can be used as the basis for a Composite Application Block application.

Part 19 of this series will discuss this solution a little more, and will look at SCSF Business Modules.

References

Discussion of software factories:
http://www.methodsandtools.com/archive/archive.php?id=64

The Shocking Blue Green Theme. Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.

Join 81 other followers