Click or drag to resize
OSIsoft, LLC

Event Example

The following simple example shows how to receive events from the AF SDK. In Visual Basic .NET, registering to receive events can be done through the use of the WithEvents statement at the top of the file, then by implementing the specific event handler methods. More flexibility is given in naming the event handlers through the use of the Handles clause of the event handler method definition. In C#, each event must have a new handler created, which is registered and unregistered using the += and -= statements, respectively.

Variable Declarations:

1// Declare Variables
2static System.Timers.Timer refreshTimer = new System.Timers.Timer(10 * 1000); // every 10 seconds
3static AFDatabase myDB = null;
4static int myEventCounter = 0;

Code Body:

 1// Get the Default Database
 2PISystems myPISystems = new PISystems();
 3myDB = myPISystems.DefaultPISystem.Databases.DefaultDatabase;
 4if (myDB == null)
 5    throw new InvalidOperationException("There is no default database.");
 6
 7// Add handlers to object
 8System.Timers.ElapsedEventHandler elapsedEH = new System.Timers.ElapsedEventHandler(OnElapsed);
 9refreshTimer.Elapsed += elapsedEH;
10
11EventHandler<AFChangedEventArgs> changedEH = new EventHandler<AFChangedEventArgs>(OnChanged);
12myDB.Changed += changedEH;
13
14// Start the refresh timer which allows this application to periodically 
15// query for changes made by other applications
16refreshTimer.Start();
17
18// Make a change to a collection which generates a change event
19AFElementTemplates myElementTemplates = myDB.ElementTemplates;
20lock (myDB)
21{
22    if (myDB.ElementTemplates["myElementTemplate"] == null)
23    {
24        Console.WriteLine("Adding an element template");
25        AFElementTemplate myElementTemplate = myElementTemplates.Add("myElementTemplate");
26    }
27    else
28    {
29        Console.WriteLine("Deleting an element template");
30        myDB.ElementTemplates.Remove("myElementTemplate");
31    }
32    myDB.CheckIn();
33}
34
35// Remove handlers from object
36myDB.Changed -= changedEH;
37refreshTimer.Elapsed -= elapsedEH;

Event Handlers:

 1internal static void OnChanged(object sender, AFChangedEventArgs e)
 2{
 3    myEventCounter++;
 4    Console.WriteLine("Object Changed Event Raised");
 5}
 6
 7internal static void OnElapsed(object sender, System.Timers.ElapsedEventArgs e)
 8{
 9    // Refreshing Database will cause any external changes to be seen which will
10    // result in the triggering of the OnChanged event handler
11    lock (myDB)
12    {
13       myDB.Refresh();
14    }
15    refreshTimer.Start();
16}

See Also
Enabling Operational Intelligence