NotificationMessageHolderType CreateMessage(XmlDocument doc, string prefix, string ns, string topic)
        {
            NotificationMessageHolderType notification = new NotificationMessageHolderType();

            XmlElement message = doc.DocumentElement;

            notification.Message                         = message;
            notification.ProducerReference               = new EndpointReferenceType();
            notification.ProducerReference.Address       = new AttributedURIType();
            notification.ProducerReference.Address.Value = HttpContext.Current.Request.Url.AbsoluteUri;
            notification.Topic         = new TopicExpressionType();
            notification.Topic.Dialect = "";

            XmlAttribute propertyOperation = doc.CreateAttribute("PropertyOperation");

            propertyOperation.Value = "Initialized";
            message.Attributes.Append(propertyOperation);


            XmlText text;

            notification.Topic.Xmlns = new System.Xml.Serialization.XmlSerializerNamespaces();
            notification.Topic.Xmlns.Add(prefix, ns);
            text = doc.CreateTextNode(string.Format("{0}:{1}", prefix, topic));

            notification.Topic.Any = new XmlNode[] { text };

            return(notification);
        }
Esempio n. 2
0
 public DeviceEvent(NotificationMessageHolderType notificationMessageHolderType)
 {
     this.Topics  = GetTopics(notificationMessageHolderType);
     this.Sources = GetDataFromMessage(notificationMessageHolderType, sourceSelector);
     this.Data    = GetDataFromMessage(notificationMessageHolderType, dataSelector);
     this.Id      = CalculateId();
 }
Esempio n. 3
0
        void DoNotify1()
        {
            Events.EndpointReferenceType reference = (Events.EndpointReferenceType)Application["consumer"];

            NotificationConsumerProxy.NotificationConsumerClient client = new
                                                                          NotificationConsumerProxy.NotificationConsumerClient(new WSHttpBinding(), new EndpointAddress(reference.Address.Value));

            NotificationConsumerProxy.Notify notify = new NotificationConsumerProxy.Notify();

            XmlDocument doc = new XmlDocument();

            doc.LoadXml("<tt:Message UtcTime=\"2008-10-10T12:24:57.321\" xmlns:tt=\"http://www.onvif.org/ver10/schema\"><tt:Source><tt:SimpleItem Name=\"VideoSourceConfigurationToken\" Value=\"1\"/><tt:SimpleItem Name=\"VideoAnalyticsConfigurationToken\" Value=\"2\"/><tt:SimpleItem Value=\"MyImportantFence1\" Name=\"Rule\"/></tt:Source><tt:Data><tt:SimpleItem Name=\"ObjectId\" Value=\"15\" /></tt:Data></tt:Message>");

            NotificationMessageHolderType notification1 = new NotificationMessageHolderType();

            XmlElement message1 = doc.DocumentElement;

            notification1.Message = message1;

            notification1.ProducerReference               = new EndpointReferenceType();
            notification1.ProducerReference.Address       = new AttributedURIType();
            notification1.ProducerReference.Address.Value = HttpContext.Current.Request.Url.AbsoluteUri;

            notification1.Topic         = new TopicExpressionType();
            notification1.Topic.Dialect = "";

            notify.NotificationMessage = new NotificationMessageHolderType[] { notification1 };

            client.Notify(notify);
        }
        bool ValidateDoorFaultMessage(NotificationMessageHolderType notification,
                                      MessageCheckSettings settings,
                                      StringBuilder logger)
        {
            MessageDescription messageInfo = GetDoorFaultMessageDescription();

            return(ValidateDoorMessage(notification, settings, logger, messageInfo));
        }
 bool ValidateRemovedMessage(TopicInfo topicInfo,
                             string sourceSimpleItem,
                             NotificationMessageHolderType message,
                             XmlElement rawElement,
                             XmlNamespaceManager manager,
                             StringBuilder logger)
 {
     return(ValidateConfigurationMessage(message, rawElement, manager, topicInfo, sourceSimpleItem, logger));
 }
        bool ValidateAccessPointRemovedMessage(NotificationMessageHolderType message,
                                               XmlElement rawElement,
                                               XmlNamespaceManager manager,
                                               StringBuilder logger)
        {
            TopicInfo topicInfo = ConstructTopic(new string[] { "AccessPoint", "Removed" });

            return(ValidateRemovedMessage(topicInfo, ACCESSPOINTTOKENSIMPLEITEM, message, rawElement, manager, logger));
        }
        bool ValidateAreaSetMessage(NotificationMessageHolderType message,
                                    XmlElement rawElement,
                                    XmlNamespaceManager manager,
                                    StringBuilder logger)
        {
            TopicInfo topicInfo = ConstructTopic(new string[] { "Area", "Changed" });

            return(ValidateSetMessage(topicInfo, AREATOKENSIMPLEITEM, message, rawElement, manager, logger));
        }
        void ValidateDoorModeSimpleItem(NotificationMessageHolderType notification, string expectedMode)
        {
            XmlElement dataElement = notification.Message.GetMessageData();

            Dictionary <string, string> dataSimpleItems = dataElement.GetMessageElementSimpleItems();

            Assert(dataSimpleItems["State"] == expectedMode,
                   string.Format("'State' simple item valud is incorrect. Expected: '{0}', actual '{1}'", expectedMode, dataSimpleItems["State"]),
                   "Validate 'State' simple item value");
        }
Esempio n. 9
0
        private static IReadOnlyList <string> GetTopics(NotificationMessageHolderType notificationMessageHolderType)
        {
            var topics = new List <string>();

            foreach (var topic in notificationMessageHolderType.Topic?.Any)
            {
                topics.Add(topic.InnerText);
            }

            return(topics);
        }
        bool ValidateAccessPointTamperingMessage(NotificationMessageHolderType notification,
                                                 MessageCheckSettings settings,
                                                 StringBuilder logger)
        {
            MessageDescription messageInfo = new MessageDescription();

            messageInfo.IsProperty = true;
            messageInfo.AddSimpleItem("State", "boolean", XSNAMESPACE);
            messageInfo.AddSimpleItem("Reason", "string", XSNAMESPACE);

            return(ValidateAccessPointMessage(notification, settings, logger, messageInfo));
        }
        public void Process(NotificationMessageHolderType nm)
        {
            var topic = nm.Topic;

            if (topic != null)
            {
                if (VerifyTopic(topic))
                {
                    Parse(topic, nm.Message);
                }
            }
        }
Esempio n. 12
0
        DateTime GetMessageTime(NotificationMessageHolderType Message)
        {
            string utcTimeValue = Message.Message.Attributes[OnvifMessage.UTCTIMEATTRIBUTE].Value;

            if (EventServiceUtils.IsValidXsdDateTime(utcTimeValue))
            {
                return(DateTime.Parse(utcTimeValue));
            }
            else
            {
                return(DateTime.MaxValue);
            }
        }
Esempio n. 13
0
        bool validateEventTopic(TopicInfo expectedTopicInfo, NotificationMessageHolderType msg, StringBuilder logger)
        {
            var actualTopicInfo = TopicInfo.ExtractTopicInfoAll(msg.Topic.Any.First().InnerText, msg.Topic.Any.First());

            //return expectedTopicInfo.GetPlainInfo().Topic == actualTopicInfo.GetPlainInfo().Topic;
            if (!fillNamespaces(actualTopicInfo, msg, logger))
            {
                return(false);
            }

            //TO DO
            return(TopicInfo.TopicsMatch(actualTopicInfo, expectedTopicInfo));
        }
        bool ValidateConfigurationMessage(NotificationMessageHolderType message,
                                          XmlElement rawElement,
                                          XmlNamespaceManager manager,
                                          TopicInfo topicInfo, string sourceItemName,
                                          StringBuilder logger)
        {
            XmlElement messageElement = message.Message;

            StringBuilder dump = new StringBuilder();
            bool          ok   = true;

            ok = ValidateMessageCommonElements(message, rawElement, topicInfo, null, manager, dump);

            if (messageElement != null)
            {
                // check message source [presence only]
                XmlElement sourceElement = messageElement.GetMessageSource();
                if (sourceElement == null)
                {
                    logger.AppendLine("   Message Source element is missing");
                    ok = false;
                }
                else
                {
                    bool   success = false;
                    string err;
                    Dictionary <string, string> sourceSimpleItems = messageElement.GetMessageSourceSimpleItems(out success, out err);
                    if (success)
                    {
                        if (!sourceSimpleItems.ContainsKey(sourceItemName))
                        {
                            logger.AppendLine(string.Format("   '{0}' SimpleItem is missing in Source", sourceItemName));
                            ok = false;
                        }
                    }
                    else
                    {
                        logger.AppendLine(string.Format("   {0}", err));
                        ok = false;
                    }
                }
            }

            if (!ok)
            {
                logger.Append(dump.ToString());
            }
            return(ok);
        }
Esempio n. 15
0
        public void FireEvent(TopicInformation topicInfo, DateTime messageTime, string propertyOperation, List <SimpleItem> source, List <SimpleItem> data)
        {
            // find topic

            DUT.PACS.Simulator.Events.Topic topic = TopicsConverter.Find(
                DUT.PACS.Simulator.Events.PACSTopicSet.Instance, topicInfo);

            // create NotificationMessage

            NotificationMessageHolderType message = GenerateNotificationMessage(topicInfo, messageTime, propertyOperation, source, data);

            EventServer.TransmitMessage(message, topic);

            EventServer.TimeoutEvent(this, topic, source, data);
        }
Esempio n. 16
0
 bool IsBeginMessage(Dictionary <NotificationMessageHolderType, XmlElement> NotificationMessages)
 {
     try
     {
         NotificationMessageHolderType Message = null;
         foreach (NotificationMessageHolderType l in NotificationMessages.Keys)
         {
             Message = l;
         }
         TopicInfo Topic = TopicInfo.ExtractTopicInfoPACS(Message.Topic.Any[0].InnerText, NotificationMessages[Message]);
         bool      match = TopicInfo.TopicsMatch(Topic, BeginTopic);
         return(match);
     }
     catch (Exception)
     {
         return(false);
     }
 }
        bool CheckDoorEventSource(NotificationMessageHolderType message, string token)
        {
            BeginStep("Check if notification should be considered");

            bool ok = false;

            XmlElement messageElement = message.Message;

            if (messageElement != null)
            {
                bool success;
                string err;
                Dictionary<string, string> sourceSimpleItems = messageElement.GetMessageSourceSimpleItems(out success, out err);
                if (success) // don't check invalid message at all
                {
                    if (sourceSimpleItems.ContainsKey(DOORTOKENSIMPLEITEM))
                    {
                        if (sourceSimpleItems[DOORTOKENSIMPLEITEM] == token)
                        {
                            ok = true;
                        }
                        else
                        {
                            LogStepEvent("Message is for other token, skip this notification");
                        }
                    }
                    else
                    {
                        LogStepEvent(string.Format("Notification cannot be checked: no '{0}' SimpleItem" , DOORMODESIMPLEITEM));
                    }
                }
                else
                {
                    LogStepEvent("Notification cannot be checked: " + err);
                }
            }

            StepPassed();
            return ok;
        }
        bool ValidateAccessPointMessage(NotificationMessageHolderType notification,
                                        MessageCheckSettings settings,
                                        StringBuilder logger,
                                        MessageDescription messageInfo)
        {
            XmlElement          messageElement    = notification.Message;
            XmlElement          messageRawElement = settings.RawMessageElements[notification];
            TopicInfo           topicInfo         = settings.ExpectedTopic;
            XmlNamespaceManager manager           = settings.NamespaceManager;

            // Init
            StringBuilder dump = new StringBuilder();
            bool          ok   = true;

            ok = ValidateMessageCommonElements(
                notification, messageRawElement, topicInfo,
                settings.ExpectedPropertyOperation, manager, dump);

            if (messageElement != null)
            {
                // check message source and data

                // source
                bool localOk = ValidateAccessPointEventSource(messageElement, manager, settings.Data, dump);
                ok = ok && localOk;

                XmlElement messageInnerElement = messageRawElement.GetMessageContentElement();
                XmlElement dataElement         = messageInnerElement.GetMessageData();
                localOk = ValidateMessageDataSimpleItems(dataElement, messageInfo, dump);
                ok      = ok && localOk;
            }

            if (!ok)
            {
                logger.Append(dump.ToString());
            }
            return(ok);
        }
Esempio n. 19
0
        bool fillNamespaces(TopicInfo topicInfo, NotificationMessageHolderType msg, StringBuilder logger)
        {
            try
            {
                while (null != topicInfo)
                {
                    if (!string.IsNullOrEmpty(topicInfo.NamespacePrefix) && string.IsNullOrEmpty(topicInfo.Namespace))
                    {
                        topicInfo.Namespace = msg.Topic.LookupNamespace(topicInfo.NamespacePrefix);
                    }

                    topicInfo = topicInfo.ParentTopic;
                }
            }
            catch (KeyNotFoundException e)
            {
                //throw new Exception(string.Format("The namespace's prefix {0} isn't defined", topicInfo.NamespacePrefix));
                logger.AppendLine(string.Format("The namespace's prefix {0} isn't defined", topicInfo.NamespacePrefix));

                return(true);
            }

            return(true);
        }
Esempio n. 20
0
        void VerifyBeginType(Dictionary <NotificationMessageHolderType, XmlElement> NotificationMessages)
        {
            bool match = false;
            NotificationMessageHolderType Message = null;

            try
            {
                foreach (NotificationMessageHolderType l in NotificationMessages.Keys)
                {
                    Message = l;
                }
                TopicInfo Topic = TopicInfo.ExtractTopicInfoPACS(Message.Topic.Any[0].InnerText, NotificationMessages[Message]);
                match = TopicInfo.TopicsMatch(Topic, BeginTopic);
            }
            catch (Exception)
            {
                Assert(false,
                       "Message topic undefind",
                       "Check if first message is " + BeginPath);
            }
            Assert(match,
                   "Message topic is wrong (topic or namespace)",
                   "Check if first message is " + BeginPath);
        }
Esempio n. 21
0
        private static IReadOnlyDictionary <string, string> GetDataFromMessage(NotificationMessageHolderType notificationMessageHolderType,
                                                                               XPathExpression selector)
        {
            var sources = new Dictionary <string, string>();

            System.Xml.XmlElement message = notificationMessageHolderType.Message;
            if (message != null)
            {
                XPathNavigator    rootNavigator = message.CreateNavigator();
                XPathNodeIterator childNodeIter = rootNavigator.Select(selector);

                if (childNodeIter != null)
                {
                    while (childNodeIter.MoveNext())
                    {
                        var currentNode = childNodeIter.Current;
                        var name        = currentNode.GetAttribute("Name", string.Empty);
                        var value       = currentNode.GetAttribute("Value", string.Empty);
                        sources.Add(name, value);
                    }
                }
            }
            return(sources);
        }
        public void AccessDoorTest()
        {
            EndpointReferenceType subscriptionReference = null;
            System.DateTime subscribeStarted = System.DateTime.MaxValue;

            int timeout = _eventSubscriptionTimeout;

            Utils.NotifyAsyncServer eventServer = null;
            RunTest(
                () =>
                {

                    // 3.	Get complete list of doors from the DUT (see Annex A.1).
                    List<DoorInfo> fullDoorsList = GetDoorInfoList();

                    //4.	ONVIF Client selects one door from the complete list of doors at step 
                    // 3 with DoorInfo.Capabilities.Access equal to true. If there is no such Door, 
                    // skip other steps and go to the next test.
                    List<DoorInfo> doorInfos = fullDoorsList.Where(
                        D => D.Capabilities != null &&
                            D.Capabilities.AccessSpecified &&
                            D.Capabilities.Access).ToList();

                    if (doorInfos.Count == 0)
                    {
                        LogTestEvent("No Doors with required Capabilities found, exit the test.");
                        return;
                    }

                    //5.	Test Operator puts Door in state when AccessDoor command will be accepted 
                    // with state change.
                    // ToDo : discuss with customer if there are better methods to select Door 
                    // which will be convenient for operator
                    List<DoorSelectionData.DoorShortInfo> tokens =
                        doorInfos.Select(
                        D => new DoorSelectionData.DoorShortInfo() { Token = D.token, Name = D.Name }).ToList();
                    string selectedToken = tokens.First().Token;

                    string message ="Put the Door with token '{0}' into state which allows 'Access' operation";

                    Definitions.Data.DoorSelectionData data = new TestTool.Tests.Definitions.Data.DoorSelectionData();
                    data.Doors = tokens;
                    data.SelectedToken = selectedToken;
                    data.MessageTemplate = message;

                    WaitHandle formHandle = _operator.ShowCountdownMessage(_messageTimeout, data);
                    try
                    {
                        Sleep(_messageTimeout, new WaitHandle[] { formHandle });
                    }
                    finally
                    {
                        _operator.HideCountdownMessage();
                    }

                    selectedToken = data.SelectedToken;
                    LogTestEvent(string.Format("Door with token '{0}' will be used for test{1}", selectedToken, Environment.NewLine));

                    TopicInfo topic = ConstructTopic(new string[] { "Door", "State", "DoorMode" });
                    TestTool.Proxies.Event.FilterType filter = CreateSubscriptionFilter(topic);

                    Func<NotificationMessageHolderType, bool> messageCheck = (n) => CheckDoorEventSource(n, selectedToken);

                    // Subscribe
                    eventServer = new TestTool.Tests.TestCases.Utils.NotifyAsyncServer(_nic);

                    //SetupNotifyServer2(eventServer);

                    string notificationsUri = eventServer.GetNotificationUri();

                    BeginStep("Begin listening");
                    eventServer.StartCollecting(_semaphore.StopEvent);
                    StepPassed();

                    //6.	ONVIF Client will invoke SubscribeRequest message with tns1:DoorControl/DoorMode 
                    // Topic as Filter and an InitialTerminationTime of 60s to ensure that the SubscriptionManager 
                    // is deleted after one minute.
                    //7.	Verify that the DUT sends a SubscribeResponse message.
                    subscriptionReference = CreateSubscription(filter, timeout, notificationsUri, out subscribeStarted);

                    LogTestEvent(string.Format("Wait until message for Door with token='{0}' is received", selectedToken)+Environment.NewLine);

                    System.DateTime messageTimeLimit = System.DateTime.Now.AddMilliseconds(_operationDelay);

                    string initialMode = string.Empty;
 
                    //8.	Verify that DUT sends Notify message for selected Door with current state 
                    // (Notifications for other Doors will be ignored for this test case).
                    //9.	Verify received Notify message (correct value for UTC time, TopicExpression and 
                    // wsnt:Message).
                    //10.	Verify that PropertyOperation="Initialized".
                    //11.	Verify that TopicExpression is equal to tns1:DoorControl/DoorMode.
                    //12.	Verify that notification contains Source.SimpleItem item with Name="DoorToken" 
                    // and Value is equal to selected Door Token.
                    //13.	Verify that notification contains Data.SimpleItem item with Name="DoorMode" 
                    // and Value with type is equal to tdc:DoorMode.
                    {
                        System.Diagnostics.Debug.WriteLine("Wait for messages with PropertyOperation=INITIALIZED"); 

                        Dictionary<NotificationMessageHolderType, XmlElement> initialMessages =
                            PeekMessages(eventServer, _messageTimeout,
                            messageTimeLimit, fullDoorsList.Count, messageCheck);
                        
                        Assert(initialMessages.Count > 0,
                            string.Format("Message for the door with token='{0}' has not been received", selectedToken ),
                            "Check that the message for selected door has been received");

                        // validate
                        ValidateMessages(initialMessages, topic, OnvifMessage.INITIALIZED, selectedToken, ValidateDoorModeMessage);

                        NotificationMessageHolderType receivedMessage = initialMessages.Keys.First();

                        XmlElement dataElement = receivedMessage.Message.GetMessageData();

                        Dictionary<string, string> dataSimpleItems = dataElement.GetMessageElementSimpleItems();

                        initialMode = dataSimpleItems["State"];
                    }

                    //14.	ONVIF Client will invoke AccessDoorRequest message (Token = [selected Door token]) 
                    // to change door state.
                    //15.	Verify the AccessDoorResponse message from the DUT.
                    AccessDoor(selectedToken, null, null, null, null, null);

                    messageTimeLimit = System.DateTime.Now.AddSeconds(_operationDelay/1000);

                    LogTestEvent("Wait until message with PropertyOperation=\"Changed\" is received" + Environment.NewLine);

                    //16.	Verify that DUT sends Notify message for selected Door with current state 
                    // (Notifications for other Doors will be ignored for this test case).
                    //17.	Verify received Notify message (correct value for UTC time, TopicExpression and 
                    // wsnt:Message).
                    //18.	Verify that PropertyOperation="Changed".
                    //19.	Verify that TopicExpression is equal to tns1:DoorControl/DoorMode.
                    //20.	Verify that notification contains Source.SimpleItem item with Name="DoorToken" 
                    // and Value is equal to selected Door Token.
                    //21.	Verify that notification contains Data.SimpleItem item with Name="DoorMode" 
                    // and Value equal to “Accessed”.
                    {
                        System.Diagnostics.Debug.WriteLine("Wait for first 'CHANGED' message"); 

                        Dictionary<NotificationMessageHolderType, XmlElement> doorModeChangedMessages =
                            PeekMessages(eventServer, _messageTimeout,
                            messageTimeLimit, 1, messageCheck);

                        Assert(doorModeChangedMessages.Count > 0,
                            string.Format("Message for the door with token='{0}' has not been received", selectedToken),
                            "Check that the message for selected door has been received");

                        // validate

                        ValidateMessages(doorModeChangedMessages, topic, selectedToken, ValidateDoorModeMessage);
                    
                        NotificationMessageHolderType receivedMessage = doorModeChangedMessages.Keys.First();
                        ValidateDoorModeSimpleItem(receivedMessage, DoorMode.Accessed);
                    }

                    LogTestEvent("Wait until message with PropertyOperation=\"Changed\" is received" + Environment.NewLine);

                    //22.	ONVIF Client will wait for next Notification for selected Door.
                    //23.	Verify that DUT sends Notify message for selected Door with current state 
                    // (Notifications for other Doors will be ignored for this test case).
                    //24.	Verify received Notify message (correct value for UTC time, TopicExpression 
                    // and wsnt:Message).
                    //25.	Verify that PropertyOperation="Changed".
                    //26.	Verify that TopicExpression is equal to tns1:DoorControl/DoorMode.
                    //27.	Verify that notification contains Source.SimpleItem item with Name="DoorToken" 
                    // and Value is equal to selected Door Token.
                    //28.	Verify that notification contains Data.SimpleItem item with Name="DoorMode" and 
                    // Value equal to previous state (previous state was received with Notification from step 8).
                    {
                        System.Diagnostics.Debug.WriteLine("Wait for second 'CHANGED' message");

                        messageTimeLimit = System.DateTime.Now.AddSeconds(_messageTimeout / 1000);

                        // ToDo: should we wait for "_operationDelay" ?
                        Dictionary<NotificationMessageHolderType, XmlElement> doorModeChangedMessages =
                            PeekMessages(eventServer, _messageTimeout,
                            messageTimeLimit, 1, messageCheck);

                        Assert(doorModeChangedMessages.Count > 0,
                            string.Format("Message for the door with token='{0}' has not been received", selectedToken),
                            "Check that the message for selected door has been received");

                        // validate
                        ValidateMessages(doorModeChangedMessages, topic, selectedToken, ValidateDoorModeMessage);

                        NotificationMessageHolderType receivedMessage = doorModeChangedMessages.Keys.First();
                        ValidateDoorModeSimpleItem(receivedMessage, initialMode);
                    }

                    eventServer.StopCollecting();
                },
                () =>
                {
                    _operator.HideCountdownMessage();
                    if (eventServer != null)
                    {
                        eventServer.StopCollecting();
                    }
                    ReleaseSubscription(subscribeStarted, subscriptionReference, timeout);
                });
        }
Esempio n. 23
0
        public static void ManejaEventos(string uri)
        {
            try
            {
                ServicePointManager.Expect100Continue = false;
                EndpointAddress             endPointAddress      = new EndpointAddress(uri);
                HttpTransportBindingElement httpTransportBinding = new HttpTransportBindingElement {
                    AuthenticationScheme = AuthenticationSchemes.Digest
                };
                httpTransportBinding.KeepAliveEnabled = true;
                TextMessageEncodingBindingElement textMessageEncodingBinding = new TextMessageEncodingBindingElement {
                    MessageVersion = MessageVersion.CreateVersion(EnvelopeVersion.Soap12, AddressingVersion.WSAddressing10)
                };
                PasswordDigestBehavior passwordDigestBehavior = new PasswordDigestBehavior("julian", "julian");

                CustomBinding customBinding = new CustomBinding(textMessageEncodingBinding, httpTransportBinding);
                customBinding.SendTimeout = new TimeSpan(0, 0, 10);



                EventPortTypeClient ept = new EventPortTypeClient(customBinding, endPointAddress);
                ept.Endpoint.Behaviors.Add(passwordDigestBehavior);
                Console.WriteLine("Status 1 : " + ept.State.ToString());

                ept.Open();
                Console.WriteLine("Status 2 : " + ept.State.ToString());

                ept.GetType();

                ept.GetHashCode();



                FilterType filter       = new FilterType();
                string     initTermTime = null;
                CreatePullPointSubscriptionSubscriptionPolicy policy =
                    new CreatePullPointSubscriptionSubscriptionPolicy();

                XmlElement[]               elems1 = new XmlElement[10];
                System.DateTime            time1  = new System.DateTime();
                Nullable <System.DateTime> time2  = new System.DateTime();

                EndpointReferenceType endpoint = ept.CreatePullPointSubscription(filter, "PT60M", policy, ref elems1, out time1, out time2);


                System.DateTime CurrentTime = new System.DateTime();
                NotificationMessageHolderType[] NotificationMessages = new NotificationMessageHolderType[0];
                PullPointSubscriptionClient.PullMessages()

                PullPointSubscriptionClient.PullMessages("PT5M", 99, Any, out CurrentTime, out NotificationMessages);


                PullPointSubscriptionClient subbind = new PullPointSubscriptionClient(customBinding, endPointAddress);
                subbind.Endpoint.Behaviors.Add(passwordDigestBehavior);



                string          timeOut  = "PT60.000S";
                int             mesLimit = 100;
                XmlElement[]    elemns2  = new XmlElement[10];
                System.DateTime termTime = new System.DateTime();
                NotificationMessageHolderType[] messHolder =
                    new NotificationMessageHolderType[0];



                subbind.PullMessages(timeOut, mesLimit, elemns2, out termTime, out messHolder);

                for (int i = 0; i < messHolder.Length; i++)
                {
                    Console.WriteLine("parsing");
                }


                Console.WriteLine("--------- NO CATCH --------- ");
            }
            catch (Exception eee)
            {
                Console.WriteLine("manejando eventos: " + eee);
            }
        }
Esempio n. 24
0
        /// <summary>
        /// Creates notification message.
        /// </summary>
        /// <param name="topicInfo">Topic information.</param>
        /// <param name="dateTime">Message time.</param>
        /// <param name="sourceItems">Source simple items.</param>
        /// <param name="dataItems">Data simple items.</param>
        /// <returns>Norification message for sending.</returns>
        private NotificationMessageHolderType GenerateNotificationMessage(TopicInformation topicInfo,
                                                                          DateTime dateTime,
                                                                          string propertyOperation,
                                                                          List <SimpleItem> sourceItems,
                                                                          List <SimpleItem> dataItems)
        {
            NotificationMessageHolderType res = new NotificationMessageHolderType();

            NameTable           nt    = new NameTable();
            XmlNamespaceManager nsmgr = new XmlNamespaceManager(nt);

            nsmgr.AddNamespace("xs", "http://www.w3.org/2001/XMLSchema");
            nsmgr.AddNamespace("tt", "http://www.onvif.org/ver10/schema");
            nsmgr.AddNamespace("wsnt", "http://docs.oasis-open.org/wsn/b-2");

            XmlDocument xmlDocument = new XmlDocument(nt);

            res.Topic         = new TopicExpressionType();
            res.Topic.Dialect = "http://www.onvif.org/ver10/tev/topicExpression/ConcreteSet";
            res.Topic.Any     = new XmlNode[1];
            res.Topic.Any[0]  = xmlDocument.CreateTextNode(topicInfo.TopicString);
            res.Topic.Xmlns   = new System.Xml.Serialization.XmlSerializerNamespaces();

            foreach (NamespaceDescription description in topicInfo.Namespaces)
            {
                res.Topic.Xmlns.Add(description.Prefix, description.Namespace);
            }

            //Message
            res.Message = xmlDocument.CreateElement("tt", "Message", "http://www.onvif.org/ver10/schema");

            DateTime time = System.DateTime.UtcNow;

            if (dateTime != DateTime.MinValue)
            {
                time = dateTime;
            }

            if (propertyOperation != null)
            {
                XmlAttribute operation = xmlDocument.CreateAttribute("PropertyOperation");
                operation.Value = propertyOperation;
                res.Message.Attributes.Append(operation);
            }

            //Message[UtcTime]
            XmlAttribute utcTime = xmlDocument.CreateAttribute("UtcTime");

            utcTime.Value = System.Xml.XmlConvert.ToString(time, XmlDateTimeSerializationMode.Utc);
            res.Message.Attributes.Append(utcTime);


            //Message/Source
            XmlElement source = xmlDocument.CreateElement("tt", "Source", "http://www.onvif.org/ver10/schema");

            res.Message.AppendChild(source);

            foreach (SimpleItem item in sourceItems)
            {
                //Message/Source/SimpleItem
                XmlElement simpleItem = xmlDocument.CreateElement("tt", "SimpleItem", "http://www.onvif.org/ver10/schema");
                source.AppendChild(simpleItem);

                //Message/Source/SimpleItem[Name]
                XmlAttribute name = xmlDocument.CreateAttribute("Name");
                name.Value = item.Name;
                simpleItem.Attributes.Append(name);

                //Message/Source/SimpleItem[Value]
                XmlAttribute value = xmlDocument.CreateAttribute("Value");
                value.Value = item.Value;
                simpleItem.Attributes.Append(value);
            }

            //Message/Data
            XmlElement data = xmlDocument.CreateElement("tt", "Data", "http://www.onvif.org/ver10/schema");

            res.Message.AppendChild(data);

            foreach (SimpleItem item in dataItems)
            {
                //Message/Data/SimpleItem
                XmlElement simpleItem = xmlDocument.CreateElement("tt", "SimpleItem", "http://www.onvif.org/ver10/schema");
                data.AppendChild(simpleItem);

                //Message/Data/SimpleItem[Name]
                XmlAttribute name = xmlDocument.CreateAttribute("Name");
                name.Value = item.Name;
                simpleItem.Attributes.Append(name);

                //Message/Data/SimpleItem[Value]
                XmlAttribute value = xmlDocument.CreateAttribute("Value");
                value.Value = item.Value;
                simpleItem.Attributes.Append(value);
            }

            return(res);
        }
        /// <summary>
        /// Validates resulting message
        /// </summary>
        /// <param name="notify">Notify packet</param>
        /// <param name="message">Selected message</param>
        /// <param name="rawData">Raw notification data</param>
        /// <param name="resultTopic">Resulting event topic</param>
        /// <param name="validateResultMessageFunction">Message validation method</param>
        /// <param name="accessPointToken">Expected access point token</param>
        /// <param name="credentialsToken">Expected credentials token</param>
        /// <param name="credentialsHolderName">Expected credentials holder name</param>
        void ValidateResultMessage(Notify notify,
                                   NotificationMessageHolderType message,
                                   byte[] rawData,
                                   TopicInfo resultTopic,
                                   ValidateMessageFunction validateResultMessageFunction,
                                   string accessPointToken, string credentialsToken, string credentialsHolderName)
        {
            BeginStep("Validate message");

            XmlDocument doc           = new XmlDocument();
            string      soapRawPacket = System.Text.Encoding.UTF8.GetString(rawData);

            doc.LoadXml(soapRawPacket);

            XmlNamespaceManager manager = CreateNamespaceManager(doc);

            Dictionary <NotificationMessageHolderType, XmlElement> rawElements =
                GetRawElements(notify.NotificationMessage, doc, manager, true);

            StringBuilder logger = new StringBuilder();
            bool          ok     = true;

            MessageCheckSettings settings = new MessageCheckSettings();

            settings.NamespaceManager          = manager;
            settings.ExpectedPropertyOperation = null;
            settings.ExpectedTopic             = resultTopic;
            settings.RawMessageElements        = rawElements;
            settings.Data = accessPointToken;

            ok = validateResultMessageFunction(message, settings, logger);

            if (ok)
            {
                Dictionary <string, string> dataSimpleItems = message.Message.GetMessageDataSimpleItems();

                if (dataSimpleItems.ContainsKey(CREDENTIALSTOKENSIMPLEITEM))
                {
                    string actualCredentialsToken = dataSimpleItems[CREDENTIALSTOKENSIMPLEITEM];
                    if (credentialsToken != actualCredentialsToken)
                    {
                        ok = false;
                        logger.Append(string.Format("CredentialToken is incorrect: expected '{0}', actual '{1}'{2}",
                                                    credentialsToken, actualCredentialsToken, Environment.NewLine));
                    }
                }
                if (!string.IsNullOrEmpty(credentialsHolderName))
                {
                    if (dataSimpleItems.ContainsKey(CREDENTIALSHOLDERNAMESIMPLEITEM))
                    {
                        string actualCredentialsHolderName = dataSimpleItems[CREDENTIALSHOLDERNAMESIMPLEITEM];
                        if (!string.IsNullOrEmpty(actualCredentialsHolderName))
                        {
                            if (credentialsHolderName != actualCredentialsHolderName)
                            {
                                ok = false;
                                logger.Append(
                                    string.Format("CredentialHolderName is incorrect: expected '{0}', actual '{1}'{2}",
                                                  credentialsHolderName, actualCredentialsHolderName, Environment.NewLine));
                            }
                        }
                    }
                }
            }

            if (!ok)
            {
                throw new AssertException(logger.ToStringTrimNewLine());
            }

            StepPassed();
        }
Esempio n. 26
0
 public static bool IsOnvifMessage(NotificationMessageHolderType msg)
 {
     return(IsOnvifMessage(msg.Message));
 }
        void ConfigurationEventTest(
            TopicInfo topicInfo,
            Action <XmlElement, TopicInfo> validateTopic,
            ValidateConfigurationMessageFunction validateMessageFunction,
            string sourceTokenSimpleItem,
            Action <string> validateConfigurationFunction)
        {
            EndpointReferenceType subscriptionReference = null;

            System.DateTime subscribeStarted = System.DateTime.MaxValue;

            int timeout = 60;

            RunTest(
                () =>
            {
                // Get topic description from the DUT.
                XmlElement topicElement = GetTopicElement(topicInfo);

                BeginStep("Check if the event topic is supported");
                if (topicElement == null)
                {
                    LogStepEvent(string.Format("Topic {0} not supported", topicInfo.GetDescription()));
                }
                StepPassed();

                if (topicElement == null)
                {
                    return;
                }

                XmlElement messageDescription = topicElement.GetMessageDescription();
                validateTopic(messageDescription, topicInfo);

                // filter for current test
                TestTool.Proxies.Event.FilterType filter = CreateSubscriptionFilter(topicInfo);

                string message = string.Format("{0}  event is expected!", topicInfo.GetDescription());

                Notify notify   = null;
                XmlDocument doc = new XmlDocument();
                try
                {
                    subscriptionReference =
                        ReceiveMessages(filter,
                                        timeout,
                                        new Action(() =>
                    {
                        _operator.ShowMessage(message);
                    }),
                                        doc,
                                        out notify,
                                        out subscribeStarted);
                }
                finally
                {
                    _operator.HideMessage();
                }

                Assert(notify.NotificationMessage.Length == 1,
                       string.Format("{0} messages received - unable to check actual configuration", notify.NotificationMessage.Length),
                       "Check that exactly one notification is received");

                BeginStep("Validate message");

                XmlNamespaceManager manager = CreateNamespaceManager(doc);
                Dictionary <NotificationMessageHolderType, XmlElement> notifications = GetRawElements(notify.NotificationMessage, doc, manager, true);

                StringBuilder logger = new StringBuilder();
                bool ok = true;

                MessageCheckSettings settings = new MessageCheckSettings();
                settings.ExpectedTopic        = topicInfo;
                settings.RawMessageElements   = notifications;
                settings.NamespaceManager     = manager;

                NotificationMessageHolderType m = notify.NotificationMessage[0];
                ok = validateMessageFunction(m, notifications[m], manager, logger);

                if (!ok)
                {
                    throw new AssertException(logger.ToStringTrimNewLine());
                }

                StepPassed();

                // validateMessageFunction should return false, if this simple item is missing
                string token = m.Message.GetMessageSourceSimpleItems()[sourceTokenSimpleItem];
                validateConfigurationFunction(token);
            },
                () =>
            {
                _operator.HideMessage();
                ReleaseSubscription(subscribeStarted, subscriptionReference, timeout);
            });
        }
 void ValidateDoorModeSimpleItem(NotificationMessageHolderType notification, DoorMode expectedMode)
 {
     ValidateDoorModeSimpleItem(notification, expectedMode.ToString());
 }
Esempio n. 29
0
        internal StepType PMSPullMessagesTest(out System.DateTime target, out NotificationMessageHolderType[] NotificationMessage, out System.DateTime TerminationTime, out SoapException ex, out int timeOut, out bool timeOutSpec, string Timeout, int MessageLimit, XmlElement[] Any)
        {
            StepType res = StepType.None;

            target      = new System.DateTime();
            timeOut     = 0;
            timeOutSpec = false;
            ex          = null;
            bool   passed     = true;
            string logMessage = "";

            NotificationMessage = new NotificationMessageHolderType[1];
            TerminationTime     = new System.DateTime();

            //Get step list for command
            XmlNodeList m_testList = m_TestCommon.GetStepsForCommand("PMSPullMessages");

            if (m_testList != null)
            {
                //Get current step
                XmlNode test = m_testList[m_commandCount[PMSPullMessages]];

                #region Analyze request

                //Timeout
                CommonCompare.StringCompare("RequestParameters/Timeout", "Timeout", Timeout, ref logMessage, ref passed, test);

                //MessageLimit
                CommonCompare.IntCompare("RequestParameters/MessageLimit", "MessageLimit", MessageLimit, ref logMessage, ref passed, test);

                #endregion //Analyze request

                //Generate response

                //TopicNamespaceLocation
                object targetObj;
                res = m_TestCommon.GenerateResponseStepTypeNotVoidTimeout(test, out targetObj, out ex, out timeOut, out timeOutSpec, typeof(NotificationMessageHolderType[]));
                NotificationMessage = (NotificationMessageHolderType[])targetObj;

                #region Serialization Temp
                //bool dsr = false;
                //XmlSerializer serializer1 = new XmlSerializer(typeof(bool));
                //TextWriter textWriter = new StreamWriter("c:\\2.txt");
                //serializer1.Serialize(textWriter, dsr);
                #endregion //Serialization Temp


                if (res == StepType.Normal)
                {
                    //CurrentTime
                    string CurrentTimeType = test.SelectSingleNode("ResponseParametersAdditional/CurrentTime/@type").InnerText;
                    switch (CurrentTimeType)
                    {
                    case "now":
                    {
                        target = System.DateTime.UtcNow;
                        break;
                    }

                    case "value":
                    {
                        target = Convert.ToDateTime(test.SelectSingleNode("ResponseParametersAdditional/CurrentTime").InnerText);
                        break;
                    }

                    case "nowDiff":
                    {
                        int timeDiff = Convert.ToInt32(test.SelectSingleNode("ResponseParametersAdditional/CurrentTime").InnerText);
                        target = System.DateTime.UtcNow.AddSeconds(timeDiff);
                        break;
                    }
                    }

                    //TerminationTime
                    if (test.SelectNodes("ResponseParametersAdditional/TerminationTime[@differance=\"true\"]").Count != 0)
                    {
                        int timeDiff = Convert.ToInt32(test.SelectSingleNode("ResponseParametersAdditional/TerminationTime").InnerText);
                        TerminationTime = target.AddSeconds(timeDiff);
                    }
                    else
                    {
                        TerminationTime = Convert.ToDateTime(test.SelectSingleNode("ResponseParametersAdditional/TerminationTime").InnerText);
                    }

                    //For tns1:Monitoring/OperatingTime/LastClockSynchronization event
                    if (test.SelectNodes("ResponseParametersAdditional/LastClockSynchronization[@differance=\"true\"]").Count != 0)
                    {
                        XmlNameTable        xmlNameTable        = NotificationMessage[0].Message.OwnerDocument.NameTable;
                        XmlNamespaceManager xmlNamespaceManager = new XmlNamespaceManager(xmlNameTable);
                        xmlNamespaceManager.AddNamespace("tt", "http://www.onvif.org/ver10/schema");
                        NotificationMessage[0].Message.SelectSingleNode("tt:Data/tt:SimpleItem[@Name=\"Status\"]/@Value", xmlNamespaceManager);
                        //int timeDiff = Convert.ToInt32(test.SelectSingleNode("ResponseParametersAdditional/TerminationTime").InnerText);
                        //TerminationTime = target.AddSeconds(timeDiff);
                    }
                }


                //Log message
                m_TestCommon.writeToLog(test, logMessage, passed);

                Increment(m_testList.Count, PMSPullMessages);
            }
            else
            {
                timeOut = 0;
                target  = new System.DateTime();
                ex      = null;
                res     = StepType.None;
            }
            return(res);
        }
        public System.DateTime PullMessages(
            [System.Xml.Serialization.XmlElementAttribute(DataType = "duration")] string Timeout,
            int MessageLimit,
            [System.Xml.Serialization.XmlAnyElementAttribute()] System.Xml.XmlElement[] Any,
            out System.DateTime TerminationTime,
            [System.Xml.Serialization.XmlElementAttribute("NotificationMessage", Namespace = "http://docs.oasis-open.org/wsn/b-2")] out NotificationMessageHolderType[] NotificationMessage)
        {
            if (Timeout == "PT24H")
            {
                SoapFaultSubCode subCode =
                    new SoapFaultSubCode(new XmlQualifiedName("ShitHappens", "http://www.onvif.org/ver10/error"));

                SoapException exception = new SoapException("Invalid Argument",
                                                            new XmlQualifiedName("Sender",
                                                                                 "http://www.w3.org/2003/05/soap-envelope"),
                                                            subCode);
                throw exception;
            }

            //if (Timeout == "PT20S")
            //{
            //    PullMessagesFaultResponseType details = new PullMessagesFaultResponseType();
            //    details.MaxMessageLimit = 5;
            //    details.MaxTimeout = "PT15S";

            //    FaultException<PullMessagesFaultResponseType> exception = new FaultException<PullMessagesFaultResponseType>(details, "InvalidArg", new FaultCode("Sender", "http://www.w3.org/2003/05/soap-envelope"));
            //    throw exception;
            //}

            string varName = "PullMessagesCounter";

            int cnt = 0;

            if (Application.AllKeys.Contains(varName))
            {
                cnt = (int)Application[varName];
            }

            if (cnt % 2 == 0)
            {
                XmlDocument doc = new XmlDocument();
                doc.LoadXml("<tt:Message UtcTime=\"2008-10-10T12:24:57.321\" xmlns:tt=\"http://www.onvif.org/ver10/schema\"><tt:Source><tt:SimpleItem Name=\"RecordingJobToken\" Value=\"1\"/></tt:Source><tt:Data><tt:SimpleItem Name=\"State\" Value=\"Idle\" /><tt:ElementItem Name=\"Information\"><tt:RecordingJobStateInformation><tt:RecordingToken>Recording1</tt:RecordingToken><tt:State>Active</tt:State></tt:RecordingJobStateInformation></tt:ElementItem></tt:Data></tt:Message>");

                NotificationMessageHolderType notification1 = CreateMessage(doc,
                                                                            "tns1",
                                                                            "http://www.onvif.org/ver10/topics",
                                                                            "RecordingConfig/JobState");

                //NotificationMessageHolderType notification2 = CreateMessage(doc, "tns1", "PropertyTopic2");

                NotificationMessage = new NotificationMessageHolderType[] { notification1 /*, notification2*/ };
            }
            else
            {
                NotificationMessage = new NotificationMessageHolderType[] { };
            }
            cnt++;
            Application[varName] = cnt;

            TerminationTime = System.DateTime.Now.AddMinutes(3);
            if (actionHeader == null)
            {
                actionHeader = new ActionHeader();
            }
            actionHeader.Value = "http://www.onvif.org/ver10/events/wsdl/PullPointSubscription/PullMessagesResponse";

            return(System.DateTime.Now.AddSeconds(10));
        }