SharePoint Calculator Service Part 6 – Custom Admin Setting

In Part 5 of this series, we created a PowerShell cmdlet to enable SharePoint administrators to script deployment of our Calculator service application in a server farm.

In this article, we’ll create a custom setting that administrators can use to modify the behavior of our service application.

Specifically, we’ll create a new Precision setting, which is defined as the number of significant digits that are used to represent the result of a calculation.

Create the setting

To do this, we’ll first add the setting to our CalculatorServiceApplication class.

You might think that it would be challenging to create a setting that can be managed from a single location and made available to all servers in a server farm via a distributed multi-tier cache, but that’s actually the easiest part thanks to the SharePoint configuration object model:

  1. internal sealed class CalculatorServiceApplication : SPIisWebServiceApplication
  2. {
  3.     [Persisted]
  4.     private int precision;
  5.  
  6.     public int Precision
  7.     {
  8.         get
  9.         {
  10.             return this.precision;
  11.         }
  12.  
  13.         set
  14.         {
  15.             if ((value < 1) || (value > 20))
  16.             {
  17.                 throw new ArgumentOutOfRangeException("value");
  18.             }
  19.  
  20.             this.precision = value;
  21.         }
  22.     }
  23. }

The precision field (line 4) represents the current precision setting for the service application, and the Precision property (lines 6-22) implement a public property to get and set the field value.

The key to integrating with the SharePoint configuration object model is the [Persisted] attribute (line 3). This attribute instructs SharePoint to persist the field value in the SharePoint configuration database when the Update method is called, and to deserialize it when the class is read from the configuration database.

That’s all it takes for the field value to be available on all machines in the server farm and automatically cached on demand for runtime access!

NOTE: The Service Application Framework does not require service application settings to be stored in the SharePoint configuration database using the [Persisted] attribute described above. For example, if a service has an existing mechanism for storing settings, then that would be fine to use instead. However, you may find this persistence mechanism convenient in many cases.

Use the setting

Next, we’ll read this value at runtime and apply it to the result of our Add method:

  1. internal sealed class CalculatorServiceContract : ICalculatorServiceContract
  2. {
  3.     public int Add(int a, int b)
  4.     {
  5.         return RoundToPrecision(a + b);
  6.     }
  7.  
  8.     private CalculatorServiceApplication ServiceApplication
  9.     {
  10.         get
  11.         {
  12.             // Lookup executing service application in config db cache
  13.             return (CalculatorServiceApplication)SPIisWebServiceApplication.Current;
  14.         }
  15.     }
  16.  
  17.     private int RoundToPrecision(int value)
  18.     {
  19.         // Get the current precision setting from the service application configuration
  20.         int precision = this.ServiceApplication.Precision;
  21.  
  22.         // Quick-and-dirty round to specified precision
  23.         return int.Parse(value.ToString("G" + precision.ToString()), System.Globalization.NumberStyles.Any);
  24.     }
  25. }

First, we add a ServiceApplication property to look up and return the executing Calculator service application (lines 8-15).

NOTE: If we had implemented our contract as methods on the CalculatorServiceApplication, this step would be unnecessary, i.e., we could just use “this” to reference the current service application. However, in this example we’re assuming that we’re integrating an existing WCF service contract implementation with SharePoint.

Then, we get the precision setting from our service application using this.ServiceApplication.Precision (line 20) and use it to round our result (line 23).

NOTE: I couldn’t find a nice math function to round a number to an arbitrary precision, so I ended up converting the int to a string formatted to display the given precision and then converting the formatted string back to an int. Not something I’d recommend for production code.

It is important to note that the ServiceApplication lookup (line 13) and the Precision setting (line 2) objects are cached in memory by the SharePoint configuration object model and should not be cached again. This is a common implementation mistake and results in stale setting values. The reason is that SharePoint is smart about invalidating the cache and keeping it fresh when administrators make changes to settings, even from other machines in the server farm. If you cache the result of a lookup, the object will become stale and your application won’t see changes made by administrators until your service host process is recycled.

So, simply follow the pattern above and lookup the setting on every access to ensure that you are reading the most recent value.

Manage the setting

Now let’s provide a way for the administrator to configure the setting. To do this, we’ll integrate with the “Manage” ribbon button on the Service Applications management page:

ServiceAppManageButton

First, we’ll create a management ASPX page:

ManageApplication.aspx

  1. <asp:content contentplaceholderid="PlaceHolderMain" runat="server">
  2.     <table border="0" cellspacing="0" cellpadding="0" width="100%" class="ms-propertysheet">
  3.         <wssuc:InputFormSection
  4.             Title="Arithmetic Precision"
  5.             runat="server">
  6.             <Template_Description>
  7.                 <wssawc:EncodedLiteral runat="server" text="Arithmetic precision is the number of significant digits that are used to represent the result of a calculation." EncodeMethod='HtmlEncodeAllowSimpleTextFormatting'/>
  8.             </Template_Description>
  9.             <Template_InputFormControls>
  10.                 <wssuc:InputFormControl runat="server">
  11.                     <Template_LabelText>
  12.                         <wssawc:EncodedLiteral text="Precision:" EncodeMethod="HtmlEncode" runat="server"/>
  13.                     </Template_LabelText>
  14.                     <Template_control>
  15.                         <wssawc:InputFormTextBox id="PrecisionTextBox" name="PrecisionTextBox" title="Precision" MaxLength="2" Width="50" class="ms-input" runat="server" />
  16.                         <wssawc:EncodedLiteral text="digits" EncodeMethod="HtmlEncode" runat="server" />
  17.                         <wssawc:InputFormRangeValidator
  18.                             id="PrecisionValidator"
  19.                             Type="Integer"
  20.                             MinimumValue="1"
  21.                             MaximumValue="20"
  22.                             ControlToValidate="PrecisionTextBox"
  23.                             ErrorMessage="Specify an integer value in the range 1..20"
  24.                             runat="server" />
  25.                     </Template_control>
  26.                 </wssuc:InputFormControl>
  27.             </Template_InputFormControls>
  28.         </wssuc:InputFormSection>
  29.         
  30.         <wssuc:ButtonSection runat="server">
  31.             <Template_Buttons>
  32.                 <asp:Button id="OkButton" OnClick="OkButton_Click" UseSubmitBehavior="false" Text="OK" class="ms-ButtonHeightWidth" runat="server" />
  33.             </Template_Buttons>
  34.         </wssuc:ButtonSection>
  35.     </table>
  36. </asp:content>

NOTE: I removed a bunch of standard page template goo for readability.

Then, the code-behind:

ManageApplication.aspx.cs

  1. [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
  2. [PermissionSet(SecurityAction.InheritanceDemand, Name = "FullTrust")]
  3. public class ManageApplicationPage : GlobalAdminPageBase
  4. {
  5.     protected TextBox PrecisionTextBox;
  6.  
  7.     protected override void OnLoad(EventArgs e)
  8.     {
  9.         base.OnLoad(e);
  10.  
  11.         if (!Page.IsPostBack)
  12.         {
  13.             CalculatorServiceApplication serviceApplication = this.ServiceApplication;
  14.             if (null == serviceApplication)
  15.             {
  16.                 throw new InvalidOperationException("Service application not found.");
  17.             }
  18.  
  19.             // Initialize controls from service application
  20.             this.PrecisionTextBox.Text = serviceApplication.Precision.ToString();
  21.         }
  22.     }
  23.  
  24.     private CalculatorServiceApplication ServiceApplication
  25.     {
  26.         get
  27.         {
  28.             // Lookup service application by querystring parameter
  29.             Guid serviceApplicationGuid = new Guid(HttpContext.Current.Request.QueryString["id"]);
  30.             return SPFarm.Local.GetObject(serviceApplicationGuid) as CalculatorServiceApplication;
  31.         }
  32.     }
  33.  
  34.     protected void OkButton_Click(object sender, EventArgs e)
  35.     {
  36.         if (Page.IsValid)
  37.         {
  38.             // Update service application settings
  39.             CalculatorServiceApplication serviceApplication = this.ServiceApplication;
  40.             serviceApplication.Precision = Int32.Parse(PrecisionTextBox.Text);
  41.             serviceApplication.Update();
  42.  
  43.             // Navigate back to the service application management page
  44.             RedirectOnOK();
  45.         }
  46.     }
  47.  
  48.     public override string PageToRedirectOnOK
  49.     {
  50.         get { return "/_admin/ServiceApplications.aspx"; }
  51.     }
  52.  
  53.     public override string PageToRedirectOnCancel
  54.     {
  55.         get { return "/_admin/ServiceApplications.aspx"; }
  56.     }
  57. }

The interesting bit of code here is the ServiceApplication property (lines 24-32). Here we’re assuming that the URL used to navigate to the aspx page will include a querystring parameter named “id” with a value that matches the Guid identifier of the service application to be managed. This is necessary because, if you remember our discussion on service application topologies, there may be more than one of our Calculator service applications in a server farm. We parse the Guid parameter and use it to look up the specified service application using the configuration object model (line 30).

And finally, we’ll hook our new management page up to the ribbon by overriding the ManageLink property of our service application:

  1. internal sealed class CalculatorServiceApplication : SPIisWebServiceApplication
  2. {
  3.     public override SPAdministrationLink ManageLink
  4.     {
  5.         get
  6.         {
  7.             return new SPAdministrationLink("/_admin/sample/calculator/manageapplication.aspx?id=" + this.Id.ToString());
  8.         }
  9.     }
  10. }

Note that we include the “id” querystring parameter in the URL required by our management page (line 7).

That’s it!

We’ve added a configurable setting and a page to manage it:

CalcServiceAppManagePage

Administrators can create multiple service applications and configure each of them with a different setting.

However, we don’t have a way for administrators to script this new setting using PowerShell. We’ll take care of that next time.