private AFNotificationContactTemplate CreateEmailEndpoint(string notificationContactTemplateName)
        {
            var email = new AFNotificationContactTemplate(AFFixture.PISystem, $"{NotificationsFixture.TestPrefix}_{notificationContactTemplateName}")
            {
                DeliveryChannelPlugIn = EmailPlugIn,
                ConfigString          = $"ToEmail={Settings.PINotificationsRecipientEmailAddress};[email protected];UseGlobalFromEmail=false;UseHtml=false",
            };

            return(email);
        }
        public void WebServiceNotificationContactTemplateTest()
        {
            var notificationContactTemplateName = $"{NotificationsFixture.TestPrefix}_{NotificationsFixture.TestInfix}_{nameof(WebServiceNotificationContactTemplateTest)}";

            AFFixture.RemoveNotificationContactTemplateIfExists(notificationContactTemplateName, Output);

            try
            {
                Output.WriteLine($"Create web service notification contact template [{notificationContactTemplateName}].");
                var nct = new AFNotificationContactTemplate(PISystem, notificationContactTemplateName)
                {
                    DeliveryChannelPlugIn = WebServicePlugIn,
                    ConfigString          = "Style=SOAP;WebServiceName=Service;WebServiceMethod=Method;WebServiceUrl=http://localhost:9000",
                    RetryInterval         = TimeSpan.FromSeconds(30),
                    MaximumRetries        = 2,
                };
                nct.CheckIn();

                AFFixture.ReconnectToDB();
                var nctId = nct.ID;
                var nct2  = PISystem.NotificationContactTemplates[nctId];
                Output.WriteLine("Verify the properties of the created web service notification contact template.");
                Assert.True(nct2.DeliveryChannelPlugIn.Name == NotificationsFixture.WebServicePlugInName,
                            "Delivery channel PlugIn is not WebService delivery channel PlugIn.");

                // SOAP style is implicit but authentication option is added automatically by default
                Assert.True(
                    nct2.ConfigString == "AuthenticationOption=Windows;WebServiceMethod=Method;WebServiceName=Service;WebServiceURL=http://localhost:9000",
                    "Delivery channel configuration string is not set properly.");
                Assert.True(nct2.RetryInterval == TimeSpan.FromSeconds(30), "Retry interval is not set properly.");
                Assert.True(nct2.MaximumRetries == 2, "Maximum retries is not set properly.");

                Output.WriteLine("Verify the web service notification contact template is added, configured and retrieved.");
                using (var contactTemplateEmailSearch = new AFNotificationContactTemplateSearch(PISystem, nameof(WebServiceNotificationContactTemplateTest), string.Empty))
                {
                    var rules = contactTemplateEmailSearch.FindObjects().Select(nr => nr.ID).ToArray();
                    Assert.True(rules.Contains(nctId), $"The created notification contact template [{notificationContactTemplateName}] is not found.");
                }
            }
            finally
            {
                AFFixture.RemoveNotificationContactTemplateIfExists(notificationContactTemplateName, Output);
            }
        }
        internal void InitializeWebService(AFFixture afFixture, ITestOutputHelper output)
        {
            if (AFFixture != null)
            {
                return;
            }

            // Initialize a web service notification contact template
            AFFixture          = afFixture;
            Service            = new TestWebService();
            SoapWebServiceHost = new BasicWebServiceHost(Service, typeof(IWebService));

            try
            {
                SoapWebServiceHost.Start(ServiceName, ServiceUri);
            }
            catch (AddressAccessDeniedException)
            {
                SoapWebServiceHost = null;
                Service            = null;

                output.WriteLine($"Warning: The Web Service endpoint [{ServiceUri}] could not be opened.");
                output.WriteLine("There are two ways how to fix the problem:");
                output.WriteLine("1. Use netsh add urlacl to add the current user for the service prefix http://+:9001/notificationtest");
                output.WriteLine("2. Run tests as administrator.");

                return;
            }

            var webServiceSoap = new AFNotificationContactTemplate(afFixture.PISystem, $"{TestPrefix}_{TestInfix}_WebServiceSoap*")
            {
                DeliveryChannelPlugIn = afFixture.PISystem.DeliveryChannelPlugIns[WebServicePlugInName],
                ConfigString          = $"Style=SOAP;WebServiceName={ServiceName};WebServiceMethod={nameof(IWebService.Test)};WebServiceUrl={ServiceUri}",
            };

            _soapWebServiceId = webServiceSoap.ID;
            _notificationContactTemplateIds.Add(webServiceSoap.ID);

            AFFixture.PISystem.CheckIn();
            output.WriteLine($"Created web service notification contact template [{webServiceSoap.Name}].");
        }
        public void EmailNotificationContactTemplateTest()
        {
            var notificationContactTemplateName = $"{NotificationsFixture.TestPrefix}_{NotificationsFixture.TestInfix}_{nameof(EmailNotificationContactTemplateTest)}";
            var contactConfigString             = "[email protected]";

            AFFixture.RemoveNotificationContactTemplateIfExists(notificationContactTemplateName, Output);

            try
            {
                Output.WriteLine($"Create email notification contact template [{notificationContactTemplateName}].");
                var nct = new AFNotificationContactTemplate(PISystem, notificationContactTemplateName)
                {
                    DeliveryChannelPlugIn = EmailPlugIn,
                    ConfigString          = contactConfigString,
                    RetryInterval         = TimeSpan.FromSeconds(45),
                    MaximumRetries        = 3,
                };
                nct.CheckIn();

                AFFixture.ReconnectToDB();
                var id   = nct.ID;
                var nct2 = PISystem.NotificationContactTemplates[id];
                Output.WriteLine("Verify the properties of the created notification contact template.");
                Assert.True(nct2.DeliveryChannelPlugIn.Name == NotificationsFixture.EmailPlugInName,
                            "Delivery channel PlugIn is not Email delivery channel PlugIn.");
                Assert.True(nct2.ConfigString == contactConfigString, "Delivery channel configuration string is not set properly.");
                Assert.True(nct2.RetryInterval == TimeSpan.FromSeconds(45), "Retry interval is not set properly.");
                Assert.True(nct2.MaximumRetries == 3, "Maximum retries is not set properly.");

                Output.WriteLine("Verify the notification contact template is added and retrieved.");
                using (var contactTemplateEmailSearch = new AFNotificationContactTemplateSearch(PISystem, nameof(EmailNotificationContactTemplateTest), string.Empty))
                {
                    var rules = contactTemplateEmailSearch.FindObjects().Select(nr => nr.ID).ToArray();
                    Assert.True(rules.Contains(id), $"The created notification contact template [{notificationContactTemplateName}] is not found.");
                }
            }
            finally
            {
                AFFixture.RemoveNotificationContactTemplateIfExists(notificationContactTemplateName, Output);
            }
        }
        internal void InitializeWebService(AFFixture afFixture, ITestOutputHelper output)
        {
            if (AFFixture != null)
            {
                return;
            }

            // Initialize a web service notification contact template
            AFFixture          = afFixture;
            Service            = new TestWebService();
            SoapWebServiceHost = new BasicWebServiceHost(Service, typeof(IWebService))
            {
                UseExactMatchForLocalhost = false,
            };

            try
            {
                SoapWebServiceHost.Start(ServiceName, ServiceUri);
            }
            catch (AddressAccessDeniedException ex)
            {
                throw new Exception(
                          $"Endpoint [{ServiceUri}] could not be opened. There are 3 possible solutions: " +
                          "1) If notifications service and the tests are run on the same machine, set UseExactMatchForLocalhost=true; " +
                          "2) Use netsh add urlacl to add the current user for the service prefix http://+:9001/notificationtest; " +
                          "3) Run tests as administrator.", ex);
            }

            var webServiceSoap = new AFNotificationContactTemplate(afFixture.PISystem, $"{TestPrefix}_{TestInfix}_WebServiceSoap*")
            {
                DeliveryChannelPlugIn = afFixture.PISystem.DeliveryChannelPlugIns[WebServicePlugInName],
                ConfigString          = $"Style=SOAP;WebServiceName={ServiceName};WebServiceMethod={nameof(IWebService.Test)};WebServiceUrl={ServiceUri}",
            };

            _soapWebServiceId = webServiceSoap.ID;
            _notificationContactTemplatIds.Add(webServiceSoap.ID);

            AFFixture.PISystem.CheckIn();
            output.WriteLine($"Created web service notification contact template [{webServiceSoap.Name}].");
        }
 internal AFNotificationContactTemplate GetSoapWebServiceEndpoint()
 => AFNotificationContactTemplate.FindNotificationContactTemplate(AFFixture.PISystem, _soapWebServiceId);
        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();
            }
        }