/// <summary>
        /// Event GetStatus stub.
        /// </summary>
        /// <param name="header">Header object.</param>
        /// <param name="reader">An XmlReader positioned at the begining of the GetStatus request body element.</param>
        /// <param name="serviceEndpoints">A Collection of serviceEndpoints used to determine what services contain the specified event.</param>
        /// <returns>Byte array containing an GetStatus response.</returns>
        /// <remarks>This method is used by the stack framework. Do not use this method.</remarks>
        public WsMessage GetStatus(WsWsaHeader header, XmlReader reader, WsServiceEndpoints serviceEndpoints)
        {
            // Parse GetStatus Request
            ///////////////////////////////
            // there's no info in GetStatus that we actually need, just get the identifier from header
            String eventSinkID = header.Any.GetNodeValue("Identifier", WsWellKnownUri.WseNamespaceUri);

            // Iterate the list of hosted services at the specified endpoint and get the status of the first
            // subscription matching the eventSink. Not pretty but eventing and shared service endpoints don't
            // fit together
            if (eventSinkID != null)
            {
                // Parse urn:uuid from the To address
                string endpointAddress = FixToAddress(header.To);

                DpwsHostedService endpoint = (DpwsHostedService)serviceEndpoints[endpointAddress];
                if (endpoint != null)
                {
                    DpwsWseEventSink eventSink;
                    if ((eventSink = GetEventSink(endpoint.EventSources, eventSinkID)) != null)
                    {
                        long timeRemaining = DateTime.Now.Ticks - (eventSink.StartTime + eventSink.Expires);
                        timeRemaining = timeRemaining < 0 ? 0 : timeRemaining;

                        return(GetStatusResponse(header, timeRemaining));
                    }
                }
            }

            // Something went wrong
            throw new WsFaultException(header, WsFaultType.WseEventSourceUnableToProcess);
        }
Exemple #2
0
 /// <summary>
 /// Creates a http service host.
 /// </summary>
 /// <param name="port">An integer containing the port number this host will listen on.</param>
 /// <param name="serviceEndpoints">A collection of service endpoints this transport service can dispatch to.</param>
 public WsHttpServiceHost(_Bind.Binding binding, WsServiceEndpoints serviceEndpoints)
 {
     m_threadManager    = new WsThreadManager(5, "Http");
     m_binding          = binding;
     m_serviceEndpoints = serviceEndpoints;
     m_isStarted        = false;
 }
Exemple #3
0
 /// <summary>
 /// Creates an empty instance of the UdpProcess class.
 /// </summary>
 public WsUdpMessageProcessor(WsServiceEndpoints serviceEndpoints, byte[] soapMessage, IPEndPoint remoteEP, WsMessageCheck messageCheck)
 {
     m_serviceEndpoints = serviceEndpoints;
     m_soapMessage      = soapMessage;
     m_remoteEP         = remoteEP;
     m_messageCheck     = messageCheck;
 }
 static Device()
 {
     m_MetadataVersion = 1;
     m_AppSequence     = 1;
     m_MessageID       = 0;
     m_hostedServices  = new WsServiceEndpoints();
     m_appMaxDelay     = 500;
 }
Exemple #5
0
        // private
        private WsUdpServiceHost()
        {
            m_threadManager     = new WsThreadManager(5, "Udp");
            m_serviceEndpoints  = new WsServiceEndpoints();
            m_refcount          = 0;
            m_binding           = null;
            m_replyChannel      = null;

            UdpTransportBindingElement transport = new UdpTransportBindingElement(new UdpTransportBindingConfig(WsDiscovery.WsDiscoveryAddress, WsDiscovery.WsDiscoveryPort, m_ignoreLocalRequests));

            m_binding = new CustomBinding(transport);
        }
        // private
        private WsUdpServiceHost()
        {
            m_threadManager    = new WsThreadManager(5, "Udp");
            m_serviceEndpoints = new WsServiceEndpoints();
            m_refcount         = 0;
            m_binding          = null;
            m_replyChannel     = null;

            UdpTransportBindingElement transport = new UdpTransportBindingElement(new UdpTransportBindingConfig(WsDiscovery.WsDiscoveryAddress, WsDiscovery.WsDiscoveryPort, m_ignoreLocalRequests));

            m_binding = new CustomBinding(transport);
        }
Exemple #7
0
        /// <summary>
        /// Creates and instance of a WsUdpServiceHost class.
        /// </summary>
        /// <param name="serviceEndpoints">A collection of service endpoints this transport service can dispatch to.</param>
        public WsUdpServiceHost(WsServiceEndpoints serviceEndpoints)
        {
            m_serviceEndpoints = serviceEndpoints;

            // Create a UdpClient used to receive multicast messages. Bind and join mutilcast group, set send timeout
            // Set the client (socket) to reuse addresses. Set the receive buffer size to 65K. This will limit the
            // memory use if threads start getting over worked.
            m_udpReceiveClient = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            IPEndPoint localEP = new IPEndPoint(IPAddress.Any, c_discoveryPort);
            m_udpReceiveClient.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            m_udpReceiveClient.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, 0x5000);
            m_udpReceiveClient.Bind(localEP);
            // Join Multicast Group
            byte[] multicastOpt = new byte[] { 239, 255, 255, 250,   // WsDiscovery Multicast Address: 239.255.255.250
                                                 0,   0,   0,   0 }; // IPAddress.Any: 0.0.0.0
            m_udpReceiveClient.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, multicastOpt);

            // Create a UdpClient used to send request responses. Set SendTimeout.
            m_udpSendClient = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            m_udpSendClient.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
        }
Exemple #8
0
        /// <summary>
        /// Creates and instance of a WsUdpServiceHost class.
        /// </summary>
        /// <param name="serviceEndpoints">A collection of service endpoints this transport service can dispatch to.</param>
        public WsUdpServiceHost(WsServiceEndpoints serviceEndpoints)
        {
            m_serviceEndpoints = serviceEndpoints;

            // Create a UdpClient used to receive multicast messages. Bind and join mutilcast group, set send timeout
            // Set the client (socket) to reuse addresses. Set the receive buffer size to 65K. This will limit the
            // memory use if threads start getting over worked.
            m_udpReceiveClient = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            IPEndPoint localEP = new IPEndPoint(IPAddress.Any, c_discoveryPort);

            m_udpReceiveClient.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            m_udpReceiveClient.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, 0x5000);
            m_udpReceiveClient.Bind(localEP);
            // Join Multicast Group
            byte[] multicastOpt = new byte[] { 239, 255, 255, 250,   // WsDiscovery Multicast Address: 239.255.255.250
                                               0, 0, 0, 0 };         // IPAddress.Any: 0.0.0.0
            m_udpReceiveClient.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, multicastOpt);

            // Create a UdpClient used to send request responses. Set SendTimeout.
            m_udpSendClient = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            m_udpSendClient.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
        }
Exemple #9
0
        /// <summary>
        /// Stop tranport services and releases the managed resources used by this class.
        /// </summary>
        /// <param name="disposing">True to release managed resources</param>
        internal void Dispose(bool disposing)
        {
            if (disposing)
            {
                // Stop the transport services
                m_httpServiceHost.Stop();
                m_udpSeviceHost.Stop();

                m_threadLock               = null;
                m_discoClient              = null;
                m_endpointAddress          = null;
                m_eventClient              = null;
                m_mexClient                = null;
                m_eventCallbacks           = null;
                m_transportAddress         = null;
                m_bodyParts                = null;
                m_discoServiceEndpoints    = null;
                m_callbackServiceEndpoints = null;
                m_udpSeviceHost            = null;
                m_httpServiceHost          = null;
            }
        }
Exemple #10
0
        /// <summary>
        /// Creates an instance of a DpwsClient class with a specified eventing callback port number.
        /// </summary>
        public DpwsClient(Binding localBinding, ProtocolVersion v)
        {
            m_threadLock               = new object();
            m_eventClient              = new DpwsEventingClient(v);
            m_mexClient                = new DpwsMexClient(v);
            m_eventCallbacks           = new WsServiceOperations();
            m_callbackServiceEndpoints = new WsServiceEndpoints();
            m_blockingCall             = true;
            m_ignoreRequestFromThisIP  = true;
            m_localBinding             = localBinding;
            m_version = v;

            m_discoClient = new DpwsDiscoveryClient(this, v);

            // Add the Hello and Bye discovery disco services
            ClientDiscoveryService = new DpwsDiscoClientService(this, v);

            // Start a Udp discovery service host
            WsUdpServiceHost.Instance.AddServiceEndpoint(ClientDiscoveryService);
            WsUdpServiceHost.Instance.IgnoreRequestFromThisIP = m_ignoreRequestFromThisIP;
            WsUdpServiceHost.Instance.MaxThreadCount          = 5;
            WsUdpServiceHost.Instance.Start(new ServerBindingContext(v));
        }
Exemple #11
0
        /// <summary>
        /// Creates an instance of a DpwsClient class with a specified eventing callback port number.
        /// </summary>
        public DpwsClient(Binding localBinding, ProtocolVersion v)
        {
            m_threadLock               = new object();
            m_eventClient              = new DpwsEventingClient(v);
            m_mexClient                = new DpwsMexClient(v);
            m_eventCallbacks           = new WsServiceOperations();
            m_callbackServiceEndpoints = new WsServiceEndpoints();
            m_blockingCall             = true;
            m_ignoreRequestFromThisIP  = true;
            m_localBinding             = localBinding;
            m_version = v;

            m_discoClient = new DpwsDiscoveryClient(this, v);

            // Add the Hello and Bye discovery disco services
            ClientDiscoveryService = new DpwsDiscoClientService(this, v);

            // Start a Udp discovery service host
            WsUdpServiceHost.Instance.AddServiceEndpoint(ClientDiscoveryService);
            WsUdpServiceHost.Instance.IgnoreRequestFromThisIP = m_ignoreRequestFromThisIP;
            WsUdpServiceHost.Instance.MaxThreadCount          = 5;
            WsUdpServiceHost.Instance.Start(new ServerBindingContext(v));

            // Add eventing SubscriptionEnd ServiceOperations. By default Subscription End call back
            // to this client
            ServiceOperations.Add(new WsServiceOperation(WsWellKnownUri.WseNamespaceUri, "SubscriptionEnd"));

            // Add callbacks implemented by this client
            m_callbackServiceEndpoints.Add(this);

            // Start the Http service host
            m_httpServiceHost = new WsHttpServiceHost(m_localBinding, m_callbackServiceEndpoints);
            m_httpServiceHost.MaxThreadCount = m_callbackServiceEndpoints.Count;
            m_httpServiceHost.Start(new ServerBindingContext(v));
            System.Ext.Console.Write("Http service host started...");
        }
Exemple #12
0
        public MFTestResults DeviceTest_ThisDevice()
        {
            /// <summary>
            /// 1. Verifies that each of the properties of the Device.ThisModel object is the correct type
            /// 2. Sets settable properties
            /// 3. Verifies their type again, and their data for non-nullable properties
            /// </summary>
            ///

            Device.Initialize(new WS2007HttpBinding(new HttpTransportBindingConfig("urn:uuid:3cb0d1ba-cc3a-46ce-b416-212ac2419b51", 8084)), new ProtocolVersion10());

            // Set device information
            //Device.EndpointAddress = "urn:uuid:3cb0d1ba-cc3a-46ce-b416-212ac2419b51";
            Device.ThisModel.Manufacturer    = "Microsoft Corporation";
            Device.ThisModel.ManufacturerUrl = "http://www.microsoft.com/";
            Device.ThisModel.ModelName       = "SimpleService Test Device";
            Device.ThisModel.ModelNumber     = "1.0";
            Device.ThisModel.ModelUrl        = "http://www.microsoft.com/";
            Device.ThisModel.PresentationUrl = "http://www.microsoft.com/";

            Device.ThisDevice.FriendlyName    = "SimpleService";
            Device.ThisDevice.FirmwareVersion = "alpha";
            Device.ThisDevice.SerialNumber    = "12345678";


            bool testResult = true;

            try
            {
                WsServiceEndpoints testWSEs = Device.HostedServices;
                if (testWSEs.GetType() != Type.GetType("Ws.Services.WsServiceEndpoints"))
                {
                    throw new Exception("HostedServices bad type");
                }

                string testString = Device.IPV4Address;
                if (testString.GetType() != Type.GetType("System.String"))
                {
                    throw new Exception("IPV4Address bad type");
                }

                int testInt = Device.MetadataVersion;
                if (testInt.GetType() != Type.GetType("System.Int32"))
                {
                    throw new Exception("MetadataVersion bad type");
                }

                Device.MetadataVersion = -12;
                if (Device.MetadataVersion != -12)
                {
                    throw new Exception("MetadataVersion did not set to invalid int value");
                }

                Device.MetadataVersion = 2;
                if (Device.MetadataVersion != 2)
                {
                    throw new Exception("MetadataVersion did not set to valid value");
                }

                testInt = Device.ProbeMatchDelay;
                if (testInt.GetType() != Type.GetType("System.Int32"))
                {
                    throw new Exception("ProbeMatchDelay bad type");
                }

                Device.ProbeMatchDelay = 2;
                if (Device.ProbeMatchDelay != 2)
                {
                    throw new Exception("ProbeMatchDelay did not set to valid value");
                }

                DpwsHostedService testDHS = Device.Host;
                if (testDHS != null)
                {
                    if (testDHS.GetType() !=
                        Type.GetType("Dpws.Device.Services.DpwsHostedService"))
                    {
                        throw new Exception("DpwsHostedService bad type");
                    }
                }

                Device.Host = new DpwsHostedService(new ProtocolVersion10());
                testDHS     = Device.Host;
                if (testDHS != null)
                {
                    if (testDHS.GetType() !=
                        Type.GetType("Dpws.Device.Services.DpwsHostedService"))
                    {
                        throw new Exception("DpwsHostedService bad type after set to new");
                    }
                }

                DpwsWseSubscriptionMgr testDWSM = Device.SubscriptionManager;
                if (testDWSM != null)
                {
                    if (testDWSM.GetType() !=
                        Type.GetType("Dpws.Device.Services.DpwsWseSubscriptionMgr"))
                    {
                        throw new Exception("DpwsWseSubscriptionMgr bad type");
                    }
                }

                // EndpointAddress will be defined by each event sink
                Device.SubscriptionManager = new DpwsWseSubscriptionMgr(new WS2007HttpBinding(), new ProtocolVersion10());
                testDWSM = Device.SubscriptionManager;
                if (testDWSM != null)
                {
                    if (testDWSM.GetType() !=
                        Type.GetType("Dpws.Device.Services.DpwsWseSubscriptionMgr"))
                    {
                        throw new Exception("DpwsWseSubscriptionMgr bad type after set to new");
                    }
                }
            }
            catch (Exception e)
            {
                testResult = false;
                Log.Comment("Incorrect exception caught: " + e.Message);
            }
            return(testResult ? MFTestResults.Pass : MFTestResults.Fail);
        }
Exemple #13
0
 /// <summary>
 /// HttpProcess()
 ///     Summary:
 ///         Main Http processor class.
 /// </summary>
 /// <param name="serviceEndpoints">A collection of service endpoints.</param>
 /// <param name="s">
 /// Socket s
 /// </param>
 public WsHttpMessageProcessor(WsServiceEndpoints serviceEndpoints)
 {
     m_serviceEndpoints = serviceEndpoints;
 }
Exemple #14
0
        //private const int ReadPayload = 0x800;

        /// <summary>
        /// HttpProcess()
        ///     Summary:
        ///         Main Http processor class.
        /// </summary>
        /// <param name="serviceEndpoints">A collection of service endpoints.</param>
        /// <param name="s">
        /// Socket s
        /// </param>
        public WsHttpMessageProcessor(WsServiceEndpoints serviceEndpoints, _Bind.RequestContext context)
        {
            m_context          = context;
            m_serviceEndpoints = serviceEndpoints;
        }
 /// <summary>
 /// Creates an empty instance of the UdpProcess class.
 /// </summary>
 public WsUdpMessageProcessor(WsServiceEndpoints serviceEndpoints)
 {
     m_serviceEndpoints = serviceEndpoints;
 }
        /// <summary>
        /// Eventing UnSubscribe stub.
        /// </summary>
        /// <param name="header">Header object.</param>
        /// <param name="reader">An XmlReader positioned at the begining of the Unsubscribe request body element.</param>
        /// <param name="serviceEndpoints">A Collection of serviceEndpoints used to determine what services contain the specified event.</param>
        /// <returns>Byte array containing an UnSubscribe response.</returns>
        /// <remarks>This method is used by the stack framework. Do not use this method.</remarks>
        public byte[] Unsubscribe(WsWsaHeader header, XmlReader reader, WsServiceEndpoints serviceEndpoints)
        {
            // Parse Unsubscribe Request
            ///////////////////////////////
            // there's no info in Unsubscribe that we actually need, just get the identifier from header
            String eventSinkID = header.Any.GetNodeValue("Identifier", WsWellKnownUri.WseNamespaceUri);

            bool eventSourceFound = false;

            if (eventSinkID != null)
            {
                // Parse urn:uuid from the To address
                string endpointAddress = FixToAddress(header.To);

                // Iterate the list of hosted services at the specified endpoint and unsubscribe from each event source
                // that matches the eventSinkID
                for (int i = 0; i < Device.HostedServices.Count; ++i)
                {
                    if (serviceEndpoints[i].EndpointAddress == endpointAddress)
                    {
                        // Delete Subscription
                        DpwsWseEventSources eventSources = ((DpwsHostedService)Device.HostedServices[i]).EventSources;

                        // Look for matching event in hosted services event sources
                        DpwsWseEventSource eventSource;
                        DpwsWseEventSinks  eventSinks;
                        DpwsWseEventSink   eventSink;
                        int eventSourcesCount = eventSources.Count;
                        int eventSinksCount;
                        for (int ii = 0; ii < eventSourcesCount; ii++)
                        {
                            eventSource     = eventSources[ii];
                            eventSinks      = eventSource.EventSinks;
                            eventSinksCount = eventSinks.Count;
                            for (int j = 0; j < eventSinksCount; j++)
                            {
                                eventSink = eventSinks[j];
                                if (eventSink.ID == eventSinkID)
                                {
                                    eventSourceFound = true;
                                    eventSource.EventSinks.Remove(eventSink);
                                }
                            }
                        }
                    }
                }

                if (eventSourceFound)
                {
                    // Generate Response

                    MemoryStream soapStream = new MemoryStream();
                    XmlWriter    xmlWriter  = XmlWriter.Create(soapStream);

                    WsWsaHeader responseHeader = new WsWsaHeader(
                        WsWellKnownUri.WseNamespaceUri + "/UnsubscribeResponse", // Action
                        header.MessageID,                                        // RelatesTo
                        header.ReplyTo.Address.AbsoluteUri,                      // To
                        null, null, null);

                    WsSoapMessageWriter.WriteSoapMessageStart(xmlWriter,
                                                              WsSoapMessageWriter.Prefixes.Wse,                                                              // Prefix
                                                              null,                                                                                          // Additional Prefix
                                                              responseHeader,                                                                                // Header
                                                              new WsSoapMessageWriter.AppSequence(Device.AppSequence, Device.SequenceID, Device.MessageID)); // AppSequence

                    WsSoapMessageWriter.WriteSoapMessageEnd(xmlWriter);

                    // Flush and close writer. Return stream buffer
                    xmlWriter.Flush();
                    xmlWriter.Close();
                    return(soapStream.ToArray());
                }
            }

            // Something went wrong
            throw new WsFaultException(header, WsFaultType.WseEventSourceUnableToProcess);
        }
Exemple #17
0
 /// <summary>
 /// Creates a http service host.
 /// </summary>
 /// <param name="port">An integer containing the port number this host will listen on.</param>
 /// <param name="serviceEndpoints">A collection of service endpoints this transport service can dispatch to.</param>
 public WsHttpServiceHost(int port, WsServiceEndpoints serviceEndpoints)
 {
     m_Port             = port;
     m_serviceEndpoints = serviceEndpoints;
     m_httpListener     = new HttpListener("http", m_Port);
 }
Exemple #18
0
 /// <summary>
 /// Creates a http service host.
 /// </summary>
 /// <param name="port">An integer containing the port number this host will listen on.</param>
 /// <param name="serviceEndpoints">A collection of service endpoints this transport service can dispatch to.</param>
 public WsHttpServiceHost(int port, WsServiceEndpoints serviceEndpoints)
 {
     m_Port = port;
     m_serviceEndpoints = serviceEndpoints;
     m_httpListener = new HttpListener("http", m_Port);
 }
Exemple #19
0
 /// <summary>
 /// Creates an empty instance of the UdpProcess class.
 /// </summary>
 public WsUdpMessageProcessor(WsServiceEndpoints serviceEndpoints, byte[] soapMessage, IPEndPoint remoteEP, WsMessageCheck messageCheck)
 {
     m_serviceEndpoints = serviceEndpoints;
     m_soapMessage = soapMessage;
     m_remoteEP = remoteEP;
     m_messageCheck = messageCheck;
 }
Exemple #20
0
 /// <summary>
 /// HttpProcess()
 ///     Summary:
 ///         Main Http processor class.
 /// </summary>
 /// <param name="serviceEndpoints">A collection of service endpoints.</param>
 /// <param name="s">
 /// Socket s
 /// </param>
 public WsHttpMessageProcessor(WsServiceEndpoints serviceEndpoints, HttpListenerContext httpContext)
 {
     m_httpContext = httpContext;
     m_serviceEndpoints = serviceEndpoints;
 }
Exemple #21
0
        public byte[] GetResponse(WsWsaHeader header, XmlReader reader)
        {
            // Build ProbeMatch
            MemoryStream soapStream = new MemoryStream();
            XmlWriter    xmlWriter  = XmlWriter.Create(soapStream);

            // Write service type namespaces
            WsXmlNamespaces additionalPrefixes = new WsXmlNamespaces();

            if (Device.Host != null)
            {
                additionalPrefixes = new WsXmlNamespaces();
                additionalPrefixes.Add(Device.Host.ServiceNamespace);
            }

            WsServiceEndpoints hostedServices = Device.HostedServices;
            int count = hostedServices.Count;

            for (int i = 0; i < count; i++)
            {
                DpwsHostedService hostedService = (DpwsHostedService)hostedServices[i];

                // Don't return Mex Service namespace
                if (hostedService.ServiceTypeName == "Internal")
                {
                    continue;
                }

                additionalPrefixes.Add(hostedService.ServiceNamespace);
            }

            WsWsaHeader responseHeader = new WsWsaHeader(
                WsWellKnownUri.WstNamespaceUri + "/GetResponse",                        // Action
                header.MessageID,                                                       // RelatesTo
                header.ReplyTo.Address.AbsoluteUri,                                     // To
                null, null, null);

            WsSoapMessageWriter.WriteSoapMessageStart(xmlWriter,
                                                      WsSoapMessageWriter.Prefixes.Wsx | WsSoapMessageWriter.Prefixes.Wsdp,                          // Prefix
                                                      additionalPrefixes,                                                                            // Additional Prefix
                                                      responseHeader,                                                                                // Header
                                                      new WsSoapMessageWriter.AppSequence(Device.AppSequence, Device.SequenceID, Device.MessageID)); // AppSequence

            // write body
            xmlWriter.WriteStartElement("wsx", "Metadata", WsWellKnownUri.WsxNamespaceUri);

            // Write ThisModel metadata section
            xmlWriter.WriteStartElement("wsx", "MetadataSection", WsWellKnownUri.WsxNamespaceUri);
            xmlWriter.WriteAttributeString("Dialect", "http://schemas.xmlsoap.org/ws/2006/02/devprof/ThisModel");

            xmlWriter.WriteStartElement("wsdp", "ThisModel", WsWellKnownUri.WsdpNamespaceUri);
            if (Device.ThisModel.Manufacturer != null && Device.ThisModel.Manufacturer != "")
            {
                xmlWriter.WriteStartElement("wsdp", "Manufacturer", WsWellKnownUri.WsdpNamespaceUri);
                xmlWriter.WriteString(Device.ThisModel.Manufacturer);
                xmlWriter.WriteEndElement(); // End Manufacturer
            }

            if (Device.ThisModel.ManufacturerUrl != null && Device.ThisModel.ManufacturerUrl != "")
            {
                xmlWriter.WriteStartElement("wsdp", "ManufacturerUrl", WsWellKnownUri.WsdpNamespaceUri);
                xmlWriter.WriteString(Device.ThisModel.ManufacturerUrl);
                xmlWriter.WriteEndElement(); // End ManufacturerUrl
            }

            if (Device.ThisModel.ModelName != null && Device.ThisModel.ModelName != "")
            {
                xmlWriter.WriteStartElement("wsdp", "ModelName", WsWellKnownUri.WsdpNamespaceUri);
                xmlWriter.WriteString(Device.ThisModel.ModelName);
                xmlWriter.WriteEndElement(); // End ModelName
            }

            if (Device.ThisModel.ModelNumber != null && Device.ThisModel.ModelNumber != "")
            {
                xmlWriter.WriteStartElement("wsdp", "ModelNumber", WsWellKnownUri.WsdpNamespaceUri);
                xmlWriter.WriteString(Device.ThisModel.ModelNumber);
                xmlWriter.WriteEndElement(); // End ModelNumber
            }

            if (Device.ThisModel.ModelUrl != null && Device.ThisModel.ModelUrl != "")
            {
                xmlWriter.WriteStartElement("wsdp", "ModelUrl", WsWellKnownUri.WsdpNamespaceUri);
                xmlWriter.WriteString(Device.ThisModel.ModelUrl);
                xmlWriter.WriteEndElement(); // End ModelUrl
            }

            if (Device.ThisModel.PresentationUrl != null && Device.ThisModel.PresentationUrl != "")
            {
                xmlWriter.WriteStartElement("wsdp", "PresentationUrl", WsWellKnownUri.WsdpNamespaceUri);
                xmlWriter.WriteString(Device.ThisModel.PresentationUrl);
                xmlWriter.WriteEndElement(); // End PresentationUrl
            }

            if (Device.ThisModel.Any != null)
            {
                Device.ThisModel.Any.WriteTo(xmlWriter);
            }

            xmlWriter.WriteStartElement("wsdp", "ModelName", WsWellKnownUri.WsdpNamespaceUri);
            xmlWriter.WriteString(Device.ThisModel.ModelName);
            xmlWriter.WriteEndElement(); // End ModelName

            xmlWriter.WriteEndElement(); // End ThisModel
            xmlWriter.WriteEndElement(); // End MetadataSection

            // Write ThisDevice metadata section
            xmlWriter.WriteStartElement("wsx", "MetadataSection", WsWellKnownUri.WsxNamespaceUri);
            xmlWriter.WriteAttributeString("Dialect", "http://schemas.xmlsoap.org/ws/2006/02/devprof/ThisDevice");

            xmlWriter.WriteStartElement("wsdp", "ThisDevice", WsWellKnownUri.WsdpNamespaceUri);
            if (Device.ThisDevice.FriendlyName != null && Device.ThisDevice.FriendlyName != "")
            {
                xmlWriter.WriteStartElement("wsdp", "FriendlyName", WsWellKnownUri.WsdpNamespaceUri);
                xmlWriter.WriteString(Device.ThisDevice.FriendlyName);
                xmlWriter.WriteEndElement(); // End FriendlyName
            }

            if (Device.ThisDevice.FirmwareVersion != null && Device.ThisDevice.FirmwareVersion != "")
            {
                xmlWriter.WriteStartElement("wsdp", "FirmwareVersion", WsWellKnownUri.WsdpNamespaceUri);
                xmlWriter.WriteString(Device.ThisDevice.FirmwareVersion);
                xmlWriter.WriteEndElement(); // End FirmwareVersion
            }

            if (Device.ThisDevice.SerialNumber != null && Device.ThisDevice.SerialNumber != "")
            {
                xmlWriter.WriteStartElement("wsdp", "SerialNumber", WsWellKnownUri.WsdpNamespaceUri);
                xmlWriter.WriteString(Device.ThisDevice.SerialNumber);
                xmlWriter.WriteEndElement(); // End SerialNumber
            }

            if (Device.ThisDevice.Any != null)
            {
                Device.ThisDevice.Any.WriteTo(xmlWriter);
            }

            xmlWriter.WriteEndElement(); // End ThisDevice
            xmlWriter.WriteEndElement(); // End MetadataSection

            // Write next MetadataSection
            xmlWriter.WriteStartElement("wsx", "MetadataSection", WsWellKnownUri.WsxNamespaceUri);
            xmlWriter.WriteAttributeString("Dialect", "http://schemas.xmlsoap.org/ws/2006/02/devprof/Relationship");

            // Write Relationship Elements
            xmlWriter.WriteStartElement("wsdp", "Relationship", WsWellKnownUri.WsdpNamespaceUri);
            xmlWriter.WriteAttributeString("Type", "http://schemas.xmlsoap.org/ws/2006/02/devprof/host");

            // List used to maintain service endpoints that have been processed. Because the DPWS spec allows
            // for multiple service types at a single endpoint address, we must make sure we only create
            // a relationship once for all of the types at a service endpoint.
            ArrayList processedEndpointList = new ArrayList();

            // If a Host type exist add it
            if (Device.Host != null)
            {
                xmlWriter.WriteStartElement("wsdp", "Host", WsWellKnownUri.WsdpNamespaceUri);
                WsWsaEndpointRef endpointReference;
                endpointReference = (WsWsaEndpointRef)Device.Host.EndpointRefs[0];
                xmlWriter.WriteStartElement("wsa", "EndpointReference", WsWellKnownUri.WsaNamespaceUri_2005_08);
                xmlWriter.WriteStartElement("wsa", "Address", WsWellKnownUri.WsaNamespaceUri_2005_08);
                xmlWriter.WriteString(endpointReference.Address.AbsoluteUri);
                xmlWriter.WriteEndElement(); // End Address
                xmlWriter.WriteEndElement(); // End EndpointReference

                // Build list of all service types that share this endpoint address

                /*
                 * string serviceTypes = null;
                 * if ((serviceTypes = BuildServiceTypesList(Device.Host, processedEndpointList)) == null)
                 *  serviceTypes = Device.Host.ServiceNamespace.Prefix + ":" + Device.Host.ServiceTypeName;
                 * else
                 *  serviceTypes = serviceTypes + " " + Device.Host.ServiceNamespace.Prefix + ":" + Device.Host.ServiceTypeName;
                 */

                // Write service types
                xmlWriter.WriteStartElement("wsdp", "Types", WsWellKnownUri.WsdpNamespaceUri);
                xmlWriter.WriteString(Device.Host.ServiceNamespace.Prefix + ":" + Device.Host.ServiceTypeName);
                xmlWriter.WriteEndElement(); // End Types

                // Write Service ID
                xmlWriter.WriteStartElement("wsdp", "ServiceId", WsWellKnownUri.WsdpNamespaceUri);
                xmlWriter.WriteString(Device.Host.ServiceID);
                xmlWriter.WriteEndElement(); // End ServiceID

                xmlWriter.WriteEndElement(); // End Hosted

                // Update processed endpoint list
                processedEndpointList.Add(Device.Host.EndpointAddress);
            }

            // Add hosted services types
            int serviceCount = hostedServices.Count;
            DpwsHostedService currentService;

            for (int i = 0; i < serviceCount; i++)
            {
                currentService = (DpwsHostedService)hostedServices[i];

                // Don't return Mex Service type
                if (currentService.ServiceTypeName == "Internal")
                {
                    continue;
                }

                // Build list of all service types that share this endpoint address
                string serviceTypes = null;
                if ((serviceTypes = BuildServiceTypesList(currentService, processedEndpointList)) == null)
                {
                    continue;
                }

                // Write hosted start element
                xmlWriter.WriteStartElement("wsdp", "Hosted", WsWellKnownUri.WsdpNamespaceUri);

                // Write n number of endpoint references
                int epRefCount = currentService.EndpointRefs.Count;
                for (int j = 0; j < epRefCount; j++)
                {
                    xmlWriter.WriteStartElement("wsa", "EndpointReference", WsWellKnownUri.WsaNamespaceUri_2005_08);
                    xmlWriter.WriteStartElement("wsa", "Address", WsWellKnownUri.WsaNamespaceUri_2005_08);
                    xmlWriter.WriteString(currentService.EndpointRefs[j].Address.AbsoluteUri);
                    xmlWriter.WriteEndElement(); // End Address
                    xmlWriter.WriteEndElement(); // End EndpointReference
                }

                // Write service types
                xmlWriter.WriteStartElement("wsdp", "Types", WsWellKnownUri.WsdpNamespaceUri);
                xmlWriter.WriteString(currentService.ServiceNamespace.Prefix + ":" + currentService.ServiceTypeName);
                xmlWriter.WriteEndElement(); // End Types

                // Write Service ID
                xmlWriter.WriteStartElement("wsdp", "ServiceId", WsWellKnownUri.WsdpNamespaceUri);
                xmlWriter.WriteString(currentService.ServiceID);
                xmlWriter.WriteEndElement(); // End ServiceID

                xmlWriter.WriteEndElement(); // End Hosted

                // Update processed endpoint list
                processedEndpointList.Add(currentService.EndpointAddress);
            }

            xmlWriter.WriteEndElement(); // End Relastionship
            xmlWriter.WriteEndElement(); // End MetadataSection

            xmlWriter.WriteEndElement(); // End Metadata

            WsSoapMessageWriter.WriteSoapMessageEnd(xmlWriter);

            // Flush and close writer. Return stream buffer
            xmlWriter.Flush();
            xmlWriter.Close();

            return(soapStream.ToArray());
        }
Exemple #22
0
 /// <summary>
 /// HttpProcess()
 ///     Summary:
 ///         Main Http processor class.
 /// </summary>
 /// <param name="serviceEndpoints">A collection of service endpoints.</param>
 /// <param name="s">
 /// Socket s
 /// </param>
 public WsHttpMessageProcessor(WsServiceEndpoints serviceEndpoints, HttpListenerContext httpContext)
 {
     m_httpContext      = httpContext;
     m_serviceEndpoints = serviceEndpoints;
 }
        /// <summary>
        /// Global eventing Subscribe stub.
        /// </summary>
        /// <param name="header">Header object.</param>
        /// <param name="reader">An XmlReader positioned at the begining of the Subscribe request body element.</param>
        /// <param name="serviceEndpoints">A Collection of serviceEndpoints used to determine what services contain the event source specified in the filter.</param>
        /// <returns>Byte array containing a Subscribe response.</returns>
        internal WsMessage Subscribe(WsWsaHeader header, XmlReader reader, WsServiceEndpoints serviceEndpoints)
        {
            WsMessage msg = null;

            // Parse Subscribe Request
            /////////////////////////////
            DpwsWseEventSink eventSink = new DpwsWseEventSink();

            try
            {
                reader.ReadStartElement("Subscribe", WsWellKnownUri.WseNamespaceUri);

                if (reader.IsStartElement("EndTo", WsWellKnownUri.WseNamespaceUri))
                {
                    eventSink.EndTo = new WsWsaEndpointRef(reader, m_version.AddressingNamespace);
                }

                reader.ReadStartElement("Delivery", WsWellKnownUri.WseNamespaceUri);
                if (reader.IsStartElement("NotifyTo", WsWellKnownUri.WseNamespaceUri))
                {
                    eventSink.NotifyTo = new WsWsaEndpointRef(reader, m_version.AddressingNamespace);
                }
                else
                {
                    throw new WsFaultException(header, WsFaultType.WseDeliverModeRequestedUnavailable);
                }

                reader.ReadEndElement();

                if (reader.IsStartElement("Expires", WsWellKnownUri.WseNamespaceUri))
                {
                    long expires = new WsDuration(reader.ReadElementString()).DurationInSeconds;

                    if (expires > 0)
                    {
                        eventSink.Expires = expires;
                    }
                    else
                    {
                        throw new WsFaultException(header, WsFaultType.WseInvalidExpirationTime);
                    }
                }
                else
                {
                    // Never Expires
                    eventSink.Expires = -1;
                }

                if (reader.IsStartElement("Filter", WsWellKnownUri.WseNamespaceUri))
                {
                    if (reader.MoveToAttribute("Dialect") == false || reader.Value != m_version.WsdpNamespaceUri + "/Action")
                    {
                        throw new WsFaultException(header, WsFaultType.WseFilteringRequestedUnavailable);
                    }

                    reader.MoveToElement();

                    String filters = reader.ReadElementString();

                    if (filters != String.Empty)
                    {
                        eventSink.Filters = filters.Split(' ');
                    }
                }

                XmlReaderHelper.SkipAllSiblings(reader);

                reader.ReadEndElement(); // Subscribe
            }
            catch (XmlException e)
            {
                throw new WsFaultException(header, WsFaultType.WseInvalidMessage, e.ToString());
            }

            // Parse urn:uuid from the To address
            string endpointAddress = FixToAddress(header.To);

            // Build a temporary collection of device services that match the specified endpoint address.
            WsServiceEndpoints matchingServices = new WsServiceEndpoints();

            for (int i = 0; i < serviceEndpoints.Count; ++i)
            {
                if (serviceEndpoints[i].EndpointAddress == endpointAddress)
                {
                    matchingServices.Add(serviceEndpoints[i]);
                }
            }

            // For each service with a matching endpoint and event sources add an event sink to the
            // event source collection
            for (int i = 0; i < matchingServices.Count; ++i)
            {
                DpwsWseEventSources eventSources = ((DpwsHostedService)matchingServices[i]).EventSources;

                // Set the EventSinkID
                eventSink.ID = "urn:uuid:" + Guid.NewGuid().ToString();

                // If subscribing to all event sources
                if (eventSink.Filters == null)
                {
                    int count = eventSources.Count;
                    for (int ii = 0; i < count; i++)
                    {
                        DpwsWseEventSource eventSource = eventSources[ii];
                        eventSink.StartTime = DateTime.Now.Ticks;
                        eventSource.EventSinks.Add(eventSink);
                    }
                }
                else
                {
                    // If subscribing to a specific event based on an event filter.
                    DpwsWseEventSource eventSource;
                    string[]           filterList = eventSink.Filters;
                    int length = filterList.Length;
                    for (int ii = 0; i < length; i++)
                    {
                        if ((eventSource = eventSources[filterList[ii]]) != null)
                        {
                            eventSink.StartTime = DateTime.Now.Ticks;
                            eventSource.EventSinks.Add(eventSink);
                        }
                        else
                        {
                            throw new Exception("Event source " + filterList[ii] + " was not found.");
                        }
                    }
                }
            }

            // Generate Response
            //////////////////////////
            using (XmlMemoryWriter xmlWriter = XmlMemoryWriter.Create())
            {
                WsWsaHeader responseHeader = new WsWsaHeader(
                    WsWellKnownUri.WseNamespaceUri + "/SubscribeResponse",  // Action
                    header.MessageID,                                       // RelatesTo
                    header.ReplyTo.Address.AbsoluteUri,                     // To
                    null, null, null);                                      // ReplyTo, From, Any

                msg = new WsMessage(responseHeader, null, WsPrefix.Wse, null,
                                    new WsAppSequence(Device.AppSequence, Device.SequenceID, Device.MessageID));

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

                // write body
                xmlWriter.WriteStartElement(WsNamespacePrefix.Wse, "SubscribeResponse", null);
                xmlWriter.WriteStartElement(WsNamespacePrefix.Wse, "SubscriptionManager", null);
                xmlWriter.WriteStartElement(WsNamespacePrefix.Wsa, "Address", null);
                // Create a uri. Use the path (by default will be a uuid) for the sub manager endpoint
                Uri subMgrUri = new Uri(((DpwsHostedService)matchingServices[0]).EndpointAddress);
                xmlWriter.WriteString("http://" + Device.IPV4Address + ":" + Device.Port + "/" + subMgrUri.AbsolutePath);
                xmlWriter.WriteEndElement(); // End Address
                xmlWriter.WriteStartElement(WsNamespacePrefix.Wsa, "ReferenceParameters", null);
                xmlWriter.WriteStartElement(WsNamespacePrefix.Wse, "Identifier", null);
                xmlWriter.WriteString(eventSink.ID);
                xmlWriter.WriteEndElement(); // End Identifier
                xmlWriter.WriteEndElement(); // End ReferenceParameters
                xmlWriter.WriteEndElement(); // End SubscriptionManager
                xmlWriter.WriteStartElement(WsNamespacePrefix.Wse, "Expires", null);
                xmlWriter.WriteString(new WsDuration(eventSink.Expires).DurationString);
                xmlWriter.WriteEndElement(); // End Expires
                xmlWriter.WriteEndElement(); // End SubscribeResponse

                smw.WriteSoapMessageEnd(xmlWriter);

                // Return stream buffer
                msg.Body = xmlWriter.ToArray();
            }

            return(msg);
        }
Exemple #24
0
 /// <summary>
 /// Creates an empty instance of the UdpProcess class.
 /// </summary>
 public WsUdpMessageProcessor(WsServiceEndpoints serviceEndpoints, RequestContext request) 
 {
     m_serviceEndpoints = serviceEndpoints;
     m_request = request;
 }
        /// <summary>
        /// Eventing UnSubscribe stub.
        /// </summary>
        /// <param name="header">Header object.</param>
        /// <param name="reader">An XmlReader positioned at the begining of the Unsubscribe request body element.</param>
        /// <param name="serviceEndpoints">A Collection of serviceEndpoints used to determine what services contain the specified event.</param>
        /// <returns>Byte array containing an UnSubscribe response.</returns>
        /// <remarks>This method is used by the stack framework. Do not use this method.</remarks>
        public WsMessage Unsubscribe(WsWsaHeader header, XmlReader reader, WsServiceEndpoints serviceEndpoints)
        {
            // Parse Unsubscribe Request
            ///////////////////////////////
            // there's no info in Unsubscribe that we actually need, just get the identifier from header
            String eventSinkID = header.Any.GetNodeValue("Identifier", WsWellKnownUri.WseNamespaceUri);

            bool eventSourceFound = false;

            if (eventSinkID != null)
            {
                // Parse urn:uuid from the To address
                string endpointAddress = FixToAddress(header.To);

                // Iterate the list of hosted services at the specified endpoint and unsubscribe from each event source
                // that matches the eventSinkID

                DpwsHostedService serv = (DpwsHostedService)Device.HostedServices[endpointAddress];

                if (serv != null)
                {
                    DpwsWseEventSources eventSources = serv.EventSources;

                    // Delete Subscription
                    // Look for matching event in hosted services event sources
                    DpwsWseEventSource eventSource;
                    DpwsWseEventSinks  eventSinks;
                    DpwsWseEventSink   eventSink;
                    int eventSourcesCount = eventSources.Count;
                    int eventSinksCount;
                    for (int i = 0; i < eventSourcesCount; i++)
                    {
                        eventSource     = eventSources[i];
                        eventSinks      = eventSource.EventSinks;
                        eventSinksCount = eventSinks.Count;

                        eventSink = eventSinks[eventSinkID];

                        if (eventSink != null)
                        {
                            eventSourceFound = true;
                            eventSource.EventSinks.Remove(eventSink);
                        }
                    }
                }

                if (eventSourceFound)
                {
                    // Generate Response
                    using (XmlMemoryWriter xmlWriter = XmlMemoryWriter.Create())
                    {
                        WsWsaHeader responseHeader = new WsWsaHeader(
                            WsWellKnownUri.WseNamespaceUri + "/UnsubscribeResponse", // Action
                            header.MessageID,                                        // RelatesTo
                            header.ReplyTo.Address.AbsoluteUri,                      // To
                            null, null, null);

                        WsMessage msg = new WsMessage(responseHeader, null, WsPrefix.Wse, null,
                                                      new WsAppSequence(Device.AppSequence, Device.SequenceID, Device.MessageID));

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

                        // Return stream buffer
                        msg.Body = xmlWriter.ToArray();

                        return(msg);
                    }
                }
            }

            // Something went wrong
            throw new WsFaultException(header, WsFaultType.WseEventSourceUnableToProcess);
        }
        /// <summary>
        /// Event renew stub.
        /// </summary>
        /// <param name="header">Header object.</param>
        /// <param name="reader">An XmlReader positioned at the begining of the Renew request body element.</param>
        /// <param name="serviceEndpoints">A Collection of serviceEndpoints used to determine what services contain the specified event.</param>
        /// <returns>Byte array containing an Renew response.</returns>
        /// <remarks>This method is used by the stack framework. Do not use this method.</remarks>
        public WsMessage Renew(WsWsaHeader header, XmlReader reader, WsServiceEndpoints serviceEndpoints)
        {
            long   newExpiration = 0;
            String eventSinkId   = String.Empty;

            // Parse Renew request
            ////////////////////////////
            try
            {
                reader.ReadStartElement("Renew", WsWellKnownUri.WseNamespaceUri);

                if (reader.IsStartElement("Expires", WsWellKnownUri.WseNamespaceUri))
                {
                    newExpiration = new WsDuration(reader.ReadElementString()).DurationInSeconds;

                    if (newExpiration <= 0)
                    {
                        throw new WsFaultException(header, WsFaultType.WseInvalidExpirationTime);
                    }
                }
                else
                {
                    // Never Expires
                    newExpiration = -1;
                }

                eventSinkId = header.Any.GetNodeValue("Identifier", WsWellKnownUri.WseNamespaceUri);

                if (eventSinkId == null)
                {
                    throw new XmlException();
                }
            }
            catch (XmlException e)
            {
                throw new WsFaultException(header, WsFaultType.WseInvalidMessage, e.ToString());
            }

            // Parse urn:uuid from the To address
            string endpointAddress = FixToAddress(header.To);

            // Iterate the list of hosted services at the specified endpoint and renew each subscription
            // with and event source that matches the eventSinkID
            DpwsWseEventSink eventSink;
            bool             eventSinkFound = false;

            DpwsHostedService endpoint = (DpwsHostedService)serviceEndpoints[endpointAddress];

            if (endpoint != null)
            {
                if ((eventSink = GetEventSink(endpoint.EventSources, eventSinkId)) != null)
                {
                    eventSinkFound = true;

                    // Update event sink expires time
                    eventSink.Expires = newExpiration;
                }
            }

            // Generate Response
            if (eventSinkFound)
            {
                return(GetStatusResponse(header, newExpiration)); // It's just like the GetStatus Response
            }
            throw new WsFaultException(header, WsFaultType.WseEventSourceUnableToProcess, "Subscription was not found. ID=" + eventSinkId);
        }
Exemple #27
0
 /// <summary>
 /// Creates an empty instance of the UdpProcess class.
 /// </summary>
 public WsUdpMessageProcessor(WsServiceEndpoints serviceEndpoints, RequestContext request)
 {
     m_serviceEndpoints = serviceEndpoints;
     m_request          = request;
 }