コード例 #1
0
        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);
            }
        }
コード例 #2
0
ファイル: DPWSDevice.cs プロジェクト: teco-kit/dpwsGW
        protected void UnsubscribeMsg(String subscriptionId)
        {
            SubscriptionManagerClient subscriptionManager = new SubscriptionManagerClient("WSEventingUnsubscribe");

            subscriptionManager.Endpoint.Address = endpointAddress;
            subscriptionManager.UnsubscribeOp(subscriptionId, new Unsubscribe());
        }
コード例 #3
0
        public async Task AuthorizeSubscription_OK_Succesful()
        {
            int      subscriptionId = 234234;
            string   password       = "******";
            int      amount         = 20000;
            string   orderId        = "234234234";
            Currency currency       = Currency.DKK;

            var mockHttp    = new MockHttpMessageHandler();
            var xmlResponse = @"<?xml version=""1.0"" encoding=""utf-8""?>
<AuthorizationResult xmlns=""http://gw.freepay.dk/WebServices/Public/SubscriptionManager"">
  <IsSuccess>true</IsSuccess>
  <TransactionID>234234234</TransactionID>
  <ErrorCode>0</ErrorCode>
</AuthorizationResult>
";

            mockHttp.When(Urls.GetAuthorizeSubscriptionUrl(subscriptionId, password, amount, orderId, (int)currency))
            .Respond("text/xml", xmlResponse);

            var httpClient = new HttpClient(mockHttp)
            {
                BaseAddress = new Uri("https://gw.freepay.dk")
            };
            var client = new SubscriptionManagerClient(httpClient);
            var result = await client.AuthorizeSubscriptionAsync(subscriptionId, password, amount, orderId, currency);

            Assert.NotNull(result);
            Assert.AreEqual(true, result.IsSuccess);
            Assert.AreEqual(234234234, result.TransactionID);
            Assert.AreEqual(0, result.ErrorCode);
        }
コード例 #4
0
ファイル: UnitTest1.cs プロジェクト: trendsales/freepay-mock
 public async Task Test()
 {
     using (TestServer server = TestServer.Create <Startup>())
     {
         var client = new SubscriptionManagerClient();
         await client.AuthorizeSubscriptionAsync(123123, "password", 20000, "orderId", Currency.DKK);
     };
 }
コード例 #5
0
        public OnVif1Events(OnVifDevice onVifDevice) : base(onVifDevice)
        {
            //   m_ErrorMessage = "";
            m_PullPointResponse = null;
            //   m_onVifDevice = onVifDevice;
            m_EventPropertiesResponse = null;
            m_EventPortTypeClient     = null;

            m_PullPointSubscriptionClient = null;
            m_SubscriptionManagerClient   = null;
            //       m_initialised = false;
            m_subscriptionTerminationTime = TimeSpan.FromSeconds(20);
        }
コード例 #6
0
        /// <summary>
        /// Creates SubscriptionManager client using address passed.
        /// </summary>
        /// <param name="endpointReference">Service address.</param>
        /// <returns></returns>
        protected SubscriptionManagerClient CreateSubscriptionManagerClient(Proxies.Event.EndpointReferenceType endpointReference)
        {
            Binding 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);
        }
コード例 #7
0
        /// <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));
            }
        }
コード例 #8
0
        //public static SubscriptionManagerClient GetSubscriptionManagerClient(string ip, int port, List<MessageHeader> headers)
        public static SubscriptionManagerClient GetSubscriptionManagerClient(string uri) // string ip, int port, List<MessageHeader> headers)
        {
            EndpointAddress serviceAddress = new EndpointAddress(uri);                   // string.Format("http://{0}:{1}/onvif/event_service", ip, port));

            HttpTransportBindingElement httpBinding = new HttpTransportBindingElement();

            httpBinding.AuthenticationScheme = AuthenticationSchemes.Digest;

            var messageElement = new TextMessageEncodingBindingElement();

            messageElement.MessageVersion = MessageVersion.CreateVersion(EnvelopeVersion.Soap12, AddressingVersion.None);
            CustomBinding bind = new CustomBinding(messageElement, httpBinding);

            SubscriptionManagerClient client = new SubscriptionManagerClient(bind, serviceAddress);

            return(client);
        }
コード例 #9
0
        public async Task QuerySubscription_Ok_Success()
        {
            int    subscriptionId = 234234;
            string password       = "******";

            var mockHttp        = new MockHttpMessageHandler();
            var mockXmlResponse = @"<?xml version=""1.0"" encoding=""utf-8""?>
<SubscriptionView xmlns=""http://gw.freepay.dk/WebServices/Public/SubscriptionManager"">
  <SubscriptionID>234234</SubscriptionID>
  <MerchantID>5345</MerchantID>
  <MerchantNumber>34534</MerchantNumber>
  <DateCreated>2016-12-12T15:32:12</DateCreated>
  <Currency>208</Currency>
  <OrderID>3453453</OrderID>
  <CardType>VisaDankort</CardType>
  <SourceIP>195.234.12.4</SourceIP>
  <PANHash>B83EB70F-36BC-48AB-A5E0-DCE51A998A7A</PANHash>
  <ExpiryDate>2016-12-12</ExpiryDate>
  <Acquirer>NetsTeller</Acquirer>
</SubscriptionView>
";

            mockHttp.When(Urls.GetQuerySubscriptionUrl(subscriptionId, password))
            .Respond("text/xml", mockXmlResponse);

            var httpClient = new HttpClient(mockHttp)
            {
                BaseAddress = new Uri("https://gw.freepay.dk")
            };
            ISubscriptionManagerClient client = new SubscriptionManagerClient(httpClient);
            var result = await client.QuerySubscriptionAsync(subscriptionId, password);

            Assert.NotNull(result);
            Assert.AreEqual(234234, result.SubscriptionID);
            Assert.AreEqual(5345, result.MerchantID);
            Assert.AreEqual(34534, result.MerchantNumber);
            Assert.AreEqual(new DateTime(2016, 12, 12, 15, 32, 12), result.DateCreated);
            Assert.AreEqual(208, result.Currency);
            Assert.AreEqual("3453453", result.OrderID);
            Assert.AreEqual("VisaDankort", result.CardType);
            Assert.AreEqual("195.234.12.4", result.SourceIP);
            Assert.AreEqual("B83EB70F-36BC-48AB-A5E0-DCE51A998A7A", result.PANHash);
            Assert.AreEqual(new DateTime(2016, 12, 12), result.ExpiryDate);
            Assert.AreEqual("NetsTeller", result.Acquirer);
        }
コード例 #10
0
ファイル: EventForm.cs プロジェクト: thephez/onvif-interface
        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);
        }
コード例 #11
0
        public static SubscriptionManagerClient GetSubscriptionManagerClient(string uri, double deviceTimeOffset, string username = "", string password = "") // string ip, int port, List<MessageHeader> headers)
        {
            EndpointAddress serviceAddress = new EndpointAddress(uri);                                                                                        // string.Format("http://{0}:{1}/onvif/event_service", ip, port));

            HttpTransportBindingElement httpBinding = new HttpTransportBindingElement();

            httpBinding.AuthenticationScheme = AuthenticationSchemes.Digest;

            var messageElement = new TextMessageEncodingBindingElement();

            messageElement.MessageVersion = MessageVersion.CreateVersion(EnvelopeVersion.Soap12, AddressingVersion.WSAddressing10);
            CustomBinding bind = new CustomBinding(messageElement, httpBinding);

            SubscriptionManagerClient client = new SubscriptionManagerClient(bind, serviceAddress);

            if (username != string.Empty)
            {
                // Handles adding of SOAP Security header containing User Token (user, nonce, pwd digest)
                PasswordDigestBehavior behavior = new PasswordDigestBehavior(username, password, deviceTimeOffset);
                client.Endpoint.Behaviors.Add(behavior);
            }

            return(client);
        }
コード例 #12
0
        private static void subscribeToLDC(EndpointAddress hostedEndPoint)
        {
            Console.WriteLine("Starting subscription event...");

            //  endpointAddress = StartDiscoveryProcess(false);
            if (hostedEndPoint != null)
            {
                //Get Metadata of the address.
                //  EndpointAddress hostedEndPoint = GetMetaData(endpointAddress);

                InstanceContext ithis = new InstanceContext(new DiscoveryCallBack());

                using (AccelerationServiceClient client = new AccelerationServiceClient(ithis))
                {
                    client.Endpoint.Address = hostedEndPoint;
                    client.Open();

                    EndpointAddress   callbackEndpoint = client.InnerDuplexChannel.LocalAddress;
                    EventSourceClient eventSource      = new EventSourceClient(ithis, "WSEventing");
                    eventSource.Endpoint.Address = hostedEndPoint;
                    eventSource.Open();

                    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("http://www.teco.edu/AccelerationService/AccelerationServiceEventOut");

                    SubscribeResponse subscription;
                    try
                    {
                        Console.WriteLine("Subscribing to the event...");
                        //Console.ReadLine();
                        subscription = eventSource.SubscribeOp(s);
                    }
                    catch (TimeoutException t)
                    {
                        Console.WriteLine("Error reply time out: {0}!!", t.Message);
                        return;
                    }

                    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;
                        }
                    }

                    Console.WriteLine("Got subscription: {0}", subscriptionId);

                    Console.WriteLine("Press <ENTER> to unsubscribe.");
                    Console.ReadLine();

                    Console.WriteLine("Unsubscribing {0}", subscriptionId);
                    SubscriptionManagerClient subscriptionManager = new SubscriptionManagerClient("WSEventingUnsubscribe");
                    subscriptionManager.Endpoint.Address = hostedEndPoint;
                    subscriptionManager.UnsubscribeOp(subscriptionId, new Unsubscribe());
                    client.Close();
                }
            }
        }
コード例 #13
0
        /// <summary>
        /// Initial point of the program.
        /// </summary>
        /// <param name="args">Arguments.</param>
        public static void Main(string[] args)
        {
            // Check if the console application will continually run.
            bool continuousRun = false;

            if (args.Length > 0 && args[0].ToLower() == "-o")
            {
                continuousRun = (args.Length > 1 && args[1].ToLower() == "continous");
            }

            // Write the header.
            Console.WriteLine(
                @"ABB  DECRC - SERVICE and usability LAB
Advanced Identification and Labeling for Service
DECRC 2009
DPWS Discovery Project,
Contact N. L. Fantana ([email protected])

 * Please, start Gateway before select the options.
   Additionally a running dummynode is required when using manual discovery (Option D) 
");
            // Go always into the menu, until the user selects to exit.
            while (true)
            {
                // Check the option.
                ConsoleKeyInfo ki = new ConsoleKeyInfo();
                Console.Write(
                    @"Select one option: 
   A-Wait for Announcement;
   C-Configuration Sample;
   D-Discover the service;
   I-Invoke the service;
   S-Eventing Subscribe; 
   P-Performance Test; 
   E-Exit
Select: ");
                ki = Console.ReadKey();
                Console.WriteLine();


                switch (ki.Key)
                {
                // Start the announcement procedure.
                case ConsoleKey.A:
                    StartAnouncementProcess();
                    break;

                // Call the Configuration Method.
                case ConsoleKey.C:
                    if (hostedEndPoint != null)
                    {
                        ConfigureNodes(hostedEndPoint, false);
                    }
                    break;

                // Call the GetValues method (with or without showing information on the console).
                case ConsoleKey.D:
                    // Finds a valid Endpoint for a Node.
                    endpointAddress = StartDiscoveryProcess(false);
                    if (endpointAddress != null)
                    {
                        // Get Metadata and the endpoint of the service.
                        hostedEndPoint = GetMetaData(endpointAddress);

                        // Check if the invokation of the service will be called again.
                    }
                    // Kill the current processes.
                    if (UsbBridgeProcess != null)
                    {
                        UsbBridgeProcess.Kill();
                    }
                    if (SSimpDevice != null)
                    {
                        SSimpDevice.Kill();
                    }

                    break;

                case ConsoleKey.I:
                    if (hostedEndPoint != null)
                    {
                        //Invoke the service to get the values.
                        InvokeService(hostedEndPoint, false);
                    }
                    break;

                // Make a performance test.
                case ConsoleKey.P:
                    // endpointAddress = StartDiscoveryProcess(false);
                    if (hostedEndPoint != null)
                    {
                        // Get Metadata and the endpoint of the service.
                        //EndpointAddress hostedEndPoint = GetMetaData(endpointAddress);

                        bool runAgainPerformance = true;
                        while (runAgainPerformance)
                        {
                            runAgainPerformance = false;

                            string valueStr = string.Empty;
                            int    quantity = 0;
                            int    timeWait = -1;

                            // Check the quantity of samples to try the performance test.
                            while (!int.TryParse(valueStr, out quantity))
                            {
                                Console.Write("Select the quantity of samples (C-Cancel): ");
                                valueStr = Console.ReadLine();
                                if (valueStr == "C" || valueStr == "c")
                                {
                                    break;
                                }
                            }
                            if (quantity <= 0)
                            {
                                break;
                            }

                            // Get the time to wait between each sample invoke.
                            valueStr = string.Empty;
                            while (!int.TryParse(valueStr, out timeWait))
                            {
                                Console.Write("Select the time to wait between samples in miliseconds (C-Cancel): ");
                                valueStr = Console.ReadLine();
                                if (valueStr == "C" || valueStr == "c")
                                {
                                    break;
                                }
                            }
                            if (timeWait < 0)
                            {
                                break;
                            }

                            Console.Write("Reading Values. This may take some time...");
                            System.Diagnostics.Stopwatch stp1 = new System.Diagnostics.Stopwatch();
                            stp1.Start();
                            for (int i = 0; i < quantity; i++)
                            {
                                // Invoke the service.
                                InvokeService(hostedEndPoint, true);
                                System.Threading.Thread.Sleep(timeWait);
                            }
                            stp1.Stop();
                            Console.WriteLine("done.");
                            Console.WriteLine("Time elapsed: {0}", stp1.ElapsedMilliseconds);

                            // Ask if the user wants to run again.
                            Console.Write("Run again (Y-yes, N-no)?");
                            ConsoleKeyInfo ky = Console.ReadKey();
                            if (ky.Key == ConsoleKey.Y)
                            {
                                runAgainPerformance = true;
                            }
                            Console.WriteLine();
                        }
                    }
                    // Kill the current processes.
                    if (UsbBridgeProcess != null)
                    {
                        UsbBridgeProcess.Kill();
                    }
                    if (SSimpDevice != null)
                    {
                        SSimpDevice.Kill();
                    }

                    break;

                // Initialize the Subcription event.
                case ConsoleKey.S:
                    Console.WriteLine("Starting subscription event...");

                    //  endpointAddress = StartDiscoveryProcess(false);
                    if (hostedEndPoint != null)
                    {
                        //Get Metadata of the address.
                        //  EndpointAddress hostedEndPoint = GetMetaData(endpointAddress);

                        InstanceContext ithis = new InstanceContext(new DiscoveryCallBack());



                        // Create a client
                        using (SensorValuesClient client = new SensorValuesClient(ithis))
                        {
                            client.Endpoint.Address = hostedEndPoint;
                            client.Open();

                            EndpointAddress   callbackEndpoint = client.InnerDuplexChannel.LocalAddress;
                            EventSourceClient eventSource      = new EventSourceClient(ithis, "WSEventing");
                            eventSource.Endpoint.Address = hostedEndPoint;
                            eventSource.Open();

                            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("http://www.teco.edu/SensorValues/SensorValuesEventOut");

                            SubscribeResponse subscription;
                            try
                            {
                                Console.WriteLine("Subscribing to the event...");
                                //Console.ReadLine();
                                subscription = eventSource.SubscribeOp(s);
                            }
                            catch (TimeoutException t)
                            {
                                Console.WriteLine("Error reply time out: {0}!!", t.Message);
                                hostedEndPoint = null;
                                return;
                            }
                            catch (EndpointNotFoundException e)
                            {
                                return;
                            }

                            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;
                                }
                            }

                            Console.WriteLine("Got subscription: {0}", subscriptionId);

                            Console.WriteLine("Press <ENTER> to unsubscribe.");
                            Console.ReadLine();

                            Console.WriteLine("Unsubscribing {0}", subscriptionId);
                            SubscriptionManagerClient subscriptionManager = new SubscriptionManagerClient("WSEventingUnsubscribe");
                            subscriptionManager.Endpoint.Address = hostedEndPoint;
                            subscriptionManager.UnsubscribeOp(subscriptionId, new Unsubscribe());
                            client.Close();
                        }
                    }

                    break;

                // Close the application.
                case ConsoleKey.E:
                    return;

                // Invalid key.
                default:
                    Console.WriteLine("Invalid value.");
                    break;
                }
            }
        }
コード例 #14
0
        void InvokeService(EndpointAddress endpointAddress)
        {
            InstanceContext ithis            = new InstanceContext(this);
            String          callbackEndpoint = "http://vs2010test/blub";


            // Create a client
            SensorValuesClient client = new SensorValuesClient(new InstanceContext(this));

            client.Endpoint.Address = endpointAddress;
            //    callbackEndpoint=client.InnerChannel.LocalAddress.Uri.AbsoluteUri;
            callbackEndpoint = client.InnerDuplexChannel.LocalAddress.Uri.AbsoluteUri;

            Console.WriteLine("Invoking at {0}", endpointAddress);

            // client.GetSensorValues(out accelleration,out audio,out light,out force,out temperature);
            SSimpSample response = client.GetSensorValues();

            Console.WriteLine("Got response: {0}", response);


            Console.WriteLine("Subscribing event {1} at {0}", endpointAddress, "http://www.teco.edu/SensorValues/SensorValuesEventOut");
            EventSourceClient eventSource = new EventSourceClient(ithis);

            eventSource.Endpoint.Address = endpointAddress;

            SubscribeOpRequest s = new SubscribeOpRequest();

            s.Subscribe = new Subscribe();

            (s.Subscribe.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;
                XmlRootAttribute notifyToElem = new XmlRootAttribute("NotifyTo");
                notifyToElem.Namespace = "http://schemas.xmlsoap.org/ws/2004/08/eventing";

                new XmlSerializer(notifyTo.GetType(), notifyToElem).Serialize(writer, notifyTo);
            }

            (s.Subscribe.Delivery.Any = new XmlElement[1])[0] =
                doc.DocumentElement;

            (s.Subscribe.Filter = new FilterType()).Dialect = "http://schemas.xmlsoap.org/ws/2006/02/devprof/Action";

            (s.Subscribe.Filter.Any = new System.Xml.XmlNode[1]) [0] =
                new System.Xml.XmlDocument().CreateTextNode("http://www.teco.edu/SensorValues/SensorValuesEventOut");

            SubscribeOpResponse subscription;

            try
            {
                Console.WriteLine("Press <ENTER> to subscribe.");
                Console.ReadLine();
                subscription = eventSource.SubscribeOp(s);
            }
            catch (TimeoutException t)
            {
                Console.WriteLine("Error reply time out: {0}!!", t.Message);
                return;
            }
            //  eventSource.Close();


            String subscriptionId = null;


            foreach (XmlNode xel in subscription.SubscribeResponse.SubscriptionManager.ReferenceParameters.Any)
            {
                if (xel.LocalName.Equals("Identifier") && xel.NamespaceURI.Equals("http://schemas.xmlsoap.org/ws/2004/08/eventing"))
                {
                    subscriptionId = xel.InnerText;
                }
            }

            Console.WriteLine("Got subscription: {0}", subscriptionId);

            Console.WriteLine("Press <ENTER> to unsubscribe.");
            Console.ReadLine();

            UnsubscribeOpRequest unsubscribe = new UnsubscribeOpRequest();

            unsubscribe.Identifier = subscriptionId;

            Console.WriteLine("Unsubscribing {0}", subscriptionId);
            SubscriptionManagerClient subscriptionManager = new SubscriptionManagerClient();

            subscriptionManager.Endpoint.Address = endpointAddress;
            subscriptionManager.UnsubscribeOp(unsubscribe);

            //Closing the client gracefully closes the connection and cleans up resources
            //client.Close();
        }
コード例 #15
0
        public override async Task <bool> InitalizeAsync()
        {
            if (this.m_onVifDevice.ServicesResponse == null)
            {
                bool b = await this.m_onVifDevice.InitalizeDeviceAsync();

                if (this.m_onVifDevice.ServicesResponse == null)
                {
                    return(false);
                }
            }

            try
            {
                foreach (var service in this.m_onVifDevice.ServicesResponse.Service)
                {
                    if (service.Namespace == "http://www.onvif.org/ver10/events/wsdl")
                    {
                        string serviceAdress = service.XAddr;

                        HttpTransportBindingElement httpBinding = new HttpTransportBindingElement();
                        httpBinding.AuthenticationScheme = AuthenticationSchemes.Digest;
                        var messageElement = new TextMessageEncodingBindingElement();
                        messageElement.MessageVersion = MessageVersion.CreateVersion(EnvelopeVersion.Soap12, AddressingVersion.WSAddressing10);
                        CustomBinding binding = new CustomBinding(messageElement, httpBinding);



                        /*
                         * this.m_EventPortTypeClient = new EventPortTypeClient(binding, new EndpointAddress($"http://{ this.m_onVifDevice.Hostname}/onvif/event_service"));
                         * this.m_EventPortTypeClient.Endpoint.EndpointBehaviors.Add(this.m_onVifDevice.GetPasswordDigestBehavior);
                         * CreatePullPointSubscriptionRequest request = new CreatePullPointSubscriptionRequest();
                         * request.InitialTerminationTime = "PT60S";
                         * request.SubscriptionPolicy = new CreatePullPointSubscriptionSubscriptionPolicy();
                         *
                         *
                         * m_PullPointResponse = await this.m_EventPortTypeClient.CreatePullPointSubscriptionAsync(request);
                         *
                         *
                         *
                         *
                         * PullMessagesRequest message = new PullMessagesRequest("PT1S", 1024, null);
                         *
                         * await m_PullPointSubscriptionClient.PullMessagesAsync(message);
                         *
                         * GetEventPropertiesRequest eventrequest = new GetEventPropertiesRequest();
                         * m_EventPropertiesResponse =await this.m_EventPortTypeClient.GetEventPropertiesAsync(eventrequest);
                         */
                        OnvifDevice.Capabilities response = await this.m_onVifDevice.GetDeviceCapabilitiesAsync();



                        NotificationConsumerClient consclient = new NotificationConsumerClient(binding, new EndpointAddress(serviceAdress));

                        consclient.Endpoint.EndpointBehaviors.Add(this.m_onVifDevice.GetPasswordDigestBehavior);
                        consclient.Endpoint.EndpointBehaviors.Add(this.m_onVifDevice.GetBasicBasicAuthBehaviour);

                        OnvifEvent10.Notify request = new OnvifEvent10.Notify();



                        //  await consclient.NotifyAsync(request);



                        //     await consclient.OpenAsync();

                        NotificationConsumerService _notificationConsumerService = new NotificationConsumerService();
                        //        _notificationConsumerService.NewNotification += _notificationConsumerService_NewNotification;
                        //       ServiceHost _notificationConsumerServiceHost = new ServiceHost(_notificationConsumerService, new Uri("http://localhost:8085/NotificationConsumerService"));
                        //       _notificationConsumerServiceHost.Open();


                        NotificationProducerClient client = new NotificationProducerClient(binding, new EndpointAddress(serviceAdress));
                        client.Endpoint.EndpointBehaviors.Add(this.m_onVifDevice.GetPasswordDigestBehavior);
                        client.Endpoint.EndpointBehaviors.Add(this.m_onVifDevice.GetBasicBasicAuthBehaviour);

                        var subScribe = new Subscribe()
                        {
                            ConsumerReference = new EndpointReferenceType
                            {
                                Address = new AttributedURIType {
                                    Value = consclient.Endpoint.Address.Uri.ToString()
                                },
                            }
                        };


                        subScribe.InitialTerminationTime = "PT2H";
                        SubscribeResponse1 resp = await client.SubscribeAsync(subScribe);



                        if ((response.Events != null) && response.Events.WSSubscriptionPolicySupport)
                        {
                            m_PullPointSubscriptionClient = new PullPointSubscriptionClient(binding, new EndpointAddress(serviceAdress));
                            m_SubscriptionManagerClient   = new SubscriptionManagerClient(binding, new EndpointAddress(serviceAdress));

                            m_PullPointSubscriptionClient.Endpoint.EndpointBehaviors.Add(this.m_onVifDevice.GetPasswordDigestBehavior);
                            m_PullPointSubscriptionClient.Endpoint.EndpointBehaviors.Add(this.m_onVifDevice.GetBasicBasicAuthBehaviour);
                            m_SubscriptionManagerClient.Endpoint.EndpointBehaviors.Add(this.m_onVifDevice.GetPasswordDigestBehavior);
                            m_SubscriptionManagerClient.Endpoint.EndpointBehaviors.Add(this.m_onVifDevice.GetBasicBasicAuthBehaviour);
                            return(true);
                        }
                        else
                        {
                            //    throw new DeviceEventReceiverException("Device doesn't support pull point subscription");
                        }


                        if ((response.Events != null) && response.Events.WSPullPointSupport)
                        {
                            m_PullPointSubscriptionClient = new PullPointSubscriptionClient(binding, new EndpointAddress(serviceAdress));
                            m_SubscriptionManagerClient   = new SubscriptionManagerClient(binding, new EndpointAddress(serviceAdress));

                            m_PullPointSubscriptionClient.Endpoint.EndpointBehaviors.Add(this.m_onVifDevice.GetPasswordDigestBehavior);
                            m_PullPointSubscriptionClient.Endpoint.EndpointBehaviors.Add(this.m_onVifDevice.GetBasicBasicAuthBehaviour);
                            m_SubscriptionManagerClient.Endpoint.EndpointBehaviors.Add(this.m_onVifDevice.GetPasswordDigestBehavior);
                            m_SubscriptionManagerClient.Endpoint.EndpointBehaviors.Add(this.m_onVifDevice.GetBasicBasicAuthBehaviour);
                            return(true);
                        }
                        else
                        {
                            throw new DeviceEventReceiverException("Device doesn't support pull point subscription");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                m_ErrorMessage = ex.Message;
                return(false);
            }

            return(m_initialised);
        }