Compartir a través de


How to: Create Custom Rules

You can create rules that are called when events occur. By default, the base rules are used. However, you can use a custom rule that is derived from a base rule. The base rules are as follows:

To create a rule

  1. In Solution Explorer, right-click the project, point to Add, click New Item, and then click Class.

  2. Name the class, and derive it from a base rule.

    The following example creates a derived rule from a base rule:

    public MyAddRule : AddRule

  3. Use the RuleOn attribute to indicate the object type for the rule and when to apply the rule.

    You apply the rule immediately, after the local transaction, or after the top-level transaction.

    Nota

    You can assign the typeof value for the RuleOn attribute to a specific type or to an abstract class (for example, ModelElement).

  4. Add a method for your rule.

    The following example adds a method for your custom rule:

    public override void ElementAdded(ElementAddedEventArgs e)

  5. Write the code for your rule.

    This code will override the action for the base rule.

  6. Save and compile your code.

  7. Notify the framework about your custom type by overriding the GetCustomDomainModelTypes method of the domain model in a new partial class.

    The following example notifies the framework that you are overriding an exsisting method:

    public partial class LibraryModel {  protected override System.Type[] GetCustomDomainModelTypes()  {   return new System.Type[] {    typeof(MyAddRule),    typeof(AnotherRule),  };

    After you compile the project, the rule runs when the conditions that you indicated occur.

Example

The following example increments a counter every time that an element of type Library is added. The rule is applied after the top-level transaction commits the change.

namespace Microsoft.VisualStudio.Modeling
{
    [RuleOn(typeof(Library), FireTime = TimeToFire.TopLevelCommit)]
    public class MyAddRule : AddRule
    {
        private static int counter;

        public override void ElementAdded(ElementAddedEventArgs e)
        {
            counter++;
            // For a console application, you could display this:
            // System.Console.WriteLine(String.Format("Library element added. Total added: {0}",counter));           
        }
    }
}

See Also

Concepts

Comparing Events and Rules