Home > Articles > Programming > Windows Programming

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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020