public EventingServiceController(string serviceTransportAddress)
        {
            this.serviceTransportAddress = serviceTransportAddress;

            // Set this device property if you want to ignore this service notifications
            this.IgnoreRequestFromThisIP = false;

            // Assigning either a static or random endpoint address will
            // init the transport address of this client which we will use soon
            this.EndpointAddress = "urn:uuid:" + Guid.NewGuid();

            // Adding a event handler
            this.ServiceOperations.Add(new WsServiceOperation(c_namespaceUri, // namespace
                                                              "SimpleEvent")); // event (method) name

            // Subscribe to the event
            DpwsServiceType subscriptionType = new DpwsServiceType("SimpleEvent", c_namespaceUri);
            DpwsSubscribeRequest request = new DpwsSubscribeRequest(subscriptionType, // subscription type
                                                                    serviceTransportAddress, // event source address
                                                                    this.TransportAddress, // notify to address
                                                                    null, // expires
                                                                    null // event identifier
                                                                    );
               this.EventingClient.Subscribe(request);
        }
        /// <summary>
        /// Use to subscribe to a devices, hosted service event sources.
        /// </summary>
        /// <param name="subscriptionRequest">
        /// A DpwsSubscriptionRequest object containing the address of the service hosting the desired event,
        /// the address where the event is sent, an optional address where subscription end messages are sent,
        /// A subscription expiration (in duration format) and an optional user defined identifier.
        /// </param>
        /// <returns>
        /// A DpwsEventSubscription containing the the subscription managers address, the time when the subscription
        /// expires (duration) and optional reference parameters and properties. Per spec the
        /// sub mananger may assign a different duration value than that specified in the request.
        /// </returns>
        /// <exception cref="ArgumentNullException">If required subscription parameters are not set.</exception>
        public DpwsEventSubscription Subscribe(DpwsSubscribeRequest subscriptionRequest)
        {
            if ((subscriptionRequest.SubscriptionType == null) ||
                (subscriptionRequest.SubscriptionType.TypeName == null) ||
                (subscriptionRequest.SubscriptionType.NamespaceUri == null) ||
                (subscriptionRequest.EndpointAddress == null) ||
                (subscriptionRequest.NotifyTo == null) ||
                (subscriptionRequest.NotifyTo.Address == null))
            {
                throw new ArgumentNullException();
            }

            // Convert the address string to a Uri
            Uri serviceUri = null;

            try
            {
                serviceUri = subscriptionRequest.EndpointAddress;
                if (serviceUri.Scheme != "http")
                {
                    System.Ext.Console.Write("");
                    System.Ext.Console.Write("Invalid endpoint address. Must be a Uri. Http Uri schemes only.");
                    System.Ext.Console.Write("");
                    return(null);
                }
            }
            catch (Exception e)
            {
                System.Ext.Console.Write("");
                System.Ext.Console.Write(e.Message);
                System.Ext.Console.Write("");
                return(null);
            }

            // Performance debugging
            DebugTiming timeDebuger       = new DebugTiming();
            long        startTime         = timeDebuger.ResetStartTime("");
            WsMessage   subscribeResponse = null;

            // Build Subscribe Request
            using (XmlMemoryWriter xmlWriter = XmlMemoryWriter.Create())
            {
                WsWsaHeader header = new WsWsaHeader(
                    m_version.EventingNamespace + "/Subscribe",     // Action
                    null,                                           // RelatesTo
                    serviceUri.AbsoluteUri,                         // To
                    m_version.AnonymousUri,                         // ReplyTo
                    null, null);                                    // From, Any

                WsXmlNamespaces additionalPrefixes = new WsXmlNamespaces();
                additionalPrefixes.Add(new WsXmlNamespace("myPrefix", subscriptionRequest.SubscriptionType.NamespaceUri));

                WsMessage msg = new WsMessage(header, null, WsPrefix.Wsd | WsPrefix.Wse, additionalPrefixes, null);

                WsSoapMessageWriter smw = new WsSoapMessageWriter(m_version);
                String messageID        = smw.WriteSoapMessageStart(xmlWriter, msg);

                // Performance debuging
                timeDebuger.PrintElapsedTime("*****Write Header Took");

                // write body
                xmlWriter.WriteStartElement(WsNamespacePrefix.Wse, "Subscribe", null);

                // If EndTo is set write it
                if (subscriptionRequest.EndTo != null)
                {
                    WriteEndpointRef(xmlWriter, subscriptionRequest.EndTo, "EndTo");
                }

                // Add the delivery element and NotifyTo endpoint
                xmlWriter.WriteStartElement(WsNamespacePrefix.Wse, "Delivery", null);
                xmlWriter.WriteAttributeString("Mode", m_version.EventingNamespace + "/DeliveryModes/Push");

                // Writer the notify to endpoint
                WriteEndpointRef(xmlWriter, subscriptionRequest.NotifyTo, "NotifyTo");

                xmlWriter.WriteEndElement(); // End Delivery

                // Write Expiration time
                if (subscriptionRequest.Expires != null)
                {
                    xmlWriter.WriteStartElement(WsNamespacePrefix.Wse, "Expires", null);
                    xmlWriter.WriteString(subscriptionRequest.Expires.DurationString);
                    xmlWriter.WriteEndElement(); // End Expires
                }

                // Write Filter element specifying the event to subscribe to.
                xmlWriter.WriteStartElement(WsNamespacePrefix.Wse, "Filter", null);
                xmlWriter.WriteAttributeString("Dialect", m_version.WsdpNamespaceUri + "/Action");
                xmlWriter.WriteString(subscriptionRequest.SubscriptionType.NamespaceUri + "/" + subscriptionRequest.SubscriptionType.TypeName);
                xmlWriter.WriteEndElement(); // End Filter

                xmlWriter.WriteEndElement(); // End Subscribe

                smw.WriteSoapMessageEnd(xmlWriter);

                // Performance debuging
                timeDebuger.PrintElapsedTime("*****Write Body Took");

                // Performance debuging
                timeDebuger.PrintTotalTime(startTime, "***Subscribe Message Build Took");

                // Create an Http client and send Subscribe request
                WsHttpClient httpClient = new WsHttpClient(m_version);

                msg.Body = xmlWriter.ToArray();

                subscribeResponse = httpClient.SendRequest(msg, subscriptionRequest.EndpointAddress);

                // If a subscribe response is received process it and return expiration time the subscription manager
                // actually assigned.
                // If a parsing fault is received print exception and go on.
                DpwsEventSubscription response = null;
                if (subscribeResponse == null)
                {
                    System.Ext.Console.Write("");
                    System.Ext.Console.Write("Subscribe response is null.");
                    return(null);
                }
                else
                {
                    byte[] responseBytes = subscribeResponse.Body as byte[];

                    // It is ok for the service to return a 202 and a 0 length response
                    // if thi is the case just return null
                    if (responseBytes == null || responseBytes.Length == 0)
                    {
                        return(null);
                    }

                    System.Ext.Console.Write("");
                    System.Ext.Console.Write("Response From: " + subscriptionRequest.EndpointAddress.Host);
                    System.Ext.Console.Write(responseBytes);
                    try
                    {
                        response = ProcessSubscribeResponse(responseBytes, messageID);
                    }
                    catch (Exception e)
                    {
                        System.Ext.Console.Write("");
                        System.Ext.Console.Write("Subscription response parsing failed.");
                        System.Ext.Console.Write(e.Message);
                    }
                }

                return(response);
            }
        }
        /// <summary>
        /// Method runs a loop waiting for Hello events. When on is received method probes, resolves
        /// and Get's device service information and calls 1way, 2way methods and subscribes to SimpleEvent
        /// and IntegerEvent and waits for them to fire. When they do Unsubscribe is called on the events
        /// and the receive hello's flag is reset.
        /// </summary>
        public void Run()
        {
            // Create Event handlers
            m_simpleServiceClient.ByeEvent += new ByeEventHandler(m_simpleControl_ByeEvent);
            m_simpleServiceClient.HelloEvent += new HelloEventHandler(m_simpleControl_HelloEvent);
            m_simpleServiceClient.SubscriptionEndEvent += new SubscriptionEndEventHandler(m_simpleControl_SubscriptionEndEvent);
            bool firstPass = true;

            bool twoWayAttach = false;

            DpwsServiceTypes typeProbes = new DpwsServiceTypes();
            typeProbes.Add(new DpwsServiceType("SimpleDeviceType", "http://schemas.example.org/SimpleService"));

            // Continuous run loop
            while (true)
            {
                if (firstPass && !m_inDiscovery)
                {
                    m_inDiscovery = true;
                    DpwsServiceDescriptions descs = m_simpleServiceClient.DiscoveryClient.Probe(typeProbes, 3, 5000);

                    for (int i = 0; i < descs.Count; i++)
                    {
                        DpwsServiceDescription desc = descs[i];

                        if (desc.XAddrs != null && desc.XAddrs.Length > 0)
                        {
                            if (CheckConnection(desc.ServiceTypes, desc.Endpoint.Address.AbsoluteUri)) break;
                        }
                    }
                    m_inDiscovery = false;
                }

                // If hello was received and a SimpleService device was found. SeletedService will not be null.
                // Process until Bye is received.
                if (m_deviceSelected.WaitOne(5000, false))
                {
                    // If this is the first time through the loop for this device subscribe to events
                    if (firstPass)
                    {
                        try
                        {
                            // Test service host call
                            System.Ext.Console.Write("Testing Host service...");
                            DpwsSubscribeRequest subReq;
                            subReq = new DpwsSubscribeRequest(m_eventingServiceClient.EventSources["SimpleEvent"], m_eventSubscriptionAddress, m_eventingServiceClient.TransportAddress, "PT1H", null);
                            m_simpleEventSubscription = m_eventingServiceClient.EventingClient.Subscribe(subReq);
                            subReq = new DpwsSubscribeRequest(m_eventingServiceClient.EventSources["IntegerEvent"], m_eventSubscriptionAddress, m_eventingServiceClient.TransportAddress, "PT1H", null);
                            m_integerEventSubscription = m_eventingServiceClient.EventingClient.Subscribe(subReq);

                            firstPass = false;
                        }
                        catch
                        {
                            m_deviceSelected.Reset();
                        }
                    }

                    // Make 1Way and 2Way service calls
                    if (m_deviceSelected.WaitOne(0, false))
                    {
                        try
                        {
                            PrintMetadataInfo();

                            System.Ext.Console.Write("");
                            System.Ext.Console.Write(">>>>>>>>>>>>> Sending 1way(10) request to: " + m_selectedService.ThisDevice.FriendlyName);
                            m_simpleServiceClient.OneWay(new OneWayRequest());
                        }
                        catch (Exception e)
                        {
                            firstPass = true;
                            m_deviceSelected.Reset();
                            System.Ext.Console.Write("");
                            System.Ext.Console.Write("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! OneWay method failed. " + e.Message);
                        }
                    }

                    if (m_deviceSelected.WaitOne(0, false))
                    {
                        int x = System.Math.Abs(m_random.Next()) % 100;
                        int y = System.Math.Abs(m_random.Next()) % 100;

                        System.Ext.Console.Write("");
                        System.Ext.Console.Write(">>>>>>>>>>>>> Sending 2way(" + x.ToString() + ", " + y.ToString() + ") request to: " + m_selectedService.ThisDevice.FriendlyName);
                        try
                        {
                            TwoWayRequest req = new TwoWayRequest();
                            req.X = x;
                            req.Y = y;

                            TwoWayResponse resp = m_simpleServiceClient.TwoWay(req);
                            if (resp.Sum == 0)
                            {
                                System.Ext.Console.Write("");
                                System.Ext.Console.Write("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 2way method did not receive a valid response.");
                            }
                            else
                            {
                                System.Ext.Console.Write("");
                                System.Ext.Console.Write("<<<<<<<<<<<<< 2way response returned " + resp.Sum);
                            }
                        }
                        catch (Exception e)
                        {
                            firstPass = true;
                            m_deviceSelected.Reset();
                            System.Ext.Console.Write("");
                            System.Ext.Console.Write("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! TwoWay method failed. " + e.Message);
                        }
                    }

                    // Make 1wayattach or a 2wayattach service calls
                    if (m_deviceSelected.WaitOne(0, false))
                    {
                        if (!twoWayAttach)
                        {
                            // create an instance of the help icon test object
                            HelpIcon helpIcon = new HelpIcon();

                            System.Ext.Console.Write("");
                            System.Ext.Console.Write(">>>>>>>>>>>>> Sending 1wayattach request to: " + m_selectedService.ThisDevice.FriendlyName);
                            try
                            {
                                OneWayAttachmentRequest req = new OneWayAttachmentRequest();
                                req.Param = helpIcon.Data.ToArray();
                                m_attachmentServiceClient.OneWayAttachment(req);
                            }
                            catch (Exception e)
                            {
                                firstPass = true;
                                m_deviceSelected.Reset();
                                System.Ext.Console.Write("");
                                System.Ext.Console.Write("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 1wayattach method failed: " + e.Message);
                            }
                        }
                        else
                        {
                            // create an instance of the help icon test object
                            HelpIcon helpIcon = new HelpIcon();

                            System.Ext.Console.Write("");
                            System.Ext.Console.Write(">>>>>>>>>>>>> Sending 2wayattach request to: " + m_selectedService.ThisDevice.FriendlyName);
                            try
                            {
                                TwoWayAttachmentRequest req = new TwoWayAttachmentRequest();
                                req.Param = helpIcon.Data.ToArray();
                                TwoWayAttachmentResponse resp = m_attachmentServiceClient.TwoWayAttachment(req);

                                System.Ext.Console.Write("");
                                System.Ext.Console.Write("<<<<<<<<<<<<< Sending 2wayattach request succeeded");
                            }
                            catch (Exception e)
                            {
                                firstPass = true;
                                m_deviceSelected.Reset();
                                System.Ext.Console.Write("");
                                System.Ext.Console.Write("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! TwoWay method failed. " + e.Message);
                            }
                        }

                        twoWayAttach = !twoWayAttach;
                    }
                }
                else
                {
                    firstPass = true;
                }

                GC.WaitForPendingFinalizers();
            }
        }
        /// <summary>
        /// Use to subscribe to a devices, hosted service event sources.
        /// </summary>
        /// <param name="subscriptionRequest">
        /// A DpwsSubscriptionRequest object containing the address of the service hosting the desired event,
        /// the address where the event is sent, an optional address where subscription end messages are sent,
        /// A subscription expiration (in duration format) and an optional user defined identifier.
        /// </param>
        /// <returns>
        /// A DpwsEventSubscription containing the the subscription managers address, the time when the subscription
        /// expires (duration) and optional reference parameters and properties. Per spec the
        /// sub mananger may assign a different duration value than that specified in the request.
        /// </returns>
        /// <exception cref="ArgumentNullException">If required subscription parameters are not set.</exception>
        public DpwsEventSubscription Subscribe(DpwsSubscribeRequest subscriptionRequest)
        {
            if ((subscriptionRequest.SubscriptionType              == null) ||
                (subscriptionRequest.SubscriptionType.TypeName     == null) ||
                (subscriptionRequest.SubscriptionType.NamespaceUri == null) ||
                (subscriptionRequest.EndpointAddress               == null) ||
                (subscriptionRequest.NotifyTo                      == null) ||
                (subscriptionRequest.NotifyTo.Address              == null))
            {
                throw new ArgumentNullException();
            }

            // Convert the address string to a Uri
            Uri serviceUri = null;
            try
            {
                serviceUri = subscriptionRequest.EndpointAddress;
                if (serviceUri.Scheme != "http")
                {
                    System.Ext.Console.Write("");
                    System.Ext.Console.Write("Invalid endpoint address. Must be a Uri. Http Uri schemes only.");
                    System.Ext.Console.Write("");
                    return null;
                }
            }
            catch (Exception e)
            {
                System.Ext.Console.Write("");
                System.Ext.Console.Write(e.Message);
                System.Ext.Console.Write("");
                return null;
            }

            // Performance debugging
            DebugTiming timeDebuger = new DebugTiming();
            long startTime = timeDebuger.ResetStartTime("");
            WsMessage subscribeResponse = null;

            // Build Subscribe Request
            using(XmlMemoryWriter xmlWriter = XmlMemoryWriter.Create())
            {
                WsWsaHeader header = new WsWsaHeader(
                    m_version.EventingNamespace + "/Subscribe",     // Action
                    null,                                           // RelatesTo
                    serviceUri.AbsoluteUri,                         // To
                    m_version.AnonymousUri,                         // ReplyTo
                    null, null);                                    // From, Any

                WsXmlNamespaces additionalPrefixes = new WsXmlNamespaces();
                additionalPrefixes.Add(new WsXmlNamespace("myPrefix", subscriptionRequest.SubscriptionType.NamespaceUri));

                WsMessage msg = new WsMessage(header, null, WsPrefix.Wsd | WsPrefix.Wse, additionalPrefixes, null);

                WsSoapMessageWriter smw = new WsSoapMessageWriter(m_version);
                String messageID = smw.WriteSoapMessageStart(xmlWriter, msg);

                // Performance debuging
                timeDebuger.PrintElapsedTime("*****Write Header Took");

                // write body
                xmlWriter.WriteStartElement(WsNamespacePrefix.Wse, "Subscribe", null);
                
                // If EndTo is set write it
                if (subscriptionRequest.EndTo != null)
                    WriteEndpointRef(xmlWriter, subscriptionRequest.EndTo, "EndTo");

                // Add the delivery element and NotifyTo endpoint
                xmlWriter.WriteStartElement(WsNamespacePrefix.Wse, "Delivery", null);
                xmlWriter.WriteAttributeString("Mode", m_version.EventingNamespace + "/DeliveryModes/Push");

                // Writer the notify to endpoint
                WriteEndpointRef(xmlWriter, subscriptionRequest.NotifyTo, "NotifyTo");

                xmlWriter.WriteEndElement(); // End Delivery

                // Write Expiration time
                if (subscriptionRequest.Expires != null)
                {
                    xmlWriter.WriteStartElement(WsNamespacePrefix.Wse, "Expires", null);
                    xmlWriter.WriteString(subscriptionRequest.Expires.DurationString);
                    xmlWriter.WriteEndElement(); // End Expires
                }

                // Write Filter element specifying the event to subscribe to.
                xmlWriter.WriteStartElement(WsNamespacePrefix.Wse, "Filter", null);
                xmlWriter.WriteAttributeString("Dialect", m_version.WsdpNamespaceUri + "/Action");
                xmlWriter.WriteString(subscriptionRequest.SubscriptionType.NamespaceUri + "/" + subscriptionRequest.SubscriptionType.TypeName);
                xmlWriter.WriteEndElement(); // End Filter

                xmlWriter.WriteEndElement(); // End Subscribe

                smw.WriteSoapMessageEnd(xmlWriter);

                // Performance debuging
                timeDebuger.PrintElapsedTime("*****Write Body Took");

                // Performance debuging
                timeDebuger.PrintTotalTime(startTime, "***Subscribe Message Build Took");

                // Create an Http client and send Subscribe request
                WsHttpClient httpClient = new WsHttpClient(m_version);

                msg.Body = xmlWriter.ToArray();

                subscribeResponse = httpClient.SendRequest(msg, subscriptionRequest.EndpointAddress);

                // If a subscribe response is received process it and return expiration time the subscription manager
                // actually assigned.
                // If a parsing fault is received print exception and go on.
                DpwsEventSubscription response = null;
                if (subscribeResponse == null)
                {
                    System.Ext.Console.Write("");
                    System.Ext.Console.Write("Subscribe response is null.");
                    return null;
                }
                else
                {
                    byte[] responseBytes = subscribeResponse.Body as byte[];

                    // It is ok for the service to return a 202 and a 0 length response
                    // if thi is the case just return null
                    if(responseBytes == null || responseBytes.Length == 0) return null;

                    System.Ext.Console.Write("");
                    System.Ext.Console.Write("Response From: " + subscriptionRequest.EndpointAddress.Host);
                    System.Ext.Console.Write(responseBytes);
                    try
                    {
                        response = ProcessSubscribeResponse(responseBytes, messageID);
                    }
                    catch (Exception e)
                    {
                        System.Ext.Console.Write("");
                        System.Ext.Console.Write("Subscription response parsing failed.");
                        System.Ext.Console.Write(e.Message);
                    }
                }
                
                return response;
            }
        }
示例#5
0
        /// <summary>
        /// Use to subscribe to a devices, hosted service event sources.
        /// </summary>
        /// <param name="subscriptionRequest">
        /// A DpwsSubscriptionRequest object containing the address of the service hosting the desired event,
        /// the address where the event is sent, an optional address where subscription end messages are sent,
        /// A subscription expiration (in duration format) and an optional user defined identifier.
        /// </param>
        /// <returns>
        /// A DpwsEventSubscription containing the the subscription managers address, the time when the subscription
        /// expires (duration) and optional reference parameters and properties. Per spec the
        /// sub mananger may assign a different duration value than that specified in the request.
        /// </returns>
        /// <exception cref="ArgumentNullException">If required subscription parameters are not set.</exception>
        public DpwsEventSubscription Subscribe(DpwsSubscribeRequest subscriptionRequest)
        {
            if (subscriptionRequest.SubscriptionType == null)
                throw new ArgumentNullException("Subscribe - SubscriptionType must not be null");
            if (subscriptionRequest.SubscriptionType.TypeName == null)
                throw new ArgumentNullException("Subscribe - SubscriptionType.TypeName must not be null");
            if (subscriptionRequest.SubscriptionType.NamespaceUri == null)
                throw new ArgumentNullException("Subscribe - SubscriptionType.NamespaceUri must not be null");
            if (subscriptionRequest.EndpointAddress == null)
                throw new ArgumentNullException("Subscribe - EndpointAddress property must not be null.");
            if (subscriptionRequest.NotifyTo == null)
                throw new ArgumentNullException("Subscribe - NotifyTo must not be null.");
            if (subscriptionRequest.NotifyTo.Address == null)
                throw new ArgumentNullException("Subscribe - NotifyTo.Address must not be null.");

            // Convert the address string to a Uri
            Uri serviceUri = null;
            try
            {
                serviceUri = subscriptionRequest.EndpointAddress;
                if (serviceUri.Scheme != "http")
                {
                    System.Ext.Console.Write("");
                    System.Ext.Console.Write("Invalid endpoint address. Must be a Uri. Http Uri schemes only.");
                    System.Ext.Console.Write("");
                    return null;
                }
            }
            catch (Exception e)
            {
                System.Ext.Console.Write("");
                System.Ext.Console.Write(e.Message);
                System.Ext.Console.Write("");
                return null;
            }

            // Performance debugging
            DebugTiming timeDebuger = new DebugTiming();
            long startTime = timeDebuger.ResetStartTime("");

            // Build Subscribe Request
            MemoryStream soapStream = new MemoryStream();
            XmlWriter xmlWriter = XmlWriter.Create(soapStream);

            WsWsaHeader header = new WsWsaHeader(
                WsWellKnownUri.WseNamespaceUri + "/Subscribe",  // Action
                null,                                           // RelatesTo
                serviceUri.AbsoluteUri,                         // To
                WsWellKnownUri.WsaAnonymousUri,                 // ReplyTo
                null, null);                                    // From, Any

            WsXmlNamespaces additionalPrefixes = new WsXmlNamespaces();
            additionalPrefixes.Add(new WsXmlNamespace("myPrefix", subscriptionRequest.SubscriptionType.NamespaceUri));

            String messageID = WsSoapMessageWriter.WriteSoapMessageStart(xmlWriter,
                WsSoapMessageWriter.Prefixes.Wsd | WsSoapMessageWriter.Prefixes.Wse,
                additionalPrefixes, header, null);

            // Performance debuging
            timeDebuger.PrintElapsedTime("*****Write Header Took");

            // write body
            xmlWriter.WriteStartElement("wse", "Subscribe", null);
            
            // If EndTo is set write it
            if (subscriptionRequest.EndTo != null)
                WriteEndpointRef(ref xmlWriter, subscriptionRequest.EndTo, "EndTo");

            // Add the delivery element and NotifyTo endpoint
            xmlWriter.WriteStartElement("wse", "Delivery", null);
            xmlWriter.WriteAttributeString("Mode", "http://schemas.xmlsoap.org/ws/2004/08/eventing/DeliveryModes/Push");

            // Writer the notify to endpoint
            WriteEndpointRef(ref xmlWriter, subscriptionRequest.NotifyTo, "NotifyTo");

            xmlWriter.WriteEndElement(); // End Delivery

            // Write Expiration time
            if (subscriptionRequest.Expires != null)
            {
                xmlWriter.WriteStartElement("wse", "Expires", null);
                xmlWriter.WriteString(subscriptionRequest.Expires.DurationString);
                xmlWriter.WriteEndElement(); // End Expires
            }

            // Write Filter element specifying the event to subscribe to.
            xmlWriter.WriteStartElement("wse", "Filter", null);
            xmlWriter.WriteAttributeString("Dialect", "http://schemas.xmlsoap.org/ws/2006/02/devprof/Action");
            xmlWriter.WriteString(subscriptionRequest.SubscriptionType.NamespaceUri + "/" + subscriptionRequest.SubscriptionType.TypeName);
            xmlWriter.WriteEndElement(); // End Filter

            xmlWriter.WriteEndElement(); // End Subscribe

            WsSoapMessageWriter.WriteSoapMessageEnd(xmlWriter);

            // Performance debuging
            timeDebuger.PrintElapsedTime("*****Write Body Took");

            // Performance debuging
            timeDebuger.PrintTotalTime(startTime, "***Subscribe Message Build Took");

            // Flush and close writer
            xmlWriter.Flush();
            xmlWriter.Close();

            // Create an Http client and send Subscribe request
            WsHttpClient httpClient = new WsHttpClient();
            byte[] subscribeResponse = null;
            try
            {
                subscribeResponse = httpClient.SendRequest(soapStream.ToArray(), subscriptionRequest.EndpointAddress.AbsoluteUri, false, false);
            }
            catch (Exception e)
            {
                System.Ext.Console.Write("");
                System.Ext.Console.Write("Subscribe failed. " + e.Message);
                return null;
            }

            // If a subscribe response is received process it and return expiration time the subscription manager
            // actually assigned.
            // If a parsing fault is received print exception and go on.
            DpwsEventSubscription response = null;
            if (subscribeResponse == null)
            {
                System.Ext.Console.Write("");
                System.Ext.Console.Write("Subscribe response is null.");
                return null;
            }
            else
            {
                System.Ext.Console.Write("");
                System.Ext.Console.Write("Response From: " + subscriptionRequest.EndpointAddress.Host);
                System.Ext.Console.Write(new String(System.Text.Encoding.UTF8.GetChars(subscribeResponse)));
                try
                {
                    // It is ok for the service to return a 202 and a 0 length response
                    // if thi is the case just return null
                    if (subscribeResponse.Length == 0)
                        return null;
                    response = ProcessSubscribeResponse(subscribeResponse, messageID);
                }
                catch (Exception e)
                {
                    System.Ext.Console.Write("");
                    System.Ext.Console.Write("Subscription response parsing failed.");
                    System.Ext.Console.Write(e.Message);
                }
            }

            return response;
        }
示例#6
0
        /// <summary>
        /// Use to subscribe to a devices, hosted service event sources.
        /// </summary>
        /// <param name="subscriptionRequest">
        /// A DpwsSubscriptionRequest object containing the address of the service hosting the desired event,
        /// the address where the event is sent, an optional address where subscription end messages are sent,
        /// A subscription expiration (in duration format) and an optional user defined identifier.
        /// </param>
        /// <returns>
        /// A DpwsEventSubscription containing the the subscription managers address, the time when the subscription
        /// expires (duration) and optional reference parameters and properties. Per spec the
        /// sub mananger may assign a different duration value than that specified in the request.
        /// </returns>
        /// <exception cref="ArgumentNullException">If required subscription parameters are not set.</exception>
        public DpwsEventSubscription Subscribe(DpwsSubscribeRequest subscriptionRequest)
        {
            if (subscriptionRequest.SubscriptionType == null)
            {
                throw new ArgumentNullException("Subscribe - SubscriptionType must not be null");
            }
            if (subscriptionRequest.SubscriptionType.TypeName == null)
            {
                throw new ArgumentNullException("Subscribe - SubscriptionType.TypeName must not be null");
            }
            if (subscriptionRequest.SubscriptionType.NamespaceUri == null)
            {
                throw new ArgumentNullException("Subscribe - SubscriptionType.NamespaceUri must not be null");
            }
            if (subscriptionRequest.EndpointAddress == null)
            {
                throw new ArgumentNullException("Subscribe - EndpointAddress property must not be null.");
            }
            if (subscriptionRequest.NotifyTo == null)
            {
                throw new ArgumentNullException("Subscribe - NotifyTo must not be null.");
            }
            if (subscriptionRequest.NotifyTo.Address == null)
            {
                throw new ArgumentNullException("Subscribe - NotifyTo.Address must not be null.");
            }

            // Convert the address string to a Uri
            Uri serviceUri = null;

            try
            {
                serviceUri = subscriptionRequest.EndpointAddress;
                if (serviceUri.Scheme != "http")
                {
                    System.Ext.Console.Write("");
                    System.Ext.Console.Write("Invalid endpoint address. Must be a Uri. Http Uri schemes only.");
                    System.Ext.Console.Write("");
                    return(null);
                }
            }
            catch (Exception e)
            {
                System.Ext.Console.Write("");
                System.Ext.Console.Write(e.Message);
                System.Ext.Console.Write("");
                return(null);
            }

            // Performance debugging
            DebugTiming timeDebuger = new DebugTiming();
            long        startTime   = timeDebuger.ResetStartTime("");

            // Build Subscribe Request
            MemoryStream soapStream = new MemoryStream();
            XmlWriter    xmlWriter  = XmlWriter.Create(soapStream);

            WsWsaHeader header = new WsWsaHeader(
                WsWellKnownUri.WseNamespaceUri + "/Subscribe",  // Action
                null,                                           // RelatesTo
                serviceUri.AbsoluteUri,                         // To
                WsWellKnownUri.WsaAnonymousUri,                 // ReplyTo
                null, null);                                    // From, Any

            WsXmlNamespaces additionalPrefixes = new WsXmlNamespaces();

            additionalPrefixes.Add(new WsXmlNamespace("myPrefix", subscriptionRequest.SubscriptionType.NamespaceUri));

            String messageID = WsSoapMessageWriter.WriteSoapMessageStart(xmlWriter,
                                                                         WsSoapMessageWriter.Prefixes.Wsd | WsSoapMessageWriter.Prefixes.Wse,
                                                                         additionalPrefixes, header, null);

            // Performance debuging
            timeDebuger.PrintElapsedTime("*****Write Header Took");

            // write body
            xmlWriter.WriteStartElement("wse", "Subscribe", null);

            // If EndTo is set write it
            if (subscriptionRequest.EndTo != null)
            {
                WriteEndpointRef(ref xmlWriter, subscriptionRequest.EndTo, "EndTo");
            }

            // Add the delivery element and NotifyTo endpoint
            xmlWriter.WriteStartElement("wse", "Delivery", null);
            xmlWriter.WriteAttributeString("Mode", "http://schemas.xmlsoap.org/ws/2004/08/eventing/DeliveryModes/Push");

            // Writer the notify to endpoint
            WriteEndpointRef(ref xmlWriter, subscriptionRequest.NotifyTo, "NotifyTo");

            xmlWriter.WriteEndElement(); // End Delivery

            // Write Expiration time
            if (subscriptionRequest.Expires != null)
            {
                xmlWriter.WriteStartElement("wse", "Expires", null);
                xmlWriter.WriteString(subscriptionRequest.Expires.DurationString);
                xmlWriter.WriteEndElement(); // End Expires
            }

            // Write Filter element specifying the event to subscribe to.
            xmlWriter.WriteStartElement("wse", "Filter", null);
            xmlWriter.WriteAttributeString("Dialect", "http://schemas.xmlsoap.org/ws/2006/02/devprof/Action");
            xmlWriter.WriteString(subscriptionRequest.SubscriptionType.NamespaceUri + "/" + subscriptionRequest.SubscriptionType.TypeName);
            xmlWriter.WriteEndElement(); // End Filter

            xmlWriter.WriteEndElement(); // End Subscribe

            WsSoapMessageWriter.WriteSoapMessageEnd(xmlWriter);

            // Performance debuging
            timeDebuger.PrintElapsedTime("*****Write Body Took");

            // Performance debuging
            timeDebuger.PrintTotalTime(startTime, "***Subscribe Message Build Took");

            // Flush and close writer
            xmlWriter.Flush();
            xmlWriter.Close();

            // Create an Http client and send Subscribe request
            WsHttpClient httpClient = new WsHttpClient();

            byte[] subscribeResponse = null;
            try
            {
                subscribeResponse = httpClient.SendRequest(soapStream.ToArray(), subscriptionRequest.EndpointAddress.AbsoluteUri, false, false);
            }
            catch (Exception e)
            {
                System.Ext.Console.Write("");
                System.Ext.Console.Write("Subscribe failed. " + e.Message);
                return(null);
            }

            // If a subscribe response is received process it and return expiration time the subscription manager
            // actually assigned.
            // If a parsing fault is received print exception and go on.
            DpwsEventSubscription response = null;

            if (subscribeResponse == null)
            {
                System.Ext.Console.Write("");
                System.Ext.Console.Write("Subscribe response is null.");
                return(null);
            }
            else
            {
                System.Ext.Console.Write("");
                System.Ext.Console.Write("Response From: " + subscriptionRequest.EndpointAddress.Host);
                System.Ext.Console.Write(new String(System.Text.Encoding.UTF8.GetChars(subscribeResponse)));
                try
                {
                    // It is ok for the service to return a 202 and a 0 length response
                    // if thi is the case just return null
                    if (subscribeResponse.Length == 0)
                    {
                        return(null);
                    }
                    response = ProcessSubscribeResponse(subscribeResponse, messageID);
                }
                catch (Exception e)
                {
                    System.Ext.Console.Write("");
                    System.Ext.Console.Write("Subscription response parsing failed.");
                    System.Ext.Console.Write(e.Message);
                }
            }

            return(response);
        }