Ok, so between naps (of my 21-month-old son) and some late nights, I've managed to get the source code from my presentation last Tuesday put together. You can downoad the source and my presentation and follow the readme.txt to get set up. The source has examples of consuming all of the application blocks. It also includes an example of how to integrate ASP.NET's Forms Authentication and EntLib's Authentication/Authorization block.
On another VB.NET note, for anyone using the BuildRules tool included in the Microsoft Visual Studio .Net 2003 Automation Samples and have noticed that when you have a reporting project in your solution the BuildRules tree doesn't populate itself, the bug is essentially the same bug as the one I fixed in VBCommenter. There's a "foreach (project in solution.projects)" or some such loop in the BuildRules code, which fails somewhat silently when a reporting services project is in the solution. If you change it to an indexed loop going from 1 to the count of the Solution.Projects.Count property (yes, it really is a one-based array) and get the project using the Projects.Item(index) property, it will work again. This appears to have something to do with the COM interface to VS.NET and its implementation of the COM equivalent of IEnumerable.GetEnumerator (NewEnum? Sorry, I wasn't a COM guy before .NET) method, which fails in this case.
I've just posted a new release of VBCommenter on the GotDotNet workspaces. This tool has been invaluable to us on my current project, where VB.NET has been mandated but where we wanted to create our API documentation just like a C# project. However, there were several issues with the 1.2 release that caused us issues, and over the last few months I've been slowly working on cleaning them up. Major improvements over the 1.2 version include:
If you happen to live in the Cincinnati area and read my blog - I'm giving a presentation on Enterprise Library tonight at the Cincinnati .Net Users Group - see their site for directions. The presentation will start at 6pm and last until around 7.
In my first article on Enterprise Library configuration, I talked about how to build your own "root node" in a configuration file. We also discussed how to use the ILinkedNodeService to reference another configuration node from within your custom configuration section, and went over some details as to how the code worked in relation to the configuration manager tool. I provided a downloadable code example that I will use again in this post.
Before I get started, I wanted to point you to the tool that myself (and many others) use to get our VS.NET code into such nice HTML format - it's called CopySourceAsHtml by Colin Coller. Thanks for such a time-saving tool.
In this post, I'm going to discuss how you can create customized "providers" (the Enterprise Library term for pluggable modules that fit within the code EntLib frameworks), and how those providers can use the configuration tool to gather customizable information from the user beyond default key/value pairs you get without any additional work. We're going to build an Authorization Provider that will authorize a given request based solely on the system's pseudo-random number generator and a threshold value provided through the configuration framework.
If you open up the solution, we'll be looking at the EntLibFrameworkConfigDemo project this time. I want to start with the MyAuthenticationProvider class, which is the actual random authenticator.
The IConfigurationManager interface:
What we're interested in here is the IConfigurationManager implementation, which is nothing more than the Initialize method. This method is called when the provider is first loaded, and provides the framework a way to pass configuration data to the provider. Here we check to make sure we've received the right type of configuration data and then initialize the private variables from the configuration data. Pretty simple all in all. The SecurityConfigurationView class is part of the core EntLib class library and provides several utility methods including the GetAuthorizationProviderData we use to retrieve the authorization data, which is defined in the MyAuthroizationProviderData class. Both the MyAuthorizationData and the MyAuthroizationProviderNode don't add anything new from my previous post, so I'm not going to go into detail on them here. The major difference between the two examples is in the DesignManager class, in this case MyAuthorizationProviderDesignManager class:
Because we are simply adding a new provider of a type the configuration manager already knows something about, we just have to figure out how to add our type to the correct menu item. In this case, the key is to know that in the RegisterXmlIncludeTypes method to call the AddXmlIncludeType takes the section name as its first parameter. Otherwise, the major difference between this class and the AppConfig example is that this one is much simpler. Most of the implementation of the IConfigurationDesignManager interface is not necessary, and there is no CreateCommands method, as the command to create an authentication provider node is already part of the configuration manager.
With that, I'll leave you to explore the Enterprise Library configuration management classes.
So I've finally gotten comfortable enough with the configuration management tool to post some examples. I'll be doing a 2-part series on the Enterprise Library configuration framework and how you can incorporate your own application configuration into the tool and also customize the configuration offered by your custom frameworks.
I've included two projects in the downloadable solution. The first is essentially a customized appsettings node that can be edited in the configuration tool. The second is an overly simplified Authorization manager, which shows how to extend the existing frameworks and provide a user-friendly way to edit the configuration data for those extensions.
Update: I missed four lines of code in my example download code (sent an older version to James) and as of 11:51 PM EST on 2/2/2005, I've sent the update to James to get to his site. If you download it before he uploads the update, simply take the code in the blog post for the AppConfigNode.cs file and replace the code in the download with this code. Sorry for the inconvenience.
Update 2: It's now 9:45am on 2/3/2005 and James has updated the download.
Customized Application Configuration Nodes
Each customized configuration node requires several classes in order to be completely integrated with the configuration management tool. The first, as explained in the EntLib Quick Starts, is the container class, usually named with a postfix of "Data." This class is the class that is actually serialized to the config file, and is fairly simple.
Note that the "State" property is defined by an Enum type, and in the configuration tool you will find that this data is represented by a drop-down list as you would expect. As stated earlier, this class is really just a data container, and the next class, the AppConfigNode, defines how this class is displayed in the configuration tool and what happens when certain events like node renames or removes happen in the tool. These events allow you to utilize other configuration nodes, like the database in this example, and be assured that when the user renames or removes them you can handle those changes appropriately. Here's the source for the AppConfigNode class, which we'll dig into more once you've read over it.
There's a lot going on in this class, so we're going to take some time to understand it better.
The first thing to notice are the attributes attached to the public properties of the class. Most of these attributes are from the System.ComponentModel namespace, and are the same attributes you would use when create a design surface for a custom control. The Browsable(false) attribute tells the designer not to display the attribute in the designer, and the Category(), Description(), Required(), and ReadOnly() attributes should be self-explanatory. Many of the EntLib classes use SRCategory() and SRDescription() attributes, which use the as-yet-unreleased StringResource custom tool to derive their values. Hopefully that will be released to the public soon, because I like the concept of the StringResource tool and the SR* attributes.
One other set of attributes to note are the Editor() attribute on the Database property, which specifies that the run-time configuration tool should use a special control to display the choices for this type. The ReferenceEditor class will filter the nodes based on the type provided, and only display those nodes that exist in the current config file.
Update before posting: Someone has now release a String Resource Tool.
The ILinkNodeService and Referencing Other Node Types
Note that the Database property is of type InstanceNode, and that, when set, we use the ILinkNodeService instance provided by a call to the base class's GetService method to inform the configuration manager that we'd like a reference to that node by calling the CreateReference method. Further, we pass this method a few delegates to handle changes in that node, including removal or renaming of the node. In this way, whenever the user modifies our referenced node, we are informed of the change and can handle it appropriately.
Our class overrides several members of the ConfigurationNode class to handle certain additional events that happen on all configuration nodes:
- ResolveNodeReferences() - This method is called to provide the ConfigurationNode an opportunity to find it's dependent nodes when it is loaded in the configuration manager. Because our configuration node uses a Database instance node, we take this opportunity to find the referenced node in the configuration heirarchy and set our Database property appropriately. Note that, in theory, the FindNodeByName call could fail if the user manually edits a configuration file, but, in that case, our Database property should just be null and (if it were a required field) would force the user to pick a new node before the file would be saved.
- AddDefaultChildNodes() - This method is called to make sure that, if your configuration node requires another node, you have an opportunity to create it if no node of that type exists. Here, we call a private method that checks to see if any database nodes exist, and, if not, add a new, empty database instance to the configuration. You can demonstrate this if you simply add a new application and then our "Test Application Configuration" node in the configuration manager. You'll notice that the entire Data Access Application Block configuration section is automatically added to the configuration file.
- OnSited() - This is called when your node is added to the configuration file. In our case, we only want one instance of our settings node per application, and we don't want the user to be able to edit the name of the node, so we take this opportunity to set the name of the node in the configuration tree to "Application Configuration."
- OnRenamed() - Called when the user renames the node. Of course, our node is not renamable and, therefore, this method would never truly be called. However, I kept it in the code so you would be aware of its existence and use.
That's about it for the AppConfigNode class. Hopefully you have a better idea of the magic behind the node. Now, we just have to get the configuration manager to know how to serialize/deserialize our class and how we expect users to add it to our configuration file. These tasks are accomplished by the AppConfigManager class:
IConfigurationDesignManager Ties It All Together
So you've got your data class, and you've got your node class, but you still can't see it in the configuration manager. Although there are a few tricks left after this class is implemented, they are nothing more than attributes and post-build events. It is the IConfigurationDesignManager interface that lets you register your classes in the configuration manager and create new menu items in the appropriate places for those classes. So, let's dig in:
- Register() - Most of the UI-level hookups happen in this method. We register our Node types, which tells the Configuration Manager which visual classes we support in our assembly. We register our XmlIncludeTypes, which tell the configuration tool how to serialize and deserialize our data classes. And then, we add a new menu command to allow our uses to click on a "Test Application Configuration" menu item to add our new node to their configuration file. These things all happen in the private implementation details section, which, because of its importance to the grand scheme, I will go into in more detail below.
- BuildContext() - Simply adds our data to the configuration dictionary. Even Scott Densmore doesn't think the context is all that interesting.
- Open() - When the configuration manager finds the XML representation of one of our Data classes in the configuration file, it calls the Open method to let our manager map the data class to the appropriate visual node element.
- Save() - When saving the configuration file, this method is called and we write our data back out to the configuration file. If any exceptions are thrown during the write, we log the exception so the configuration manager can display it to the user to fix.
The Guts (Private Implementation Details)
These methods are important as they are what drives the addition of our classes into the config tool in the IConfigurationDesignManager.Register() method, so let's look a little more carefully at these:
- RegisterNodeTypes() - This method retrieves the default instance of the NodeCreationService provided by the ServiceProvider passed to us (which will be implemented by the configuration management tool). Once we have a node creation service, we register our AppConfigNode type as available for use, and mapping our AppConfigNode and our AppConfigData types together.
- RegisterXmlIncludeTypes() - Similar to the RegisterNodeTypes method, we retrieve an instance of the XmlIncludeTypeService provided by the configuration manager and register our AppConfigData type to be mapped to the given section name.
- CreateCommands() - Get the UI Heirarchy service, find the currently selected node in the heirarchy, and check to see if we already have an instance of our node (the containsNode variable). We'll use this information later to enable or disable our menu item based on this result. Then, get the IMenuContainerService instance and add a new menu command to the New menu (InsertionPoint.New) at the root node level (ServiceHelper.GetCurrentRootNode()) that will execute the AddConfigurationSectionCommand.ExecuteCore() method to add our config section, using the display text "Test Application Configuration" and enabled/disabled based on if we have our node in the configuration already (containsNode).
What's left? (Answer: Attributes and Build Events)
Two things remain to get your assembly registered with the UI:
- Add an attribute to your AssemblyInfo.cs file that tells the configuration manager UI which class(es) in your assembly implement the IConfigurationDesignManager interface. The relevant sections of the file are:
- Push the DLL and any required reference DLLs to the EntLib\Bin directory (usually C:\Program Files\Microsoft Enterprise Library\Bin) so that the configuration manager can find them when it's loaded. As I develop a new configuration management implementation, I tend to like to be able to easily debug these classes so I also push the PDB files. If you run into issues, just add a call to System.Diagnostics.Debugger.Launch() in your code and then, when the configuration tool loads your assembly and fires off the relevant method, you can force the debugger to attach to the configuration manager and find your error. The file copy is accomplished using a post-build event on the project (mine is completely generic except for the location of EntLib, and so these two lines can be added to pretty much any project to move the target DLL to the correct directory):
So that walks you through everything you need to know to add a single-instance configuration node to the root of your configuration file and allow your end-user to edit it easily in the configuration manager. OK, so it's nowhere close to everything, but I believe this should give you enough understanding to go "code spelunking" on your own.
Good luck. The next installment will cover extending existing frameworks with your own implementations, which require custom configuration sections of their own to be integrated with the tool. I'll use an AuthorizationProvider as an example, and you'll see that, once you grok the tool, it's not difficult to add your own configuration sections anywhere you need them.