Home > Articles > Programming > Windows Programming

  • Print
  • + Share This
This chapter is from the book

Supporting Customization

As I noted at the start of this case study, part of this solution includes giving the developer the ability to modify the connection string retrieved from the configuration file. There are at least two ways to provide this option:

  • Add a second partial class (the "customization" class) where the developer can add code to modify the connection string. The class holding the generated code calls methods in this second class before returning the connection string to the calling application. The developer can add code inside these methods to modify the connection string.
  • Allow the developer to inherit from our generated class. Again, our generated code would call methods that allow the developer to modify the connection string before the string is returned. However, with this design, the developer would override those methods to add his or her own code.

For this case study, I use the first strategy. As part of that strategy, I add a second file to the project (named ConnectionManager.Customization) where developers can put their custom code.

I also allow the developer to turn customization on and off so that when the developer doesn't need to modify the connection string through Visual Studio's Options dialog, the customization support (e.g., the ConnectionManager.Customization file) won't be generated.

Customizable Code

When customization is turned on, the property generated calls a method and passes it the connection string. The property then returns whatever is passed back by the method. A typical example of the generated code with customization support looks like this:

public static string Northwind
{
 get
 {
  return NorthwindCustomization(
         System.Web.Configuration.WebConfigurationManager.
             ConnectionStrings["Northwind"].ConnectionString);
 }
}

The corresponding customization class contains stubs for the customization methods:

public static partial class ConnectionManager
{
 public static string NorthwindCustomization(string ConnectionString)
 {
  return ConnectionString;
 }
}

Developers can now put any code to modify the connection string in these stubs. To ensure that the developer never loses any code, my code never deletes the customization class. If a customization stub doesn't exist, the code-generation process will add the stub. However, no compile error is raised if a developer renames (or deletes) a connection string that he or she has written customized code for. Unfortunately, the customized code will never be called.

The add-in offers one other customization option. Although the add-in's default implementation is a static/shared class, developers may find that too restrictive when they start adding their custom code. In order to give the developers more options, I also allow them to turn off the static/shared option.

Accepting Input

Rather than expect the developer to specify these options for each generation, I let the developer set the customization options in the Tools | Options dialog. For a complete solution, the options should be stored on a project-by-project basis so the dialog for these choices should be a list of projects showing the choice for each option. However, that would take the focus of this case study into the realm of Windows Form programming and away from creating an effective code-generation implementation, so this example just supports a global setting that applies to all projects.

Defining the Options Dialog

My first step in adding to the Tools | Options dialog is to create a separate project (named ConnectManagerUI) to hold the user control that becomes part of the Tools | Options dialog. Because, even for testing purposes, this project's DLL must go into the Add-Ins library, I create a new class library project and set the output path on the Tools | Options | Build dialog to ...\Visual Studio version\Addins\.

In order to have the user control loaded by Visual Studio, I add the following elements to my add-in project's .Addin files (this code assumes that the user control will be called ConnectionManagerOptions). The Tools | Options dialog uses the values in the Category and SubCategory elements to create the TreeView on the left side of the dialog that lets the developer navigate to my user control. I also use the Category/SubCategory values in my add-in's code to retrieve the options the developer sets:

<ToolsOptionsPage>
 <Category Name="Code Generation">
  <SubCategory Name="Connection Manager">
   <Assembly>ConnectionManagerUI.dll</Assembly>
    <FullClassName>ConnectionManagerUI.ConnectionManagerOptions
    </FullClassName>
  </SubCategory>
 </Category>
</ToolsOptionsPage>

Saving Developer Choices

It's my responsibility to save and retrieve the choices entered by the developer in the Tools | Options dialog. To support that, I add a class to my CodeGenerationUtilities project with methods that save and retrieve string values to and from the Windows registry. That class looks like this:

namespace CodeGenerationUtilities
{
 public class Utilities
 {
  public static string GetValue(string Name)
  {
   Microsoft.Win32.RegistryKey key;

   key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(
                  @"SOFTWARE\Microsoft\VisualStudio\9.0", false);
   return key.GetValue(Name, "").ToString();
  }

  public static void SaveValue(string Name, string value)
 {
  Microsoft.Win32.RegistryKey key;

  key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(
                   @"SOFTWARE\Microsoft\VisualStudio\9.0", true);
  key.SetValue(Name, value,
                       Microsoft.Win32.RegistryValueKind.String);
 }
}

Option Manager Class

Before creating the user control, I also create a class in the same project as the user control to manage the values entered by the developer. In addition to simplifying the code in the user control, this option manager class is required if I'm going to pass the values saved by the user control to the add-in that generates the code.

The option manager class has one property for each value I allow the developer to set in the user control and uses the SaveValue and GetValue methods in my Utilities class to save data in the Windows registry as strings. The code in the option manager class sets the names that these values will be saved under in the Windows registry. The naming convention that I use is the word "Generate," followed by the name of the code-generation solution, followed by the property name.

This option manager class for this case study has properties for turning customization support on or off (SupportCustomization, which saves its value under the name GenerateConnectionManagerSupportCustomization) and specifying whether the class and property should be static/shared (IsStatic, which saves its value under the name GenerateConnectionManagerIsStatic):

namespace ConnectionManagerUI
{
 public class ConnectionStringProperties
 {
  public string SupportCustomization
  {
   get
   {
    return Utilities.GetValue(
        "GenerateConnectionManagerSupportCustomization");
   }
   set
   {
    Utilities.SaveValue(
        "GenerateConnectionManagerSupportCustomization", value);
   }
  }

  public string IsStatic
  {
   get
   {
    return Utilities.GetValue(
        "GenerateConnectionManagerIsStatic");
   }
   set
   {
    Utilities.SaveValue(
        "GenerateConnectionManagerIsStatic", value);
   }
  }
 }
}

Creating the User Control

I'm finally ready to add the user control that will appear in the Tools | Options dialog (see Figure 9-2). The user control has two check boxes, one for each of the two options offered by this add-in: whether a customization file will be generated and whether the generated classes should be static/shared.

Figure 9-2

Figure 9-2 The user control for the case study allows the developer to turn support for customization on or off and to specify whether the generated class is static/shared.

I must add two attributes to the user control to have it work well with the Tools | Options (ComVisible and ClassInterface). In addition, the user control must implement the EnvDTE.IDTToolsOptionsPage interface. This code shows the resulting definition for the user control for this case study:

namespace ConnectionManagerUI
{
 [System.Runtime.InteropServices.ComVisible(true)]
 [System.Runtime.InteropServices.ClassInterface(
    System.Runtime.InteropServices.ClassInterfaceType.AutoDual)]
public partial class ConnectionManagerOptions: UserControl,
                                             EnvDTE.IDTToolsOptionsPage
 {

In the user control, I take advantage of the option manager class that I created earlier to do most of the user control's work. I instantiate that class in my user control's constructor:

public ConnectionManagerOptions()
{
 InitializeComponent();
 opts = new ConnectionStringProperties();
}

Implementing the User Control Interface

The IDTToolsOptionsPage interface adds several methods to the user control, but I only need to put code in four of them. I add code to the OnAfterCreated event to retrieve the current values for the property and to the OnOk event to save the current values. In these events, I just call the appropriate methods on my option manager class (with a little extra code to initialize the page when the user control is called for the first time):

public void OnAfterCreated(EnvDTE.DTE DTEObject)
{
 if (opts.IsStatic == "true"|| opts.IsStatic == "")
 {
  this.StaticCheckbox.Checked = true;
 }
 else
 {
  this.StaticCheckbox.Checked = false;
 }

 if (opts.SupportCustomization == "true")
 {
 this.CustomizationCheckbox.Checked = true;
 }
 else
 {
  this.CustomizationCheckbox.Checked = false;
 }
}

public void OnOK()
{
 if (this.StaticCheckbox.Checked)
 {
  opts.IsStatic = "true";
 }
 else
 {
  opts.IsStatic = "false";
 }

 if ( this.CustomizationCheckbox.Checked)
 {
  opts.SupportCustomization = "true";
 }
 else
 {
  opts.SupportCustomization = "false";
 }
}

Because I intend to pass the values collected in the user control to an add-in running in Visual Studio, I also implement the interface's GetProperties method. All that I have to do is to set the PropertiesObject passed to this routine to an instance of my option manager class:

public void GetProperties(ref object PropertiesObject)
{
 PropertiesObject = opts;
}

Integrating with the Add-In

With the work on the user control complete, the developer can choose his or her options in the Tools | Options page. I access the developer's choices by retrieving a Properties object from the applicationObject, specifying the Category and SubCategory I set in the .add-in file's ToolsOptionsPage element. I typically end up using these options throughout my add-in, so I usually declare the Properties object at the class level:

Properties props;

I then retrieve the options in the add-in's constructor. To retrieve the options set through the user control, I pass the Category and SubCategory I set in the ProvideOptionPage attribute on the user control to the get_Properties method on the applicationObject. (In Visual Basic, you read the Properties property.) In the get_Properties method, the SubCategory value is passed to a parameter called PageName. For this case study, the Category is "Code Generation" and the SubCategory is "Connection Manager":

props = applicationObject.get_Properties["Code Generation",
                                           "Connection Manager"];

To retrieve any particular property, I pass the property name from my data manager object to the Properties object's Item method. This example, for instance, retrieves my IsStatic method from my option manager class and, because the value returned by the property is a string, converts it into a Boolean value:

bool IsStatic;

if (props.Item("IsStatic").Value.ToString() == "true")
{
 IsStatic = true;
}
else
{
 IsStatic = false;
}

The resulting values can be used to control code generation. For instance, this example uses the IsStatic value to control whether the class is declared as static/shared:

if (!IsStatic)
{
 cc.IsShared = true;
}

Generating Custom Code

Working with a file that holds code written by the developer requires a different strategy than a file holding only code you generate. In general, it's never okay to delete a developer's code, but it is okay to make the code invalid or irrelevant.

As an example, in this case study the developer may add custom code to work with the Northwind property that is tied to the Northwind connection string. If the developer then deletes the connection string named "Northwind" from the configuration file and ConnectionManager is regenerated, my solution will re-create the ConnectionManager.Generation file without the Northwind property.

Without the Northwind property in place, the developer's custom code is orphaned and will never be called—but that's not a problem (at least, it's not your problem). Even if removing the generated Northwind property prevents the solution from compiling because of problems with the custom code (not the case with this solution), the problem is—from the developer's point of view—solvable: When the compile fails, the developer will get a message pointing to the offending custom code. The developer can then modify or delete the code.

What would not be a good idea would be to "helpfully" delete the developer's custom code. After all, the developer may intend to move his or her orphaned custom code to another custom routine—if my solution deletes the code, that option is no longer available to the developer.

In the customization file, the general strategy is to first check before adding any custom code to see if it's already present. If the code is present, the solution should leave the code alone; if the custom code isn't present, the solution should generate whatever support code is part of the code-generation solution. If the developer wants to have any support for custom code regenerated, all the developer has to do is delete the relevant custom code. With the custom code gone, the solution will regenerate any necessary support code.

Adding Custom Code

In the case study, the first place where I implement this strategy is in adding the customization file. For the file holding the generated code, the file is always deleted and re-created. For the customization file, on the other hand, if the file is present, the solution just retrieves a reference to it; only if the customization file isn't already present does my solution generate the customization file. This code checks to see if customization is being supported and, if it is, implements that strategy:

if (IsCustomized)
{
 pjic = sln.FindProjectItem(@ProjectPath + @"\" +
      codeFolder.Name + @"\ConnectionManager.Customization.cs");
 if (pjic == null)
 {
   if (prj.Kind == "{E24C65DC-7377-472b-9ABA-BC803B73C61A}")
   {
    ItemTemplatePath = sln.GetProjectItemTemplate("Class.zip",
                                                     @"Web\CSharp");
   }
   else
   {
    ItemTemplatePath = sln.GetProjectItemTemplate("Class.zip",
                                                       "CSharp");
   }
   pjic = codeFolder.ProjectItems.AddFromTemplate(
        ItemTemplatePath, "ConnectionManager.Customization.cs");
 }
}

The same process is followed when adding the support stubs inside the customization file: Stubs are only added if they're not already present.

  • + Share This
  • 🔖 Save To Your Account