Exemplo n.º 1
0
        private void CreateEventFrame(AFDatabase afDatabase, string name, string startTime = null, string endTime = null, string template = null)
        {
            // look to get the template, if template=null then aftemplate will be null as well
            var afTemplate = GetEventFrameTemplate(afDatabase, template);

            var eventFrame = new AFEventFrame(afDatabase, name, afTemplate);

            if (!string.IsNullOrEmpty(startTime))
            {
                eventFrame.SetStartTime(startTime);
            }
            if (!string.IsNullOrEmpty(endTime))
            {
                eventFrame.SetEndTime(endTime);
            }

            // when using a template, you'll want to assign a primary element to the event frame:
            // here is an example:
            eventFrame.PrimaryReferencedElement = null;
            eventFrame.Description = "";


            // for demonstration purpose, we add some attributes to the event frame created, only if there was no template passed.
            if (afTemplate == null)
            {
                AddAttributes(afDatabase, eventFrame);
            }

            // the checkin writes the event frame to the database
            eventFrame.CheckIn();

            Logger.InfoFormat("EventFrameCreated: name: {0} GUID: {1}", eventFrame.Name, eventFrame.ID);
        }
        static void CreateEventFrames(AFDatabase database, AFElementTemplate eventFrameTemplate)
        {
            string queryString = "Template:MeterBasic";

            {
                // This method returns the collection of AFBaseElement objects that were created with this template.
                using (AFElementSearch elementQuery = new AFElementSearch(database, "Meters", queryString))
                {
                    DateTime timeReference = DateTime.Today.AddDays(-7);
                    int      count         = 0;
                    foreach (AFElement meter in elementQuery.FindElements())
                    {
                        foreach (int day in Enumerable.Range(1, 7))
                        {
                            AFTime       startTime = new AFTime(timeReference.AddDays(day - 1));
                            AFTime       endTime   = new AFTime(startTime.LocalTime.AddDays(1));
                            AFEventFrame ef        = new AFEventFrame(database, "*", eventFrameTemplate);
                            ef.SetStartTime(startTime);
                            ef.SetEndTime(endTime);
                            ef.PrimaryReferencedElement = meter;
                            // It is good practice to periodically check in the database
                            if (++count % 500 == 0)
                            {
                                database.CheckIn();
                            }
                        }
                    }
                }
            }
            if (database.IsDirty)
            {
                database.CheckIn();
            }
        }
        public void NotificationRuleResendWebServiceTest()
        {
            AFDatabase db                   = AFFixture.AFDatabase;
            var        elementName          = $"{NotificationsFixture.TestPrefix}_{NotificationsFixture.TestInfix}_{nameof(NotificationRuleResendWebServiceTest)}";
            var        notificationRuleName = $"{NotificationsFixture.TestPrefix}_{NotificationsFixture.TestInfix}_NotificationRule1";
            var        eventFrameName       = $"{NotificationsFixture.TestPrefix}_{NotificationsFixture.TestInfix}_EventFrame1";
            var        resendInterval       = TimeSpan.FromMinutes(1);

            AFFixture.RemoveElementIfExists(elementName, Output);
            Guid?eventFrameId = null;

            try
            {
                Output.WriteLine($"Create element [{elementName}] with notification rule [{notificationRuleName}].");
                var element          = db.Elements.Add(elementName);
                var notificationRule = element.NotificationRules.Add(notificationRuleName);
                notificationRule.Criteria       = $"Name:{NotificationsFixture.TestPrefix}*";
                notificationRule.ResendInterval = resendInterval;
                var format = notificationRule.DeliveryFormats.Add("testFormat", WebServicePlugIn);
                NotificationsFixture.SetFormatProperties(format.Properties, nameof(NotificationRuleResendWebServiceTest));

                var webServiceEndpoint = NotificationsFixture.GetSoapWebServiceEndpoint();
                var subscriber         = notificationRule.Subscribers.Add(webServiceEndpoint);
                subscriber.DeliveryFormat = format;
                notificationRule.SetStatus(AFStatus.Enabled);
                db.CheckIn();

                Output.WriteLine("Waiting for notification to startup.");
                Thread.Sleep(TimeSpan.FromSeconds(10));

                var eventFrame = new AFEventFrame(db, eventFrameName)
                {
                    PrimaryReferencedElement = element,
                };

                Output.WriteLine($"Create event frame [{eventFrameName}].");
                eventFrame.SetStartTime(AFTime.Now);
                eventFrame.CheckIn();
                eventFrameId = eventFrame.ID;

                var msg = NotificationsFixture.Service.WaitForMessage(resendInterval);
                Assert.True(notificationRule.ID == msg.NotificationRuleId, "Notification rule is not set properly.");
                Assert.True(msg.Content == nameof(NotificationRuleResendWebServiceTest), "The message content is not set properly.");

                // Waiting for resend
                Output.WriteLine("Verify notification is resent.");
                Thread.Sleep(resendInterval);
                msg = NotificationsFixture.Service.WaitForMessage(resendInterval);
                Assert.True(notificationRule.ID == msg.NotificationRuleId, "Notification rule is not set properly.");
                Assert.True(msg.Content == nameof(NotificationRuleResendWebServiceTest), "The message content is not set properly.");
            }
            finally
            {
                AFFixture.RemoveElementIfExists(elementName, Output);
                if (eventFrameId != null)
                {
                    AFFixture.RemoveEventFrameIfExists(eventFrameId.GetValueOrDefault(), Output);
                }
            }
        }
Exemplo n.º 4
0
        public string CreateEventFrame()
        {
            if (currentDb == null)
            {
                currentDb = InitializeAf();
            }
            string result;
            var    eventFrame = new EventFrame();

            if (currentDb != null)
            {
                AFEventFrame myEventFrame = new AFEventFrame(currentDb, "RandomEventFrame*");
                myEventFrame.SetStartTime("T-1w");
                myEventFrame.SetEndTime(AFTime.Now);
                myEventFrame.Template = currentDb.ElementTemplates["Сообщение"];
                AFValue myValue = new AFValue {
                    Value = "Test"
                };
                myEventFrame.Attributes["Текст сообщения"].SetValue(myValue);
                myEventFrame.Description = "This is my EventFrame";
                myEventFrame.CheckIn();

                eventFrame.Id       = myEventFrame.ID.ToString();
                eventFrame.Name     = myEventFrame.Name;
                eventFrame.DateTime = myEventFrame.EndTime.ToString();
                var serializer = new JavaScriptSerializer();
                result = serializer.Serialize(eventFrame);
            }
            else
            {
                result = "disconnect";
            }

            return(result);
        }
Exemplo n.º 5
0
        public void WriteQuery(Query q)
        {
            AFEventFrame ef = new AFEventFrame(db, $"{eftemplate.Name}_{q.StartTime.ToShortDateString()}", eftemplate);

            ef.SetStartTime(q.StartTime);
            ef.SetEndTime(q.EndTime);
            ef.Attributes["ID"].SetValue(new AFValue(q.id));

            db.CheckIn();
        }
        /// <summary>
        /// Create an Event Frame when the leaf element shows the target mode
        /// </summary>
        /// <param name="obj"></param>
        private void CreateEFOnTargetMode(AFValue obj)
        {
            var newMode = ((AFEnumerationValue)obj.Value).Name;

            if (String.Equals(newMode, _leafTargetMode, StringComparison.OrdinalIgnoreCase))
            {
                var element = (AFElement)obj.Attribute.Element;

                var time = obj.Timestamp;
                AFEventFrame ef = new AFEventFrame(element.Database, String.Format("{0}_{1}_{2}", element.Name, time.ToString("yyyy_MM_dd_HH_mm"), _leafTargetMode));
                ef.PrimaryReferencedElement = element;
                ef.SetStartTime(time);
                ef.SetEndTime(AFTime.Now);
                ef.CheckIn();
            }
        }
        private void CreateEventFrames(AFDatabase afDatabase)
        {
            AFElementTemplate efTemplate = afDatabase.ElementTemplates["BasicEventFrameTemplate"];
            for (int i = 0; i < 5; i++)
            {
                AFEventFrame ef = new AFEventFrame(afDatabase, "EF_" + i, efTemplate);
                ef.SetStartTime(new AFTime(string.Format("t-{0}d", i + 1)));
                ef.SetEndTime(new AFTime(string.Format("t-{0}d", i)));

                AFElement element = afDatabase.Elements["Region_0"].Elements["BoilerA"];
                ef.PrimaryReferencedElement = element;
            }

            // Do a bulk check in of all changes made so far.
            afDatabase.CheckIn();
        }
Exemplo n.º 8
0
        private void CreateEventFrames(AFDatabase afDatabase)
        {
            AFElementTemplate efTemplate = afDatabase.ElementTemplates["BasicEventFrameTemplate"];

            for (int i = 0; i < 5; i++)
            {
                AFEventFrame ef = new AFEventFrame(afDatabase, "EF_" + i, efTemplate);
                ef.SetStartTime(new AFTime(string.Format("t-{0}d", i + 1)));
                ef.SetEndTime(new AFTime(string.Format("t-{0}d", i)));

                AFElement element = afDatabase.Elements["Region_0"].Elements["BoilerA"];
                ef.PrimaryReferencedElement = element;
            }

            // Do a bulk check in of all changes made so far.
            afDatabase.CheckIn();
        }
Exemplo n.º 9
0
        public static void CreateDowntimeEvent(AFDatabase afdb, AFElement relay, string operatorName, string reason)
        {
            //Creating Event Frame

            var downtimeReasons = afdb.EnumerationSets["Downtime Reason Codes"];
            var template        = afdb.ElementTemplates["Downtime"];

            var eventFrame = new AFEventFrame(afdb, "manual creation", template);

            eventFrame.PrimaryReferencedElement = relay;
            eventFrame.SetStartTime(DateTime.Now);
            eventFrame.Attributes["Operator"].SetValue(new AFValue(operatorName));
            eventFrame.Attributes["Reason Code"].SetValue(new AFValue(downtimeReasons[reason]));
            AFNameSubstitution.ResolveName(eventFrame, template.NamingPattern);

            //commit changes
            afdb.CheckIn(AFCheckedOutMode.ObjectsCheckedOutThisSession);
            Console.WriteLine("Eventframe: " + eventFrame.Name);
        }
Exemplo n.º 10
0
        private AFEventFrame CreateEventFrame(AFDatabase db, AFElementTemplate eventFrameTemplate, AFCategory elementCategory)
        {
            AFEventFrame ef = null;

            if (eventFrameTemplate == null)
            {
                AFElement el2       = db.Elements[Constants.AF_ELEMENT_NAME + "2"];
                AFElement el        = db.Elements[Constants.AF_ELEMENT_NAME];
                AFTime    startTime = new AFTime(DateTime.Now.AddDays(-1));
                ef = new AFEventFrame(db, Constants.AF_EVENT_FRAME_NAME);
                ef.ReferencedElements.Add(el);
                ef.ReferencedElements.Add(el2);
                ef.PrimaryReferencedElement = el;
                ef.SetStartTime(startTime);
                ef.CanBeAcknowledged = true;
                ef.SetEndTime(new AFTime("*"));
                ef.Categories.Add(elementCategory);
                AFEventFrame ef1 = ef.EventFrames.Add(Constants.AF_EVENT_FRAME_NAME + "Child1");
                AFEventFrame ef2 = ef.EventFrames.Add(Constants.AF_EVENT_FRAME_NAME + "Child2");
                ef.Attributes.Add(Constants.AF_ATTRIBUTE_NAME);
                IList <AFAnnotation> annotations = el.GetAnnotations();
                AFAnnotation         ann         = new AFAnnotation(ef);
                ann.Name  = Constants.AF_EVENT_FRAME_ANNOTATION_NAME;
                ann.Value = "Sample value for annotation";
                ann.Save();
            }
            else
            {
                AFElement myTank1   = db.Elements["Tank 1"];
                AFElement myTank2   = db.Elements["Tank 2"];
                AFTime    startTime = new AFTime("*-1d");
                ef = new AFEventFrame(db, "Tank Level 1", eventFrameTemplate);
                ef.ReferencedElements.Add(myTank1);
                ef.ReferencedElements.Add(myTank2);
                ef.PrimaryReferencedElement = myTank1;
                ef.SetStartTime(AFTime.Now);
                ef.CheckIn();
                AFTime endTime = AFTime.Now;
                ef.SetEndTime(endTime);
            }
            return(ef);
        }
        static void CreateEventFrames(AFDatabase database, AFElementTemplate eventFrameTemplate)
        {
            const int pageSize   = 1000;
            int       startIndex = 0;
            int       totalCount;

            do
            {
                AFNamedCollectionList <AFBaseElement> results = database.ElementTemplates["MeterBasic"].FindInstantiatedElements(
                    includeDerived: true,
                    sortField: AFSortField.Name,
                    sortOrder: AFSortOrder.Ascending,
                    startIndex: startIndex,
                    maxCount: pageSize,
                    totalCount: out totalCount
                    );

                IList <AFElement> meters = results.Select(elm => (AFElement)elm).ToList();

                DateTime timereference = DateTime.Now.AddDays(-7);
                //AFTime startTime = new AFTime(new DateTime(timereference.Year, timereference.Month, timereference.Day, 0, 0, 0, DateTimeKind.Local));
                foreach (AFElement meter in meters)
                {
                    foreach (int day in Enumerable.Range(1, 7))
                    {
                        AFTime       startTime = new AFTime(timereference.AddDays(day - 1));
                        AFTime       endTime   = new AFTime(startTime.LocalTime.AddDays(1));
                        AFEventFrame ef        = new AFEventFrame(database, "*", eventFrameTemplate);
                        ef.SetStartTime(startTime);
                        ef.SetEndTime(endTime);
                        ef.PrimaryReferencedElement = meter;
                    }
                }

                database.CheckIn();

                startIndex += pageSize;
            } while (startIndex < totalCount);

            database.CheckIn();
        }
Exemplo n.º 12
0
        public bool CreateEventFrame(string name, AFTime start, AFTime end, AFElement primaryReferencedElement, AFElementTemplate efTemplate)
        {
            try
            {
                AFEventFrame newEF = new AFEventFrame(_db, name, efTemplate);
                newEF.SetStartTime(start);
                newEF.SetEndTime(end);
                newEF.PrimaryReferencedElement = primaryReferencedElement;
                newEF.CheckIn();

                _db.CheckIn(AFCheckedOutMode.ObjectsCheckedOutThisThread);
                _db.Refresh();
              
                return true;
            }
            catch
            {
                return false;
            }

        }
        public void CreateEventFrames()
        {
            const int pageSize = 1000;
            int startIndex = 0;
            int totalCount;
            do
            {
                AFNamedCollectionList<AFBaseElement> results = _database.ElementTemplates["MeterBasic"].FindInstantiatedElements(
                    includeDerived: true,
                    sortField: AFSortField.Name,
                    sortOrder: AFSortOrder.Ascending,
                    startIndex: startIndex,
                    maxCount: pageSize,
                    totalCount: out totalCount
                    );

                IList<AFElement> meters = results.Select(elm => (AFElement)elm).ToList();

                foreach (AFElement meter in meters)
                {
                    foreach (int day in Enumerable.Range(1, 31))
                    {
                        DateTime start = new DateTime(2015, 12, day, 0, 0, 0, DateTimeKind.Local);
                        AFTime startTime = new AFTime(start);
                        AFTime endTime = new AFTime(start.AddDays(1));
                        AFEventFrame ef = new AFEventFrame(_database, "*", _eventFrameTemplate);
                        ef.SetStartTime(startTime);
                        ef.SetEndTime(endTime);
                        ef.PrimaryReferencedElement = meter;
                    }
                }

                _database.CheckIn();

                startIndex += pageSize;
            } while (startIndex < totalCount);
        }
        static void CreateEventFrames(AFDatabase database, AFElementTemplate eventFrameTemplate)
        {
            const int pageSize = 1000;
            int startIndex = 0;
            int totalCount;
            do
            {
                AFNamedCollectionList<AFBaseElement> results = database.ElementTemplates["MeterBasic"].FindInstantiatedElements(
                    includeDerived: true,
                    sortField: AFSortField.Name,
                    sortOrder: AFSortOrder.Ascending,
                    startIndex: startIndex,
                    maxCount: pageSize,
                    totalCount: out totalCount
                    );

                IList<AFElement> meters = results.Select(elm => (AFElement)elm).ToList();

                DateTime timereference = DateTime.Now.AddDays(-7);
                //AFTime startTime = new AFTime(new DateTime(timereference.Year, timereference.Month, timereference.Day, 0, 0, 0, DateTimeKind.Local));
                foreach (AFElement meter in meters)
                {
                    foreach (int day in Enumerable.Range(1, 7))
                    {
                        AFTime startTime = new AFTime(timereference.AddDays(day - 1));
                        AFTime endTime = new AFTime(startTime.LocalTime.AddDays(1));
                        AFEventFrame ef = new AFEventFrame(database, "*", eventFrameTemplate);
                        ef.SetStartTime(startTime);
                        ef.SetEndTime(endTime);
                        ef.PrimaryReferencedElement = meter;
                    }
                }

                database.CheckIn();

                startIndex += pageSize;
            } while (startIndex < totalCount);

            database.CheckIn();
        }
Exemplo n.º 15
0
        private void CreateEventFrame(AFDatabase afDatabase, string name, string startTime = null, string endTime = null, string template = null)
        {
            // look to get the template, if template=null then aftemplate will be null as well
            var afTemplate = GetEventFrameTemplate(afDatabase, template);

            var eventFrame = new AFEventFrame(afDatabase, name, afTemplate);
            if (!string.IsNullOrEmpty(startTime)) eventFrame.SetStartTime(startTime);
            if (!string.IsNullOrEmpty(endTime)) eventFrame.SetEndTime(endTime);

            // when using a template, you'll want to assign a primary element to the event frame:
            // here is an example:
            eventFrame.PrimaryReferencedElement = null;
            eventFrame.Description = "";

            // for demonstration purpose, we add some attributes to the event frame created, only if there was no template passed.
            if (afTemplate == null)
                AddAttributes(afDatabase, eventFrame);

            // the checkin writes the event frame to the database
            eventFrame.CheckIn();

            Logger.InfoFormat("EventFrameCreated: name: {0} GUID: {1}", eventFrame.Name, eventFrame.ID);
        }
        public void NotificationRuleSendWebServiceEventFrameNotifyOptionTest(AFNotifyOption afNotifyOption, bool eventFrameStartSent, bool eventFrameEndSent)
        {
            Assert.True(NotificationsFixture.SoapWebServiceHost != null, "The Web Service host couldn't be started.");

            AFDatabase db                   = AFFixture.AFDatabase;
            var        elementName          = $"{NotificationsFixture.TestPrefix}_{NotificationsFixture.TestInfix}_{nameof(NotificationRuleSendWebServiceEventFrameNotifyOptionTest)}_{afNotifyOption.ToString()}";
            var        notificationRuleName = $"{NotificationsFixture.TestPrefix}_{NotificationsFixture.TestInfix}_NotificationRule1";
            var        eventFrameName       = $"{NotificationsFixture.TestPrefix}_{NotificationsFixture.TestInfix}_EventFrame1";

            AFFixture.RemoveElementIfExists(elementName, Output);
            Guid?eventFrameId = null;

            try
            {
                Output.WriteLine($"Run test {nameof(NotificationRuleSendWebServiceEventFrameNotifyOptionTest)} with notify option [{afNotifyOption.ToString()}].");
                Output.WriteLine($"Create element [{elementName}] with notification rule [{notificationRuleName}].");
                var element          = db.Elements.Add(elementName);
                var notificationRule = element.NotificationRules.Add(notificationRuleName);
                notificationRule.Criteria = $"Name:{NotificationsFixture.TestPrefix}*";
                notificationRule.NonrepetitionInterval = TimeSpan.FromMinutes(1);
                var format = notificationRule.DeliveryFormats.Add("testFormat", WebServicePlugIn);
                NotificationsFixture.SetFormatProperties(format.Properties, nameof(NotificationRuleSendWebServiceEventFrameNotifyOptionTest));

                var webServiceEndpoint = NotificationsFixture.GetSoapWebServiceEndpoint();
                var subscriber         = notificationRule.Subscribers.Add(webServiceEndpoint);
                subscriber.DeliveryFormat = format;
                subscriber.NotifyOption   = afNotifyOption;
                notificationRule.SetStatus(AFStatus.Enabled);
                db.CheckIn();

                Output.WriteLine("Waiting for notification to startup.");
                Thread.Sleep(TimeSpan.FromSeconds(10));

                var eventFrame = new AFEventFrame(db, eventFrameName)
                {
                    PrimaryReferencedElement = element,
                };

                Output.WriteLine($"Created event frame [{eventFrameName}].");
                eventFrame.SetStartTime(AFTime.Now);
                eventFrame.CheckIn();
                eventFrameId = eventFrame.ID;

                Output.WriteLine("Event frame start send.");
                Message msg;
                if (eventFrameStartSent)
                {
                    msg = NotificationsFixture.Service.WaitForMessage(TimeSpan.FromMinutes(1));
                    Assert.True(notificationRule.ID == msg.NotificationRuleId, "Notification rule is not set properly.");
                    Assert.True(msg.Content == nameof(NotificationRuleSendWebServiceEventFrameNotifyOptionTest), "The message content is not set properly.");
                }
                else
                {
                    var foundMessage = NotificationsFixture.Service.TryWaitForMessage(TimeSpan.FromMinutes(1), out msg);
                    Assert.False(foundMessage, $"Notification rule should not send any notification, but found message for notification rule Id: [{msg?.NotificationRuleId}].");
                }

                // Waiting for event frame close send
                eventFrame.SetEndTime(AFTime.Now);
                eventFrame.CheckIn();

                if (eventFrameEndSent)
                {
                    msg = NotificationsFixture.Service.WaitForMessage(TimeSpan.FromMinutes(1));
                    Assert.True(notificationRule.ID == msg.NotificationRuleId, "Notification rule is not set properly.");
                    Assert.True(msg.Content == nameof(NotificationRuleSendWebServiceEventFrameNotifyOptionTest), "The message content is not set properly.");
                }
                else
                {
                    var foundMessage = NotificationsFixture.Service.TryWaitForMessage(TimeSpan.FromMinutes(1), out msg);
                    Assert.False(foundMessage, $"Notification rule should not send any notification, but found message for notification rule Id: [{msg?.NotificationRuleId}].");
                }
            }
            finally
            {
                AFFixture.RemoveElementIfExists(elementName, Output);
                if (eventFrameId != null)
                {
                    AFFixture.RemoveEventFrameIfExists(eventFrameId.GetValueOrDefault(), Output);
                }
            }
        }
        public void NotificationRuleSendEmailAnnotationTest()
        {
            AFDatabase db                   = AFFixture.AFDatabase;
            var        elementName          = $"{NotificationsFixture.TestPrefix}_{NotificationsFixture.TestInfix}_{nameof(NotificationRuleSendEmailAnnotationTest)}";
            var        notificationRuleName = $"{NotificationsFixture.TestPrefix}_{NotificationsFixture.TestInfix}_NotificationRule1";
            var        eventFrameName       = $"{NotificationsFixture.TestPrefix}_{NotificationsFixture.TestInfix}_EventFrame1";

            AFFixture.RemoveElementIfExists(elementName, Output);
            Guid?eventFrameId = null;
            AFNotificationContactTemplate emailEndpoint = null;

            try
            {
                emailEndpoint = CreateEmailEndpoint(nameof(NotificationRuleSendEmailAnnotationTest));
                Output.WriteLine($"Create email notification contact template [{emailEndpoint.Name}].");
                PISystem.CheckIn();

                Output.WriteLine($"Create element [{elementName}] with notification rule [{notificationRuleName}]");
                var element          = db.Elements.Add(elementName);
                var notificationRule = element.NotificationRules.Add(notificationRuleName);
                notificationRule.Criteria = $"Name:{NotificationsFixture.TestPrefix}*";
                var format = notificationRule.DeliveryFormats.Add("testFormat", EmailPlugIn);
                NotificationsFixture.SetFormatProperties(format.Properties, nameof(NotificationRuleSendEmailAnnotationTest));

                var subscriber = notificationRule.Subscribers.Add(emailEndpoint);
                subscriber.DeliveryFormat = format;

                notificationRule.SetStatus(AFStatus.Enabled);
                db.CheckIn();

                Output.WriteLine("Waiting for notification to startup.");
                Thread.Sleep(TimeSpan.FromSeconds(10));

                var eventFrame = new AFEventFrame(db, eventFrameName)
                {
                    PrimaryReferencedElement = element,
                };

                eventFrame.SetStartTime(AFTime.Now);
                eventFrame.CheckIn();
                eventFrameId = eventFrame.ID;
                Output.WriteLine($"Created event frame [{eventFrameName}].");

                // Verify annotations are gotten correctly
                var annotations = eventFrame.GetAnnotations();
                if (annotations.Count == 0)
                {
                    AssertEventually.True(
                        () => eventFrame.GetAnnotations().Count != 0,
                        TimeSpan.FromSeconds(60),
                        TimeSpan.FromSeconds(5),
                        "Did not find any annotations.");
                    annotations = eventFrame.GetAnnotations();
                }

                Output.WriteLine("Verify the notification is sent for the event frame and the annotation is set properly.");
                Assert.True(annotations.Count == 1, $"Expected to get only one annotation, but got {annotations.Count}.");
                Assert.True(annotations[0].Owner.ID == eventFrameId, "The owner of the annotation is not set properly.");
                Assert.True(annotations[0].Name == NotificationsFixture.AnnotationName, "The name of the annotation is not set properly.");
                Assert.False(string.IsNullOrWhiteSpace(annotations[0].Description), "The description of the annotation is not set properly.");
                Assert.True((string)annotations[0].Value == string.Format(CultureInfo.InvariantCulture, NotificationsFixture.SentAnnotation, 1),
                            "The value of the annotation is not set properly.");

                Output.WriteLine("Verify the content of the annotation is set properly.");
                Assert.False(string.IsNullOrWhiteSpace(annotations[0].Description), "The description of the annotation is not set properly.");
                var description = NotificationsFixture.DeserializeAnnotationDescription(annotations[0].Description);
                var subscribers = description.Subscribers;
                Assert.True(description.Notification == notificationRuleName, "The notification rule name is not set properly.");
                Assert.True(subscribers.Count == 1, $"Expected to get only one subscriber, but got {description.Subscribers.Count}.");
                Assert.True(subscribers[0].Name == emailEndpoint.Name, "The name of the subscriber is not set properly.");
                Assert.True(subscribers[0].Configuration == Settings.PINotificationsRecipientEmailAddress, "The email address of the subscriber is not set properly.");
                Assert.True(subscribers[0].Type == "Email", "The type of the subscriber is not set properly.");
            }
            finally
            {
                AFFixture.RemoveElementIfExists(elementName, Output);
                if (eventFrameId != null)
                {
                    AFFixture.RemoveEventFrameIfExists(eventFrameId.GetValueOrDefault(), Output);
                }

                if (emailEndpoint != null)
                {
                    PISystem.NotificationContactTemplates.Remove(emailEndpoint.ID);
                    PISystem.CheckIn();
                }
            }
        }
        public void NotificationRuleSendToEscalationContactTest()
        {
            AFDatabase db                   = AFFixture.AFDatabase;
            var        elementName          = $"{NotificationsFixture.TestPrefix}_{NotificationsFixture.TestInfix}_{nameof(NotificationRuleSendToEscalationContactTest)}";
            var        notificationRuleName = $"{NotificationsFixture.TestPrefix}_{NotificationsFixture.TestInfix}_NotificationRule1";
            var        escalationNotificationContactTemplateName = $"{NotificationsFixture.TestPrefix}_{NotificationsFixture.TestInfix}_Escalation1";
            var        eventFrameName = $"{NotificationsFixture.TestPrefix}_{NotificationsFixture.TestInfix}_EventFrame1";
            var        emailContactsCountInEscalation = 2;
            var        escalationPeriod = TimeSpan.FromSeconds(20);

            AFFixture.RemoveElementIfExists(elementName, Output);
            Guid?eventFrameId   = null;
            var  emailEndpoints = new List <AFNotificationContactTemplate>();
            AFNotificationContactTemplate escalation = null;

            try
            {
                Output.WriteLine($"Created group notification contact template [{escalationNotificationContactTemplateName}]" +
                                 $" with [{emailContactsCountInEscalation}] email notification contact added.");
                escalation = new AFNotificationContactTemplate(PISystem, escalationNotificationContactTemplateName)
                {
                    ContactType       = AFNotificationContactType.Escalation,
                    EscalationTimeout = escalationPeriod,
                };
                escalation.CheckIn();

                for (var i = 0; i < emailContactsCountInEscalation; i++)
                {
                    var emailEndpoint = CreateEmailEndpoint($"{nameof(NotificationRuleSendToEscalationContactTest)}_{i}");
                    escalation.NotificationContactTemplates.Add(emailEndpoint);
                    emailEndpoints.Add(emailEndpoint);
                }

                PISystem.CheckIn();

                Output.WriteLine($"Created element [{elementName}] with notification rule [{notificationRuleName}].");
                var element          = db.Elements.Add(elementName);
                var notificationRule = element.NotificationRules.Add(notificationRuleName);
                notificationRule.Criteria = $"Name:{NotificationsFixture.TestPrefix}*";
                var subscriber = notificationRule.Subscribers.Add(escalation);
                notificationRule.SetStatus(AFStatus.Enabled);
                db.CheckIn();

                Output.WriteLine("Waiting for notification to startup.");
                Thread.Sleep(TimeSpan.FromSeconds(10));

                var eventFrame = new AFEventFrame(db, eventFrameName)
                {
                    PrimaryReferencedElement = element,
                };

                Output.WriteLine($"Create event frame [{eventFrameName}].");
                eventFrame.SetStartTime(AFTime.Now);
                eventFrame.CheckIn();
                eventFrameId = eventFrame.ID;

                Output.WriteLine("Waiting for escalation period.");
                Thread.Sleep(TimeSpan.FromSeconds(30));

                // Verify annotations are gotten correctly
                var annotations = eventFrame.GetAnnotations();
                if (annotations.Count == 0)
                {
                    AssertEventually.True(
                        () => eventFrame.GetAnnotations().Count != 0,
                        TimeSpan.FromSeconds(60),
                        TimeSpan.FromSeconds(5),
                        "Did not find any annotations.");
                    annotations = eventFrame.GetAnnotations();
                }

                Output.WriteLine("Verify the notification is sent for the event frame and the annotation is set properly.");
                Assert.True(annotations.Count == emailContactsCountInEscalation, $"Expected to get [{emailContactsCountInEscalation}] annotations, but got [{annotations.Count}].");
                for (var i = 0; i < emailContactsCountInEscalation; i++)
                {
                    Assert.True(annotations[i].Name == NotificationsFixture.AnnotationName, "The name of the annotation is not set properly.");

                    Assert.False(string.IsNullOrWhiteSpace(annotations[i].Description), "The description of the annotation is not set properly.");
                    var description = NotificationsFixture.DeserializeAnnotationDescription(annotations[i].Description);
                    var subscribers = description.Subscribers;
                    Assert.True(description.Notification == notificationRuleName, "The notification rule name is not set properly.");
                    Assert.True(subscribers.Count == 1, $"Expected to get only one subscriber, but got {description.Subscribers.Count}.");
                    Assert.True(subscribers[0].Name == emailEndpoints[i].Name, $"The name of the [{i}] subscriber is not set properly.");
                    Assert.True(subscribers[0].Configuration == Settings.PINotificationsRecipientEmailAddress, $"The configuration of the [{i}] subscriber is not displayed in the annotation.");
                    Assert.True(subscribers[0].Type == "Email", $"The type of the [{i}] subscriber is not set properly.");

                    if (i == 0)
                    {
                        Assert.True((string)annotations[i].Value == string.Format(CultureInfo.InvariantCulture, NotificationsFixture.SentAnnotation, 1),
                                    "The value of the annotation is not set properly.");
                    }
                    else
                    {
                        Assert.True((string)annotations[i].Value == string.Format(CultureInfo.InvariantCulture, NotificationsFixture.EscalatedAnnotation, 1),
                                    "The value of the annotation is not set properly.");
                    }
                }

                for (var i = emailContactsCountInEscalation - 1; i > 0; i--)
                {
                    Assert.True(annotations[i].CreationDate - annotations[i - 1].CreationDate >= escalationPeriod, $"The escalation period is not performed properly.");
                }
            }
            finally
            {
                AFFixture.RemoveElementIfExists(elementName, Output);
                if (eventFrameId != null)
                {
                    AFFixture.RemoveEventFrameIfExists(eventFrameId.GetValueOrDefault(), Output);
                }

                if (escalation != null)
                {
                    PISystem.NotificationContactTemplates.Remove(escalation.ID);
                }

                foreach (var emailEndpoint in emailEndpoints)
                {
                    PISystem.NotificationContactTemplates.Remove(emailEndpoint.ID);
                }

                PISystem.CheckIn();
            }
        }
        public void NotificationRuleResendWebServiceStopsOnAcknowledgmentTest()
        {
            Assert.True(NotificationsFixture.SoapWebServiceHost != null, "The Web Service host couldn't be started.");

            AFDatabase db                     = AFFixture.AFDatabase;
            var        elementName            = $"{NotificationsFixture.TestPrefix}_{NotificationsFixture.TestInfix}_{nameof(NotificationRuleResendWebServiceStopsOnAcknowledgmentTest)}";
            var        eventFrameTemplateName = $"{NotificationsFixture.TestPrefix}_{NotificationsFixture.TestInfix}_EventFrameTemplate1";
            var        notificationRuleName   = $"{NotificationsFixture.TestPrefix}_{NotificationsFixture.TestInfix}_NotificationRule1";
            var        eventFrameName         = $"{NotificationsFixture.TestPrefix}_{NotificationsFixture.TestInfix}_EventFrame1";

            AFFixture.RemoveElementIfExists(elementName, Output);
            AFFixture.RemoveElementTemplateIfExists(eventFrameTemplateName, Output);
            Guid?eventFrameId = null;

            try
            {
                Output.WriteLine($"Create event frame template [{eventFrameTemplateName}] and element [{elementName}] with notification rule [{notificationRuleName}].");
                var efTemplate = db.ElementTemplates.Add(eventFrameTemplateName);
                efTemplate.InstanceType      = typeof(AFEventFrame);
                efTemplate.CanBeAcknowledged = true;

                var element          = db.Elements.Add(elementName);
                var notificationRule = element.NotificationRules.Add(notificationRuleName);
                notificationRule.Criteria       = $"Template:{eventFrameTemplateName}";
                notificationRule.ResendInterval = TimeSpan.FromSeconds(30);
                var format = notificationRule.DeliveryFormats.Add("testFormat", WebServicePlugIn);
                NotificationsFixture.SetFormatProperties(format.Properties, nameof(NotificationRuleResendWebServiceStopsOnAcknowledgmentTest));

                var webServiceEndpoint = NotificationsFixture.GetSoapWebServiceEndpoint();
                var subscriber         = notificationRule.Subscribers.Add(webServiceEndpoint);
                subscriber.DeliveryFormat = format;
                subscriber.NotifyOption   = AFNotifyOption.EventStartAndEnd;
                notificationRule.SetStatus(AFStatus.Enabled);
                db.CheckIn();

                Output.WriteLine("Waiting for notification to startup.");
                Thread.Sleep(TimeSpan.FromSeconds(10));

                var eventFrame = new AFEventFrame(db, eventFrameName, efTemplate)
                {
                    PrimaryReferencedElement = element,
                };

                Output.WriteLine($"Create event frame [{eventFrameName}].");
                eventFrame.SetStartTime(AFTime.Now);
                eventFrame.CheckIn();
                eventFrameId = eventFrame.ID;

                Output.WriteLine("Event frame start send.");
                var msg = NotificationsFixture.Service.WaitForMessage(TimeSpan.FromMinutes(1));
                Assert.True(notificationRule.ID == msg.NotificationRuleId, "Notification rule is not set properly.");
                Assert.True(msg.Content == nameof(NotificationRuleResendWebServiceStopsOnAcknowledgmentTest), "The message content is not set properly.");

                Output.WriteLine($"Acknowledge the event frame with the Id: {eventFrameId}");
                eventFrame.Acknowledge();
                eventFrame.CheckIn();

                var foundMessage = NotificationsFixture.Service.TryWaitForMessage(TimeSpan.FromMinutes(1), out msg);
                Assert.False(foundMessage, $"Notification rule should not resend if acknowledged, but found message for notification rule with the Id: [{msg?.NotificationRuleId}].");
            }
            finally
            {
                AFFixture.RemoveElementTemplateIfExists(eventFrameTemplateName, Output);
                AFFixture.RemoveElementIfExists(elementName, Output);
                if (eventFrameId != null)
                {
                    AFFixture.RemoveEventFrameIfExists(eventFrameId.GetValueOrDefault(), Output);
                }
            }
        }