This is the last part of a series on programming policy-based management. The series starts here.
In the previous installment, I created a policy that was constrained to a single database. To accomplish this, I used a Condition that called out the database by name, and tied it to the TargetSet using TargetSet's SetLevelCondition method.
An alternative consists of creating a policy as part of a PolicyCategory. Each Policy is a member of exactly one PolicyCategory. The default PolicyCategory is the only one that "ships with the system", but you can define your own. If you don't specify otherwise in the code (SSMS has a Category dropdown on the Description page of the new Category dialog), your policy is a member of the default category.
Each PolicyCategory has a property that indicates whether it's manditory that a database subscribe to that category. If this property is true, each database has an implicit subscription to the category. If not, a database must explicitly subscribe. The code to define a PolicyCategory is straightforward:
static void CreateCategory(PolicyStore ps)
PolicyCategory cat = new PolicyCategory(ps, "MyNewCategory");
cat.MandateDatabaseSubscriptions = false;
To create a Policy that's a member of the PolicyCategory, simply use the aptly-named PolicyCategory property. If you're using a named PolicyCategory you may not want to restrict that policy to a specific database. Here's the changes to the Policy definition.
// No Condition On This One, applies to all databases, but must be subscribed to
// Name the category
p2.PolicyCategory = "MyNewCategory";
To create a PolicyCategorySubscription (for those categories that are not Manditory), the only interesting part is that you need a SqlSmoObject. You can use a concrete subclass (like Database) or make up a SqlSmoObject by using a URN. Dan Sullivan's and my book "Developer's Guide to SQL Server 2005" covers both ways to make an SqlSmoObject. Here's the code for PolicyCategorySubscription.
static void CreatePolicyCategorySubscription(PolicyStore ps)
Server svr = new Server(); // open a connection to default instance, local server
Database db = new Database(svr, "pubs");
PolicyCategorySubscription subs = new PolicyCategorySubscription(ps, db);
subs.PolicyCategory = "MyNewCategory";
This means that only the pubs database now follows the policies in "MyNewCategory". BTW, there's currently the PowerShell provider in CTP6 throws an error when attempting list a PolicyCategorySubscription (its in the hierarchy at the same level as Policy). The PolicyCategorySubscription still works as advertised though.
This concludes the series on Programming Policy-Based Management with SMO. Hope it was useful.