private void btnSubscribe_Click(object sender, EventArgs e) { try { EventsReceiver listener = new EventsReceiver(); listener.NotificationReceived += listener_NotificationReceived; listener.Name = tbEventsReceiver.Text; _listener = listener; _host = new ServiceHost(listener, new Uri(tbEventsReceiver.Text)); ServiceEndpoint endpoint = _host.AddServiceEndpoint(typeof(Proxies.Events.NotificationConsumer), new WSHttpBinding(SecurityMode.None), string.Empty); _host.Open(); Subscribe request = new Subscribe(); request.ConsumerReference = new EndpointReferenceType(); request.ConsumerReference.Address = new AttributedURIType(); request.ConsumerReference.Address.Value = tbEventsReceiver.Text; if (!string.IsNullOrEmpty(tbTopicsFilter.Text)) { request.Filter = CreateFilter(); } request.InitialTerminationTime = tbSubscriptionTime.Text; SubscribeResponse response = Client.Subscribe(request); tcSubscription.SelectedTab = tpManageSubscription; _subscriptionReference = response.SubscriptionReference; tbSubscriptionReference.Text = _subscriptionReference.Address.Value; _subscribed = true; if (response.TerminationTime.HasValue) { _terminationTime = response.TerminationTime.Value; tbTerminationTime.Text = _terminationTime.ToString("hh:mm:ss.fff"); DisplayTimeLeft(); } EndpointAddress addr = new EndpointAddress(_subscriptionReference.Address.Value); EndpointReferenceBehaviour behaviour = new EndpointReferenceBehaviour(response.SubscriptionReference); _subscriptionManager = new SubscriptionManagerClient(_custombindingSoap12, addr); _subscriptionManager.Endpoint.Behaviors.Add(behaviour); _pullPointSubscriptionClient = new PullPointSubscriptionClient(_custombindingSoap12, addr); _pullPointSubscriptionClient.Endpoint.Behaviors.Add(behaviour); timer.Start(); btnSubscribe.Enabled = false; btnRenew.Enabled = true; btnUnsubscribe.Enabled = true; btnSetSynchronizationPoint.Enabled = true; } catch (Exception exc) { _host.Close(); MessageBox.Show(exc.Message); } }
/// <summary> /// /// </summary> /// <param name="Filter"></param> /// <param name="InitialTerminationTime"></param> /// <param name="SubscriptionPolicy"></param> /// <param name="Any"></param> /// <param name="CurrentTime"></param> /// <param name="TerminationTime"></param> /// <returns></returns> /// <remarks>As this method uses EventPortType client, the client can be created without additional data.</remarks> protected EndpointReferenceType CreatePullPointSubscription( FilterType Filter, string InitialTerminationTime, CreatePullPointSubscriptionSubscriptionPolicy SubscriptionPolicy, ref XmlElement[] Any, out DateTime CurrentTime, out System.Nullable <System.DateTime> TerminationTime) { EnsureEventPortTypeClientCreated(); EndpointReferenceType result = null; System.Xml.XmlElement[] anyCopy = Any; System.DateTime currentTimeCopy = DateTime.MinValue; DateTime?terminationTimeCopy = DateTime.MinValue; RunStep(() => { result = _eventPortTypeClient.CreatePullPointSubscription( Filter, InitialTerminationTime, SubscriptionPolicy, ref anyCopy, out currentTimeCopy, out terminationTimeCopy); }, "Create Pull Point Subsciption"); CurrentTime = currentTimeCopy; TerminationTime = terminationTimeCopy; return(result); }
public void UnsubscribeTest() { EndpointReferenceType subscriptionReference = null; bool unsubscribed = true; RunTest <object>( new Backup <object>( () => { return(null); }), () => { EnsureNotificationProducerClientCreated(); SubscribeResponse subscribeResponse = CreateStandardSubscription(); unsubscribed = false; if (subscribeResponse == null) { return; } subscriptionReference = subscribeResponse.SubscriptionReference; Unsubscribe request = new Unsubscribe(); UnsubscribeResponse unsubscribeResponse = Unsubscribe(request); unsubscribed = true; Renew renew = new Renew(); renew.TerminationTime = "PT10S"; RunStep( () => { _subscriptionManagerClient.Renew(renew); unsubscribed = false; }, "Renew - negative test", new ValidateTypeFault(ValidateResourseUnknownFault)); }, (o) => { if (!unsubscribed) { if (subscriptionReference != null) { CreateSubscriptionManagerClient(subscriptionReference); } // // Use default timeout of 10 seconds. // Really timeout passed in Subscribe request may be different. // ReleaseSubscriptionManager(); } }); }
protected void AttachAddressing(ServiceEndpoint endpoint, EndpointReferenceType endpointReference) { if (endpointReference.ReferenceParameters != null && endpointReference.ReferenceParameters.Any != null) { Utils.EndpointReferenceBehaviour behaviour = new EndpointReferenceBehaviour(endpointReference); endpoint.Behaviors.Add(behaviour); } }
/* * [Test(Name = "DOOR CONTROL – DOOR MODE EVENT", * Path = PATHDOORCONTROL, * Order = "04.01.01", * Id = "4-1-1", * Category = Category.DOORCONTROL, * Version = 2.1, * RequiredFeatures = new Feature[] { Feature.DoorControlService }, * RequirementLevel = RequirementLevel.Must, * FunctionalityUnderTest = new Functionality[] { Functionality.Notify, * Functionality.TopicFilter, Functionality.EventsSetSynchronizationPoint, Functionality.DoorModeEvent })] * public void DoorModeEventTest() * { * // Topic for current test * * TopicInfo topic = ConstructTopic(new string[] { "Door", "State", "DoorMode" }); * * CommonEventTest(topic, ValidateDoorModeTopic, GetDoorInfoList, ValidateDoorModeMessage); * * } * * [Test(Name = "DOOR CONTROL – DOOR PHYSICAL STATE EVENT", * Path = PATHDOORCONTROL, * Order = "04.01.02", * Id = "4-1-2", * Category = Category.DOORCONTROL, * Version = 2.1, * RequiredFeatures = new Feature[] { Feature.DoorControlService }, * RequirementLevel = RequirementLevel.Must, * FunctionalityUnderTest = new Functionality[] { Functionality.Notify, Functionality.TopicFilter, Functionality.EventsSetSynchronizationPoint, Functionality.DoorPhysicalStateEvent })] * public void DoorPhysicalStateEventTest() * { * // Topic for current test * TopicInfo topicInfo = ConstructTopic(new string[] { "Door", "State", "DoorPhysicalState" }); * * CommonEventTest(topicInfo, ValidateDoorPhysicalStateTopic, GetDoorInfoList, ValidateDoorPhysicalStateMessage); * } * * * [Test(Name = "DOOR CONTROL – DOUBLE LOCK PHYSICAL STATE EVENT", * Path = PATHDOORCONTROL, * Order = "04.01.03", * Id = "4-1-3", * Category = Category.DOORCONTROL, * Version = 2.1, * RequiredFeatures = new Feature[] { Feature.DoorControlService }, * RequirementLevel = RequirementLevel.Must, * FunctionalityUnderTest = new Functionality[] { Functionality.Notify, Functionality.TopicFilter, Functionality.EventsSetSynchronizationPoint, Functionality.DoubleLockPhysicalStateEvent })] * public void DoorDoubleLockPhysicalStateEventTest() * { * // Topic for current test * * TopicInfo topicInfo = ConstructTopic(new string[] { "Door", "State", "DoubleLockPhysicalState" }); * * CommonEventTest(topicInfo, ValidateDoorDoubleLockPhysicalStateTopic, GetDoorInfoList, ValidateDoorDoubleLockMessage); * * } * * [Test(Name = "DOOR CONTROL – LOCK PHYSICAL STATE EVENT", * Path = PATHDOORCONTROL, * Order = "04.01.04", * Id = "4-1-4", * Category = Category.DOORCONTROL, * Version = 2.1, * RequiredFeatures = new Feature[] { Feature.DoorControlService }, * RequirementLevel = RequirementLevel.Must, * FunctionalityUnderTest = new Functionality[] { Functionality.Notify, Functionality.TopicFilter, Functionality.EventsSetSynchronizationPoint, Functionality.LockPhysicalStateEvent })] * public void DoorLockPhysicalStateEventTest() * { * // Topic for current test * TopicInfo topicInfo = ConstructTopic(new string[] { "Door", "State", "LockPhysicalState" }); * * CommonEventTest(topicInfo, ValidateDoorLockPhysicalStateTopic, GetDoorInfoList, ValidateDoorLockPhysicalStateMessage); * * } * * * [Test(Name = "DOOR CONTROL – DOOR TAMPER EVENT", * Path = PATHDOORCONTROL, * Order = "04.01.05", * Id = "4-1-5", * Category = Category.DOORCONTROL, * Version = 2.1, * RequiredFeatures = new Feature[] { Feature.DoorControlService }, * RequirementLevel = RequirementLevel.Must, * FunctionalityUnderTest = new Functionality[] { Functionality.Notify, Functionality.TopicFilter, Functionality.EventsSetSynchronizationPoint, Functionality.DoorTamperEvent })] * public void DoorTamperEventTest() * { * // Topic for current test * * TopicInfo topicInfo = ConstructTopic(new string[] { "Door", "State", "DoorTamper" }); * * CommonEventTest(topicInfo, ValidateDoorTamperTopic, GetDoorInfoList, ValidateDoorTamperMessage); * * } * * * [Test(Name = "DOOR CONTROL – DOOR ALARM EVENT", * Path = PATHDOORCONTROL, * Order = "04.01.06", * Id = "4-1-6", * Category = Category.DOORCONTROL, * Version = 2.1, * RequiredFeatures = new Feature[] { Feature.DoorControlService }, * RequirementLevel = RequirementLevel.Must, * FunctionalityUnderTest = new Functionality[] { Functionality.Notify, Functionality.TopicFilter, Functionality.EventsSetSynchronizationPoint, Functionality.DoorAlarmEvent })] * public void DoorAlarmEventTest() * { * // Topic for current test * * TopicInfo topicInfo = ConstructTopic(new string[] { "Door", "State", "DoorAlarm" }); * * CommonEventTest(topicInfo, ValidateDoorAlarmTopic, GetDoorInfoList, ValidateDoorAlarmMessage); * * } */ /// <summary> /// Common event test /// </summary> /// <param name="topicInfo">Topic to be tested</param> /// <param name="validateTopic">Method of topic validation</param> /// <param name="getDataForValidation">Method for getting additional data for message validation</param> /// <param name="validateMessageFunction">Method for message validation</param> void CommonEventTest(TopicInfo topicInfo, Action <XmlElement, TopicInfo> validateTopic, Func <object> getDataForValidation, ValidateMessageFunction validateMessageFunction) { EndpointReferenceType subscriptionReference = null; System.DateTime subscribeStarted = System.DateTime.MaxValue; int timeout = 60; RunTest( () => { // Get topic description from the DUT. XmlElement topicElement = GetTopicElement(topicInfo); Assert(topicElement != null, string.Format("Topic {0} not supported", topicInfo.GetDescription()), "Check that the event topic is supported"); object data = getDataForValidation(); // Validate topic XmlElement messageDescription = topicElement.GetMessageDescription(); validateTopic(messageDescription, topicInfo); // Create filter for test FilterInfo filter = CreateFilter(topicInfo, messageDescription); // subscribe XmlDocument doc = new XmlDocument(); Notify notify = null; subscriptionReference = ReceiveMessages(filter, timeout, doc, out notify, out subscribeStarted); if (notify != null) { ValidateMessages(notify.NotificationMessage, doc, topicInfo, data, validateMessageFunction); } }, () => { if (subscribeStarted != System.DateTime.MaxValue) { if (subscriptionReference != null && _subscriptionManagerClient == null) { CreateSubscriptionManagerClient(subscriptionReference); } TimeSpan diff = System.DateTime.Now - subscribeStarted; int releaseTime = timeout * 1000 - (int)diff.TotalMilliseconds; ReleaseSubscriptionManager(releaseTime); } }); }
public void InvalidMessageContentFilterTest() { EndpointReferenceType subscriptionReference = null; RunTest <object>( new Backup <object>( () => { return(null); }), () => { Proxies.Event.Subscribe request = new Subscribe(); bool topicSetEmpty = false; FilterInfo filterInfo = GetInvalidMessageContentFilter(out topicSetEmpty); if (topicSetEmpty) { return; } Assert(filterInfo != null, "Failed to create filter for test", "Check if a filter has been created"); request.Filter = filterInfo.Filter; request.InitialTerminationTime = "PT10S"; request.ConsumerReference = new EndpointReferenceType(); request.ConsumerReference.Address = new AttributedURIType(); request.ConsumerReference.Address.Value = _subscriberAddress; EnsureNotificationProducerClientCreated(); RunStep( () => { SubscribeResponse response = _notificationProducerClient.Subscribe(request); if (response == null) { throw new AssertException("The DUT did not return Subscribe response"); } subscriptionReference = response.SubscriptionReference; }, "Subscribe - negative test", new ValidateTypeFault(ValidateInvalidMessageContentFilterFault)); }, (o) => { if (subscriptionReference != null) { if (_subscriptionManagerClient == null) { CreateSubscriptionManagerClient(subscriptionReference); } ReleaseSubscriptionManager(10000); } }); }
/// <summary> /// Send the subscription message to the endpoint /// </summary> /// <param name="eventSource"></param> /// <param name="callbackEndpoint"></param> /// <param name="eventOut"></param> /// <returns></returns> /// protected String SubscribeMsg(EventSourceClient eventSource, EndpointAddress callbackEndpoint, String eventOut) { Subscribe s = new Subscribe(); (s.Delivery = new DeliveryType()).Mode = "http://schemas.xmlsoap.org/ws/2004/08/eventing/DeliveryModes/Push"; XmlDocument doc = new XmlDocument(); using (XmlWriter writer = doc.CreateNavigator().AppendChild()) { EndpointReferenceType notifyTo = new EndpointReferenceType(); (notifyTo.Address = new AttributedURI()).Value = callbackEndpoint.Uri.AbsoluteUri; XmlRootAttribute notifyToElem = new XmlRootAttribute("NotifyTo"); notifyToElem.Namespace = "http://schemas.xmlsoap.org/ws/2004/08/eventing"; XmlDocument doc2 = new XmlDocument(); using (XmlWriter writer2 = doc2.CreateNavigator().AppendChild()) { XmlRootAttribute ReferenceElement = new XmlRootAttribute("ReferenceElement"); foreach (AddressHeader h in callbackEndpoint.Headers) { h.WriteAddressHeader(writer2); } writer2.Close(); notifyTo.ReferenceParameters = new ReferenceParametersType(); notifyTo.ReferenceParameters.Any = notifyTo.ReferenceParameters.Any = doc2.ChildNodes.Cast <XmlElement>().ToArray <XmlElement>(); } new XmlSerializer(notifyTo.GetType(), notifyToElem).Serialize(writer, notifyTo); } (s.Delivery.Any = new XmlElement[1])[0] = doc.DocumentElement; (s.Filter = new FilterType()).Dialect = "http://schemas.xmlsoap.org/ws/2006/02/devprof/Action"; (s.Filter.Any = new System.Xml.XmlNode[1])[0] = new System.Xml.XmlDocument().CreateTextNode(eventOut); SubscribeResponse subscription; Console.WriteLine("Subscribing to the event..."); //Console.ReadLine(); subscription = eventSource.SubscribeOp(s); String subscriptionId = null; foreach (XmlNode xel in subscription.SubscriptionManager.ReferenceParameters.Any) { if (xel.LocalName.Equals("Identifier") && xel.NamespaceURI.Equals("http://schemas.xmlsoap.org/ws/2004/08/eventing")) { subscriptionId = xel.InnerText; } } return(subscriptionId); }
public ByeRequest(EndpointReferenceType EndpointReference, string Types, ScopesType Scopes, string XAddrs, uint MetadataVersion, System.Xml.XmlElement[] Any, System.Xml.XmlAttribute[] AnyAttr) { this.EndpointReference = EndpointReference; this.Types = Types; this.Scopes = Scopes; this.XAddrs = XAddrs; this.MetadataVersion = MetadataVersion; this.Any = Any; this.AnyAttr = AnyAttr; }
public void TimeoutTest() { EndpointReferenceType endpointReference = null; RunTest <object>( () => { return(null); }, () => { EnsureEventPortTypeClientCreated(); int actualTerminationTime = 20; endpointReference = CreateStandardSubscription(ref actualTerminationTime); if (endpointReference == null) { return; } BeginStep("Wait until subscription expires"); Sleep(actualTerminationTime * 1000 + _operationDelay); StepPassed(); Renew renew = new Renew(); renew.TerminationTime = "PT10S"; RunStep( () => { _subscriptionManagerClient.Renew(renew); }, "Renew - negative test", new ValidateTypeFault(ValidateUnsubscribeFault)); }, (o) => { if (endpointReference != null) { if (endpointReference.Address != null && _subscriptionManagerClient == null) { CreateSubscriptionManagerClient(endpointReference); } // // Use timeout of 10 seconds. // TT has already spent time waiting for timeout passed in Subscribe. // 10 seconds is the same as value passed in Renew. // ReleaseSubscriptionManager(10000); } }); }
public void RenewTest() { EndpointReferenceType endpointReference = null; int actualTerminationTime = 10; RunTest <object>( () => { return(null); }, () => { EnsureEventPortTypeClientCreated(); endpointReference = CreateStandardSubscription(ref actualTerminationTime); if (endpointReference == null) { return; } Renew renew = new Renew(); renew.TerminationTime = "PT10S"; // there was no requirement to retry Renew for this test RenewResponse renewResponse = Renew(renew); Assert(renewResponse != null, "The DUT did not return Renew response", "Check that the DUT returned Renew response"); Assert(renewResponse.CurrentTimeSpecified, "Current time is not specified", "Check that CurrentTime is specified"); Assert(renewResponse.TerminationTime.HasValue, "Termination time is not specified", "Check that TerminationTime is specified"); Assert(renewResponse.CurrentTime.AddSeconds(10) <= renewResponse.TerminationTime.Value, "TerminationTime < CurrentTime + InitialTerminationTime", "Validate times"); }, (o) => { if (endpointReference != null) { if (endpointReference.Address != null && _subscriptionManagerClient == null) { CreateSubscriptionManagerClient(endpointReference); } ReleaseSubscriptionManager(actualTerminationTime * 1000); } }); }
/// <summary> /// Creates PullPointSubscription client using address passed. /// </summary> /// <param name="address">Service address.</param> /// <returns></returns> protected PullPointSubscriptionClient CreatePullPointSubscriptionClient(EndpointReferenceType endpointReference) { HttpBinding binding = CreateEventServiceBinding(endpointReference.Address.Value); _pullPointSubscriptionClient = new PullPointSubscriptionClient(binding, new EndpointAddress(endpointReference.Address.Value)); AddSecurityBehaviour(_pullPointSubscriptionClient.Endpoint); AttachAddressing(_pullPointSubscriptionClient.Endpoint, endpointReference); SetupTimeout(_pullPointSubscriptionClient.InnerChannel); return(_pullPointSubscriptionClient); }
public void InvalidTopicExpressionTest() { EndpointReferenceType subscriptionReference = null; RunTest <object>( new Backup <object>( () => { return(null); }), () => { EnsureNotificationProducerClientCreated(); string invalidTopic = GetInvalidTopic(); Proxies.Event.Subscribe request = new Subscribe(); request.Filter = new FilterType(); request.InitialTerminationTime = "PT10S"; request.ConsumerReference = new EndpointReferenceType(); request.ConsumerReference.Address = new AttributedURIType(); request.ConsumerReference.Address.Value = _subscriberAddress; XmlDocument doc = new XmlDocument(); XmlElement topicElement = doc.CreateTopicElement(); topicElement.InnerText = invalidTopic; request.Filter.Any = new XmlElement[] { topicElement }; RunStep( () => { SubscribeResponse response = _notificationProducerClient.Subscribe(request); subscriptionReference = response.SubscriptionReference; }, "Subscribe - negative test", new ValidateTypeFault(ValidateInvalidTopicFilterFault)); }, (o) => { if (subscriptionReference != null) { if (_subscriptionManagerClient == null) { CreateSubscriptionManagerClient(subscriptionReference); } ReleaseSubscriptionManager(10000); } }); }
/// <summary> /// Creates SubscriptionManager client using address passed. /// </summary> /// <param name="endpointAddress">Service address.</param> /// <returns></returns> protected SubscriptionManagerClient CreateSubscriptionManagerClient(EndpointReferenceType endpointReference) { HttpBinding binding = CreateEventServiceBinding(endpointReference.Address.Value); _subscriptionManagerClient = new SubscriptionManagerClient(binding, new EndpointAddress(endpointReference.Address.Value)); System.Net.ServicePointManager.Expect100Continue = false; AddSecurityBehaviour(_subscriptionManagerClient.Endpoint); AttachAddressing(_subscriptionManagerClient.Endpoint, endpointReference); SetupTimeout(_subscriptionManagerClient.InnerChannel); return(_subscriptionManagerClient); }
public void ResourceUnknownTest() { EndpointReferenceType subscriptionReference = null; bool unsubscribed = true; int terminationTime = 10; RunTest <object>( new Backup <object>( () => { return(null); }), () => { EnsureNotificationProducerClientCreated(); SubscribeResponse subscribeResponse = CreateStandardSubscription(ref terminationTime); unsubscribed = false; if (subscribeResponse == null) { return; } subscriptionReference = subscribeResponse.SubscriptionReference; Unsubscribe request = new Unsubscribe(); UnsubscribeResponse unsubscribeResponse = Unsubscribe(request); unsubscribed = true; RunStep( () => { _subscriptionManagerClient.Unsubscribe(request); }, "Unsubscribe - negative test", new ValidateTypeFault(ValidateUnsubscribeFault)); }, (o) => { if (!unsubscribed) { if (subscriptionReference != null && _subscriptionManagerClient == null) { CreateSubscriptionManagerClient(subscriptionReference); } ReleaseSubscriptionManager(terminationTime * 1000); } }); }
/// <summary> /// Subscribes to all events provided by the device and directs to :8080/subscription-1 Http listener /// </summary> /// <param name="uri">XAddr URI for Onvif events</param> /// <param name="username">User</param> /// <param name="password">Password</param> public void Subscribe(string uri, double deviceTimeOffset, string username, string password) { EventPortTypeClient eptc = OnvifServices.GetEventClient(uri, deviceTimeOffset, username, password); string localIP = GetLocalIp(); // Producer client NotificationProducerClient npc = OnvifServices.GetNotificationProducerClient(uri, deviceTimeOffset, username, password); // ip, port, username, password); npc.Endpoint.Address = eptc.Endpoint.Address; Subscribe s = new Subscribe(); // Consumer reference tells the device where to Post messages back to (the client) EndpointReferenceType clientEndpoint = new EndpointReferenceType() { Address = new AttributedURIType() { Value = string.Format("http://{0}:8080/subscription-1", localIP) } }; s.ConsumerReference = clientEndpoint; s.InitialTerminationTime = "PT60S"; try { SubscribeResponse sr = npc.Subscribe(s); // Store the subscription URI for use in Renew SubRenewUri = sr.SubscriptionReference.Address.Value; // Start timer to periodically check if a Renew request needs to be issued // Use PC time for timer in case camera time doesn't match PC time // This works fine because the renew command issues a relative time (i.e. PT60S) so PC/Camera mismatch doesn't matter SubTermTime = System.DateTime.UtcNow.AddSeconds(50); // sr.TerminationTime; SubRenewTimer.Start(); SubRenewTimer.Interval = 1000; SubRenewTimer.Elapsed += SubRenewTimer_Elapsed; OnNotification(string.Format("Initial Termination Time: {0} (Current Time: {1})", SubTermTime, System.DateTime.UtcNow)); SubscriptionManagerClient = OnvifServices.GetSubscriptionManagerClient(SubRenewUri, deviceTimeOffset, username, password); } catch (Exception e) { OnNotification(string.Format("{0} Unable to subscribe to events on device [{1}]", System.DateTime.UtcNow, uri)); // ip)); } }
public void CreateSubscriptionInvalidTopicExpressionTest() { EndpointReferenceType endpointReference = null; RunTest <object>( () => { return(null); }, () => { string invalidTopic = GetInvalidTopic(); XmlElement[] any = null; DateTime currentTime; DateTime?terminationTime; FilterType filter = new FilterType(); XmlDocument doc = new XmlDocument(); XmlElement topicElement = doc.CreateTopicElement(); topicElement.InnerText = invalidTopic; filter.Any = new XmlElement[] { topicElement }; EnsureEventPortTypeClientCreated(); RunStep( () => { endpointReference = _eventPortTypeClient.CreatePullPointSubscription(filter, "PT10S", null, ref any, out currentTime, out terminationTime); }, "Create Pull Point Subscription - negative test", new ValidateTypeFault(ValidateInvalidTopicFilterFault)); }, (o) => { if (endpointReference != null) { if (endpointReference.Address != null) { CreateSubscriptionManagerClient(endpointReference); } ReleaseSubscriptionManager(10000); } }); }
public void Bye(ref EndpointReferenceType EndpointReference, string Types, ScopesType Scopes, string XAddrs, uint MetadataVersion, ref System.Xml.XmlElement[] Any, ref System.Xml.XmlAttribute[] AnyAttr) { ByeRequest inValue = new ByeRequest(); inValue.EndpointReference = EndpointReference; inValue.Types = Types; inValue.Scopes = Scopes; inValue.XAddrs = XAddrs; inValue.MetadataVersion = MetadataVersion; inValue.Any = Any; inValue.AnyAttr = AnyAttr; ByeResponse retVal = ((RemoteDiscoveryPort)(this)).Bye(inValue); EndpointReference = retVal.EndpointReference; Any = retVal.Any; AnyAttr = retVal.AnyAttr; }
public void pull(string ip, int port) { EventPortTypeClient eptc = OnvifServices.GetEventClient(ip, port); // 2. CreatePullPointSubscription FilterType filter = new FilterType(); DateTime currentTime; XmlElement[] xml = null; DateTime? termTime; List <MessageHeader> lstHeaders = new List <MessageHeader>() { }; EndpointReferenceType ert = eptc.CreatePullPointSubscription( filter, "PT15S", new CreatePullPointSubscriptionSubscriptionPolicy(), ref xml, out currentTime, out termTime ); listBox1.Items.Add(ert.Address.Value); if ((ert.ReferenceParameters != null) && (ert.ReferenceParameters.Any != null)) { foreach (System.Xml.XmlElement oXml in ert.ReferenceParameters.Any) { string strName = oXml.LocalName; string strNS = oXml.NamespaceURI; string strValue = oXml.InnerXml; lstHeaders.Add(MessageHeader.CreateHeader(strName, strNS, strValue, true)); } } //PullPointSubscriptionClient ppsc = OnvifServices.GetPullPointSubClient(ip, port); //NotificationMessageHolderType[] nmht; //DateTime terminationTime; //XmlDocument doc = new XmlDocument(); //doc.CreateElement("test"); //XmlElement[] pullMsgXml = { doc.CreateElement("test") }; //ppsc.PullMessages("PT5S", 5, any, out terminationTime, out nmht); }
public void UnsubscribeTest() { bool unsubscribed = true; RunTest <object>( () => { return(null); }, () => { EnsureEventPortTypeClientCreated(); EndpointReferenceType endpoint = CreateStandardSubscription(); if (endpoint == null) { return; } Unsubscribe request = new Unsubscribe(); UnsubscribeResponse unsubscribeResponse = Unsubscribe(request); unsubscribed = true; Renew renew = new Renew(); renew.TerminationTime = "PT10S"; RunStep( () => { _subscriptionManagerClient.Renew(renew); unsubscribed = false; }, "Renew - negative test", new ValidateTypeFault(ValidateResourseUnknownFault)); }, (o) => { if (!unsubscribed) { BeginStep("Wait until subscription expires"); Sleep(10000); StepPassed(); } }); }
/// <summary> /// Gets URL upon calling which the required study data can be retrieved. /// </summary> /// <param name="studyUIDs">List of UIDs for the studies to be retrieved</param> /// <param name="endPointUrl">URL of the NBIA Data Service to query. This is NOT the Data Transfer URL!</param> /// <returns>URL that returns zip file with the studies</returns> public string retrieveStudyURL(string[] studyUIDs, string endPointUrl) { TransferServiceContextService.DataTransferDescriptor dtd; using (NCIACoreServicePortTypeClient proxy = new NCIACoreServicePortTypeClient("NCIACoreServicePortTypePort", endPointUrl)) { try { TransferServiceContextReference tras = proxy.retrieveDicomDataByStudyUIDs(studyUIDs); // new TransferServiceContextReference(); EndpointReferenceType endPoint = tras.EndpointReference; // new EndpointReferenceType(); AddressHeader[] ah = new AddressHeader[endPoint.ReferenceProperties.Any.Length]; for (int lcv = 0; lcv < ah.Length; lcv++) { XmlElement refProp = endPoint.ReferenceProperties.Any[lcv]; ah[lcv] = AddressHeader.CreateAddressHeader(refProp.LocalName, refProp.NamespaceURI, refProp.InnerText); } EndpointAddress ea = new EndpointAddress(new Uri(endPoint.Address.Value), ah); // create binding by hand so we don't have to associate a config file with a dll BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.None); binding.Name = "TransferServiceContextPortTypePort"; TransferServiceContextPortTypeClient transProxy = new TransferServiceContextPortTypeClient(binding, ea); dtd = transProxy.getDataTransferDescriptor(); } catch (System.Net.WebException ex) { System.Console.WriteLine(ex.Message); //never gets here throw new GridServicerException("Error querying NCIA Grid", ex); } catch (Exception e) { System.Console.WriteLine(e.Message); //never gets here throw new GridServicerException("Error retrieving from NCIA Grid", e); } } if (string.IsNullOrEmpty(dtd.url)) { return(dtd.url); } else { return(null); } }
public void CreateSubscriptionInvalidMessageContentFilterTest() { EndpointReferenceType endpointReference = null; RunTest <object>( () => { return(null); }, () => { XmlElement[] any = null; DateTime currentTime; DateTime?terminationTime; FilterInfo filterInfo = GetInvalidMessageContentFilter(); Assert(filterInfo != null, "Failed to create filter for test", "Check if a filter has been created"); EnsureEventPortTypeClientCreated(); RunStep( () => { endpointReference = _eventPortTypeClient.CreatePullPointSubscription(filterInfo.Filter, "PT10S", null, ref any, out currentTime, out terminationTime); }, "Create Pull Point Subscription - negative test", new ValidateTypeFault(ValidateInvalidMessageContentFilterFault)); }, (o) => { if (endpointReference != null) { if (endpointReference.Address != null) { CreateSubscriptionManagerClient(endpointReference); } ReleaseSubscriptionManager(10000); } }); }
private EventPortType CreatEeventPortTypeFake() { var endPointRefType = new EndpointReferenceType { Address = new AttributedURIType { Value = "http://127.0.0.1" } }; var response = new CreatePullPointSubscriptionResponse(endPointRefType, new System.DateTime(), null, null); var eventPortTypeMock = new Mock <EventPortType>(); eventPortTypeMock.Setup( x => x.CreatePullPointSubscriptionAsync(It.IsNotNull <CreatePullPointSubscriptionRequest>())). Returns(Task.FromResult(response)); return(eventPortTypeMock.Object); }
public void Subscribe(string ip, int port) { EventPortTypeClient eptc = OnvifServices.GetEventClient(ip, port); string localIP = GetLocalIp(); // "172.16.5.111"; // Producer client NotificationProducerClient npc = OnvifServices.GetNotificationProducerClient(ip, port); npc.Endpoint.Address = eptc.Endpoint.Address; Subscribe s = new Subscribe(); // Consumer reference tells the device where to Post messages back to (the client) EndpointReferenceType clientEndpoint = new EndpointReferenceType() { Address = new AttributedURIType() { Value = string.Format("http://{0}:8080/subscription-1", localIP) } }; s.ConsumerReference = clientEndpoint; s.InitialTerminationTime = "PT60S"; SubscribeResponse sr = npc.Subscribe(s); // Store the subscription URI for use in Renew SubRenewUri = sr.SubscriptionReference.Address.Value; // Start timer to periodically check if a Renew request needs to be issued // Use PC time for timer in case camera time doesn't match PC time // This works fine because the renew command issues a relative time (i.e. PT60S) so PC/Camera mismatch doesn't matter SubTermTime = DateTime.UtcNow.AddSeconds(50); // sr.TerminationTime; SubRenewTimer.Start(); SubRenewTimer.Interval = 1000; SubRenewTimer.Tick += SubRenewTimer_Tick; listBox1.Items.Add(string.Format("Initial Termination Time: {0} (Current Time: {1})", SubTermTime, DateTime.UtcNow)); SubscriptionManagerClient = OnvifServices.GetSubscriptionManagerClient(SubRenewUri); // oAux1.Address.Value); }
void CommonDoorPropertyEventTest(Func <DoorInfo, bool> doorCapabilitiesTest, TopicInfo topicInfo, Action <XmlElement, TopicInfo> validateTopic, ValidateMessageFunction validateMessageFunction, Func <DoorState, string> stateValueSelector, string stateSimpleItemName) { EndpointReferenceType subscriptionReference = null; System.DateTime subscribeStarted = System.DateTime.MaxValue; int timeout = 60; RunTest( () => { //3. Get complete list of doors from the DUT (see Annex A.1). //4. Check that there is at least one Door with [DOOR CAPABILITIES TEST]= “true”. // Otherwise skip other steps and go to the next test. List <DoorInfo> fullList = GetDoorInfoList(); List <DoorInfo> doors = fullList.Where(D => doorCapabilitiesTest(D)).ToList(); if (doors.Count == 0) { LogTestEvent("No Doors with required Capabilities found, exit the test" + Environment.NewLine); return; } //5. ONVIF Client will invoke GetEventPropertiesRequest message to retrieve // all events supported by the DUT. //6. Verify the GetEventPropertiesResponse message from the DUT. //7. Check if there is an event with Topic [TOPIC]. If there is no event with // such Topic skip other steps, fail the test and go to the next test. XmlElement topicElement = GetTopicElement(topicInfo); // if only one topic should be checked //ValidateTopicXml(topicElement); Assert(topicElement != null, string.Format("Topic {0} not supported", topicInfo.GetDescription()), "Check that the event topic is supported"); //8. Check that this event is a Property event (MessageDescription.IsProperty="true"). //9. Check that this event contains Source.SimpleItemDescription item with // Name="DoorToken" and Type="pt:ReferenceToken". //10. Check that this event contains Data.SimpleItemDescription item with Name=[NAME] // and Type=[TYPE]. XmlElement messageDescription = topicElement.GetMessageDescription(); validateTopic(messageDescription, topicInfo); FilterInfo filter = CreateFilter(topicInfo, messageDescription); Dictionary <NotificationMessageHolderType, XmlElement> notifications = new Dictionary <NotificationMessageHolderType, XmlElement>(); //11. 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. //12. Verify that the DUT sends a SubscribeResponse message. //13. Verify that DUT sends Notify message(s) //14. Verify received Notify messages (correct value for UTC time, TopicExpression and wsnt:Message). //15. Verify that TopicExpression is equal to tns1:DoorControl/DoorMode for all received Notify messages. //16. Verify that each notification contains Source.SimpleItem item with Name="DoorToken" and Value is equal to one of existing Door Tokens (e.g. complete list of doors contains Door with the same token). Verify that there are Notification messages for each Door. //17. Verify that each notification contains Data.SimpleItem item with Name="DoorMode" and Value with type is equal to tdc:DoorMode. //18. Verify that Notify PropertyOperation="Initialized". subscriptionReference = ReceiveMessages(filter.Filter, timeout, new Action(() => { }), fullList.Count, notifications, out subscribeStarted); EntityListInfo <DoorInfo> data = new EntityListInfo <DoorInfo>(); data.FullList = fullList; data.FilteredList = doors; ValidateMessages(notifications, topicInfo, OnvifMessage.INITIALIZED, data, validateMessageFunction); Dictionary <string, NotificationMessageHolderType> doorsMessages = new Dictionary <string, NotificationMessageHolderType>(); ValidateMessagesSet(notifications.Keys, doors, doorsMessages); //19. ONVIF Client will invoke GetDoorStateRequest message for each Door // with corresponding tokens. //20. Verify the GetDoorStateResponse messages from the DUT. Verify that // Data.SimpleItem item with Name=[SIMPLEITEMNAME] from Notification message has the // same value with [ELEMENT SELECTION] elements from corresponding GetDoorStateResponse // messages for each Door. foreach (string doorToken in doorsMessages.Keys) { DoorState state = GetDoorState(doorToken); string expectedState = stateValueSelector(state); XmlElement dataElement = doorsMessages[doorToken].Message.GetMessageData(); Dictionary <string, string> dataSimpleItems = dataElement.GetMessageElementSimpleItems(); string notificationState = dataSimpleItems[stateSimpleItemName]; Assert(expectedState == notificationState, string.Format("State is different ({0} in GetDoorStateResponse, {1} in Notification)", expectedState, notificationState), "Check that state is the same in Notification and in GetDoorStateResponse"); } }, () => { ReleaseSubscription(subscribeStarted, subscriptionReference, timeout); }); }
void CommonDoorPropertyEventStateChangeTest(Func <DoorInfo, bool> doorCapabilitiesTest, TopicInfo topicInfo, ValidateMessageFunction validateMessageFunction) { EndpointReferenceType subscriptionReference = null; System.DateTime subscribeStarted = System.DateTime.MaxValue; int timeout = 60; RunTest( () => { //3. Get complete list of doors from the DUT (see Annex A.1). List <DoorInfo> fullDoorInfosList = GetDoorInfoList(); //4. Check that there is at least one Door with Capabilities.[CAPABILITIES FOR THE TEST]= “true”. // Otherwise skip other steps and go to the next test. List <DoorInfo> doorsList = null; if (doorCapabilitiesTest != null) { doorsList = fullDoorInfosList.Where(A => doorCapabilitiesTest(A)).ToList(); if (doorsList.Count == 0) { LogTestEvent("No Doors with required Capabilities found, exit the test" + Environment.NewLine); return; } } else { doorsList = fullDoorInfosList; } //5. ONVIF Client will select one random Door (token = Token1) with // Capabilities.DoorMonitor= “true”. // ToDo: may be change it to really random selection DoorInfo selectedDoor = doorsList[0]; // filter for current test TestTool.Proxies.Event.FilterType filter = CreateSubscriptionFilter(topicInfo); //6. ONVIF Client will invoke SubscribeRequest message with tns1:DoorControl/DoorPhysicalState 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. //8. Test Operator will invoke change of DoorPhysicalState property for Door with token = Token1. //9. Verify that DUT sends Notify message. string message = string.Format("{0} event is expected \r\n for the Door with token={{0}}", topicInfo.GetDescription()); DoorSelectionData data = new DoorSelectionData(); data.SelectedToken = selectedDoor.token; data.MessageTemplate = message; data.Doors = doorsList.Select( D => new DoorSelectionData.DoorShortInfo() { Token = D.token, Name = D.Name }).ToList(); Dictionary <NotificationMessageHolderType, XmlElement> notifications = new Dictionary <NotificationMessageHolderType, XmlElement>(); try { subscriptionReference = ReceiveMessages(filter, timeout, new Action(() => { _operator.ShowDoorSelectionMessage(data); }), 1, (n) => CheckMessagePropertyOperation(n, OnvifMessage.CHANGED), notifications, out subscribeStarted); } finally { _operator.HideDoorSelectionMessage(); } Assert(notifications.Count > 0, string.Format("Message with PropertyOperation='Changed' for the door with token='{0}' has not been received", data.SelectedToken), "Check that the message for selected door has been received"); //10. Verify received Notify messages (correct value for UTC time, TopicExpression and // wsnt:Message). //11. Verify that TopicExpression is equal to [TOPIC] for // received Notify message. //12. Verify that notification contains Source.SimpleItem item with Name="DoorToken" // and Value= “Token1”. //13. Verify that notification contains Data.SimpleItem item with Name=[ITEMNAME] and // Value with type is equal to [TYPE]. BeginStep("Validate messages"); XmlNamespaceManager manager = CreateNamespaceManager(notifications.First().Value.OwnerDocument); StringBuilder logger = new StringBuilder(); bool ok = true; MessageCheckSettings settings = new MessageCheckSettings(); settings.Data = data.SelectedToken; settings.ExpectedTopic = topicInfo; settings.RawMessageElements = notifications; settings.NamespaceManager = manager; foreach (NotificationMessageHolderType m in notifications.Keys) { bool local = validateMessageFunction(m, settings, logger); ok = ok && local; } if (!ok) { throw new AssertException(logger.ToStringTrimNewLine()); } StepPassed(); }, () => { _operator.HideDoorSelectionMessage(); ReleaseSubscription(subscribeStarted, subscriptionReference, timeout); }); }
void CommonDoorOperationEventTest( Func<DoorInfo, bool> doorCapabilitiesTest, string operationName, TopicInfo topic, ValidateMessageFunction validateMessage, Action<string> doorOperation, string stateItemName, string expectedState, bool equal) { EndpointReferenceType subscriptionReference = null; System.DateTime subscribeStarted = System.DateTime.MaxValue; int timeout = _eventSubscriptionTimeout; RunTest( () => { // Get full list List<DoorInfo> fullDoorsList = GetDoorInfoList(); // Check if there are Doors with required properties List<DoorInfo> doorInfos = fullDoorsList.Where(doorCapabilitiesTest).ToList(); // if there are no Doors with required capabilities, skip other steps. if (doorInfos.Count == 0) { LogTestEvent("No Doors with required Capabilities found, exit the test."); return; } // Select one Door. DoorInfo selectedDoor = doorInfos[0]; string selectedToken = selectedDoor.token; List<DoorSelectionData.DoorShortInfo> tokens = doorInfos.Select( D => new DoorSelectionData.DoorShortInfo(){ Token = D.token, Name=D.Name}).ToList(); string message = string.Format("Put the Door with token '{{0}}' into state which allows '{0}' operation", operationName); DoorSelectionData data = new 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)); EnsureEventPortTypeClientCreated(); TestTool.Proxies.Event.FilterType filter = CreateSubscriptionFilter(topic); // Subscribe Utils.NotifyCollectingServer eventServer = new TestTool.Tests.TestCases.Utils.NotifyCollectingServer(_nic); SetupNotifyServer2(eventServer); string notificationsUri = eventServer.GetNotificationUri(); System.DateTime localSubscribeStarted = System.DateTime.MaxValue; Func<NotificationMessageHolderType, bool> messageCheck = (n) => CheckDoorEventSource(n, selectedToken); { AutoResetEvent subscribedEvent = new AutoResetEvent(false); // collect "Initialized" messaged Action setSynchronizationPointAction = new Action( () => { StepPassed(); subscriptionReference = CreateSubscription(filter, timeout, notificationsUri, out localSubscribeStarted); subscribedEvent.Set(); }); BeginStep("Start listening"); // collect messages for all door infos Dictionary<Notify, byte[]> notifications = eventServer.CollectNotifications(setSynchronizationPointAction, _operationDelay, 1, messageCheck, subscribedEvent, _semaphore.StopEvent); subscribeStarted = localSubscribeStarted; Assert(notifications.Count > 0, string.Format("No notifications were received for Door with token='{0}'", selectedToken), "Check that the DUT sent expected notification(s)"); // Create raw elements list Dictionary<NotificationMessageHolderType, XmlElement> messages = GetRawElements(notifications); Dictionary<NotificationMessageHolderType, XmlElement> filtered = GetFilteredList(messages, messageCheck); // Validate messages ValidateMessages(filtered, topic, OnvifMessage.INITIALIZED, doorInfos, validateMessage); } { // Perform operation AutoResetEvent initializedEvent = new AutoResetEvent(false); Action initiationAction = new Action(() => { doorOperation(selectedToken); initializedEvent.Set(); }); // Check state change message Dictionary<Notify, byte[]> notifications = eventServer.CollectNotifications(initiationAction, _operationDelay, 1, messageCheck, initializedEvent, _semaphore.StopEvent); Assert(notifications.Count > 0, string.Format("No notifications were received for Door with token='{0}'", selectedToken), "Check that the DUT sent notification(s)"); // Create raw elements list Dictionary<NotificationMessageHolderType, XmlElement> messages = GetRawElements(notifications); Dictionary<NotificationMessageHolderType, XmlElement> filtered = GetFilteredList(messages, messageCheck); // validate state changed message ValidateMessages(filtered, topic, OnvifMessage.CHANGED, selectedToken, validateMessage); BeginStep("Validate current State"); Dictionary<string, string> dataSimpleItems = messages.Keys.First().Message.GetMessageDataSimpleItems(); if (equal) { if (dataSimpleItems[stateItemName] != expectedState) { throw new AssertException(string.Format("{0} is incorrect: expected {1}, actual {2}", stateItemName, expectedState, dataSimpleItems[stateItemName])); } } else { if (dataSimpleItems[stateItemName] == expectedState) { throw new AssertException(string.Format("{0} is incorrect: must be different from {1}", stateItemName, dataSimpleItems[stateItemName])); } } StepPassed(); } RemoveHandlers2(eventServer); }, () => { _operator.HideMessage(); ReleaseSubscription(subscribeStarted, subscriptionReference, timeout); }); }
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); }); }
void SubscribeTestWithTransformation(XmlTransformation transformation) { EndpointReferenceType subscriptionReference = null; int terminationTime = 10; RunTest <object>( () => null, () => { EnsureNotificationProducerClientCreated(); FaultException exc11, exc12; Subscribe(out exc11, out exc12, ref terminationTime); XmlNamespacesTransformer transformer = new XmlNamespacesTransformer(transformation); EnsureNotificationProducerClientCreated(); SetBreakingBehaviour(_notificationProducerClient.Endpoint, transformer); FaultException exc21, exc22; Subscribe(out exc21, out exc22, ref terminationTime); BeginStep("Check if reaction to request was the same"); bool ok = true; StringBuilder dump = new StringBuilder(); Action <FaultException, FaultException, string> compareFaults = new Action <FaultException, FaultException, string>( (exc1, exc2, descr) => { if (exc1 == null) { if (exc2 == null) { // ok } else { ok = false; dump.AppendFormat( "Fault has been received in response to {0} request only when sending without transformation{1}", descr, Environment.NewLine); } } else { if (exc2 == null) { ok = false; dump.AppendFormat( "Fault has been received in response to {0} request only when sending with transformation{1}", descr, Environment.NewLine); } else { // Both not null. // Compare types if (exc1.GetType().GUID != exc2.GetType().GUID) { ok = false; dump.AppendFormat( "Faults received in response to {0} request have different types{1}", descr, Environment.NewLine); } } } } ); compareFaults(exc11, exc21, "first"); FaultException <UnacceptableInitialTerminationTimeFaultType> invalidTerminationTimeFault1 = exc11 as FaultException <UnacceptableInitialTerminationTimeFaultType>; FaultException <UnacceptableInitialTerminationTimeFaultType> invalidTerminationTimeFault2 = exc21 as FaultException <UnacceptableInitialTerminationTimeFaultType>; if (invalidTerminationTimeFault1 != null && invalidTerminationTimeFault2 != null) { compareFaults(exc12, exc22, "second"); } if (!ok) { throw new AssertException(dump.ToStringTrimNewLine()); } StepPassed(); }, (o) => { ResetBreakingBehaviour(_notificationProducerClient.Endpoint); if (subscriptionReference != null) { if (_subscriptionManagerClient == null) { CreateSubscriptionManagerClient(subscriptionReference); } ReleaseSubscriptionManager(terminationTime * 1000); } }); }
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); } }
public EndpointReferenceBehaviour(EndpointReferenceType endpointReference) { _endpointReference = endpointReference; }