public DpwsMexService(XmlReader reader) { reader.ReadStartElement(); this.EndpointRefs = new WsWsaEndpointRefs(); while ( (reader.IsStartElement("EndpointReference", WsWellKnownUri.WsaNamespaceUri_2005_08)) || (reader.IsStartElement("EndpointReference", WsWellKnownUri.WsaNamespaceUri_2004_08)) ) { this.EndpointRefs.Add(new WsWsaEndpointRef(reader)); } if (EndpointRefs.Count == 0) { throw new XmlException(); // must have at least one EndpointReference } if (reader.IsStartElement("Types", WsWellKnownUri.WsdpNamespaceUri)) { this.ServiceTypes = new DpwsServiceTypes(reader); } this.ServiceID = reader.ReadElementString("ServiceId", WsWellKnownUri.WsdpNamespaceUri); XmlReaderHelper.SkipAllSiblings(reader); // xs:any reader.ReadEndElement(); }
public DpwsMexService(XmlReader reader, ProtocolVersion version) { reader.ReadStartElement(); this.EndpointRefs = new WsWsaEndpointRefs(); while (reader.IsStartElement("EndpointReference", version.AddressingNamespace)) { this.EndpointRefs.Add(new WsWsaEndpointRef(reader, version.AddressingNamespace)); } if (EndpointRefs.Count == 0) { throw new XmlException(); // must have at least one EndpointReference } if (reader.IsStartElement("Types", version.WsdpNamespaceUri)) { this.ServiceTypes = new DpwsServiceTypes(reader); } this.ServiceID = reader.ReadElementString("ServiceId", version.WsdpNamespaceUri); XmlReaderHelper.SkipAllSiblings(reader); // xs:any reader.ReadEndElement(); }
void CheckConnection(DpwsServiceTypes servTypes, string servAddr) { bool simpleDeviceTypeFound = false; string types = ""; for (int i = 0; i < servTypes.Count; ++i) { if (servTypes[i].TypeName == "SimpleDeviceType") { simpleDeviceTypeFound = true; } types += "NamespaceUri: " + servTypes[i].NamespaceUri + " " + "TypeName: " + servTypes[i].TypeName + "\n"; } System.Ext.Console.Write("Types: " + types); System.Ext.Console.Write(""); // If this is not a SimplDeviceType don't discover if (simpleDeviceTypeFound == false) { System.Ext.Console.Write(""); System.Ext.Console.Write("Discovery will only resolve SimpleDeviceType services."); } // Get SimpleService metadata DpwsMetadata deviceMetadata = m_discoClient.GetSimpleService(servAddr); if (deviceMetadata != null) { SelectedService = deviceMetadata; m_deviceSelected.Set(); } }
/// <summary> /// Looks for devices that host a service identified by its type and namespace. /// It returns the transport address of the first matching service. /// </summary> public static string FindFirst(DpwsDiscoveryClient discoveryClient, string serviceTypeName, string namespaceUri) { if (discoveryClient == null) { throw new ArgumentNullException(); } if (serviceTypeName == null) { throw new ArgumentNullException(); } if (namespaceUri == null) { throw new ArgumentNullException(); } Debug.Print("Discovering service devices..."); // Define search criterias DpwsServiceType serviceType = new DpwsServiceType(serviceTypeName, namespaceUri); DpwsServiceTypes filters = new DpwsServiceTypes(); filters.Add(serviceType); // Probe for devices DpwsServiceDescriptions probeMatches = discoveryClient.Probe(filters); if (probeMatches != null && probeMatches.Count > 0) { // Remember transport address of the first device string deviceTransportAddress = probeMatches[0].XAddrs[0]; // Request metadata to get the desired service and its ID DpwsMexClient mexClient = new DpwsMexClient(); DpwsMetadata metadata = mexClient.Get(deviceTransportAddress); // Check host service DpwsMexService host = metadata.Relationship.Host; if (host != null) // has host service { if (host.ServiceTypes[serviceTypeName] != null) { return(host.EndpointRefs[0].Address.AbsoluteUri); } } // Check hosted services DpwsMexServices hostedServices = metadata.Relationship.HostedServices; if (hostedServices != null) { for (int i = 0; i < hostedServices.Count; ++i) { DpwsMexService hostedService = hostedServices[i]; if (hostedService.ServiceTypes[serviceTypeName] != null) { return(hostedService.EndpointRefs[0].Address.AbsoluteUri); } } } } Debug.Print("No service found."); return(null); }
// Helper method to print names and namespaces of service types private void PrintServiceTypes(DpwsServiceTypes types) { int typeCount = types.Count; for (int i = 0; i < typeCount; i++) { DpwsServiceType serviceType = types[i]; //Log.Comment(" Name = " + serviceType.TypeName); //Log.Comment(" Namespace = " + serviceType.NamespaceUri); } }
private bool Discover(ServiceHelloWCFClientProxy proxy) { DpwsServiceTypes typeProbes = new DpwsServiceTypes(); typeProbes.Add(new DpwsServiceType("IServiceHelloWCF", "http://localhost/ServiceHelloWCF")); DpwsServiceDescriptions descs = proxy.DiscoveryClient.Probe(typeProbes, 1, 20000); if (descs.Count > 0) { proxy.EndpointAddress = descs[0].XAddrs[0]; return(true); } return(false); }
public void PrintProbeMatchInfo() { Debug.Print("Discovering service devices..."); // Define search criterias DpwsServiceType serviceType = new DpwsServiceType("SimpleServiceType2", // type name "http://schemas.sample.org/SimpleService2"); // namespace URI DpwsServiceTypes filters = new DpwsServiceTypes(); filters.Add(serviceType); // Probe for devices DpwsServiceDescriptions probeMatches = this.DiscoveryClient.Probe(filters); if (probeMatches != null) { for (int i = 0; i < probeMatches.Count; ++i) { DpwsServiceDescription probeMatch = probeMatches[i]; // Print probe match information Debug.Print(""); Debug.Print("Probe Match:"); Debug.Print("Endpoint Address = " + probeMatch.Endpoint.Address.AbsoluteUri); Debug.Print("Types:"); for (int t = 0; t < probeMatch.ServiceTypes.Count; ++t) { DpwsServiceType matchType = probeMatch.ServiceTypes[t]; Debug.Print("\tName = " + matchType.TypeName); Debug.Print("\tNamespace = " + matchType.NamespaceUri); Debug.Print(""); } Debug.Print("XAddrs:"); foreach (string xaddr in probeMatch.XAddrs) { Debug.Print("\tTransport Address = " + xaddr); } Debug.Print("Metadata Version = " + probeMatch.MetadataVersion); } } else { Debug.Print("No service device found."); } }
/// <summary> /// Builds a probe request message based on the filters parameter. /// </summary> /// <param name="serviceAddress"> /// A string containing the target service address. /// For example: urn:uuid:3cb0d1ba-cc3a-46ce-b416-212ac2419b20 /// </param> /// <param name="filters"> /// A DpwsServiceTypes object containing a collection of types a service must support to signal a match. /// Null = any type. /// </param> /// <param name="messageID"> /// A string used to return the messageID assigned to this message. /// </param> /// <returns>A byte array containing the probe message or null if an error occures.</returns> private WsMessage BuildProbeRequest(string serviceAddress, DpwsServiceTypes filters, out String messageID) { // Performance debugging DebugTiming timeDebuger = new DebugTiming(); long startTime = timeDebuger.ResetStartTime(""); WsMessage msg = null; // Build Probe request using(XmlMemoryWriter xmlWriter = XmlMemoryWriter.Create()) { WsWsaHeader header = new WsWsaHeader( m_version.DiscoveryNamespace + "/Probe", // Action null, // RelatesTo serviceAddress, // To m_version.AnonymousUri, null, null); // ReplyTo, From, Any header.MustUnderstand = true; // If filters are supplied, write filter namespaces if prefixed. Build filter list for use later WsXmlNamespaces namespaces = new WsXmlNamespaces(); // Prefix hack for now: int i = 0; string prefix; string filterList = ""; bool spaceFlag = false; if (filters != null) { int count = filters.Count; for (int j = 0; j < count; j++) { DpwsServiceType serviceType = filters[j]; prefix = namespaces.LookupPrefix(serviceType.NamespaceUri); if (prefix == null) { prefix = "dp" + (i++); namespaces.Add(new WsXmlNamespace(prefix, serviceType.NamespaceUri)); } filterList = filterList + ((spaceFlag == true) ? " " : "") + prefix + ":" + serviceType.TypeName; spaceFlag = true; } } msg = new WsMessage(header, null, WsPrefix.Wsd, namespaces, null); WsSoapMessageWriter smw = new WsSoapMessageWriter(m_version); messageID = smw.WriteSoapMessageStart(xmlWriter, msg); // Performance debuging timeDebuger.PrintElapsedTime("*****Write Header Took"); // write body xmlWriter.WriteStartElement(WsNamespacePrefix.Wsd, "Probe", null); // If filter is supplied add filter types tag else write blank string to probe body, force an empty tag if (filterList.Length != 0) { xmlWriter.WriteStartElement(WsNamespacePrefix.Wsd, "Types", null); xmlWriter.WriteString(filterList); xmlWriter.WriteEndElement(); // End Filter } else xmlWriter.WriteString(""); xmlWriter.WriteEndElement(); // End Probe // Performance debuging timeDebuger.PrintElapsedTime("*****Write Body Took"); smw.WriteSoapMessageEnd(xmlWriter); // Performance debuging timeDebuger.PrintTotalTime(startTime, "***Probe Message Build Took"); // return the probe message msg.Body = xmlWriter.ToArray(); } return msg; }
/// <summary> /// Creates an instance of a DpwsServiceDescription class initialized with a service endpoint and a list of /// supported service types. /// </summary> /// <param name="endpoint">A WsWsaEndpointRef object containing a Dpws Device servie endpoint.</param> /// <param name="serviceTypes">A string array containing a list of service types supporte by a Dpws devie service endpoint.</param> public DpwsServiceDescription(WsWsaEndpointRef endpoint, DpwsServiceTypes serviceTypes) { this.Endpoint = endpoint; this.ServiceTypes = serviceTypes; }
/// <summary> /// Sends a Probe request and parses ProbeMatches responses. /// </summary> /// <param name="filters"> /// A DpwsServiceTypes object containing a collection of types a service must support to signal a match. /// Null = any type. /// </param> /// <remarks> /// A Probe is used to discover services on a network. The Probe method sends a UDP request to the /// Dpws multicast address, 239.255.255.250:3702. Any service that implements types specified in the /// filters parameter should respond with a ProbeMatches message. The ProbeMatches mesgage is unicast /// back to the that client that made the request. If a null filter is supplied any Dpws complient /// service should reply with a ProbeMatches reponse. Probe waits DpwsDiceoveryCleint.ReceiveTimout /// for probe matches. /// </remarks> /// <returns> /// A collection of ProbeMatches objects. A ProbeMatch object contains endpoint details used /// used to locate the actual service on a network and the types supported by the service. /// </returns> public DpwsServiceDescriptions Probe(DpwsServiceTypes filters) { return Probe(filters, 0, -1); }
/// <summary> /// Sends a Probe request and parses ProbeMatches responses. /// </summary> /// <param name="filters"> /// A DpwsServiceTypes object containing a collection of types a service must support to signal a match. /// Null = any type. /// </param> /// <param name="maxProbeMatches"> /// An integer representing the maximum number of matches to reveive within the timout period. Pass 0 to receive /// as many matches as possible before the timeout expires. /// </param> /// <param name="timeout"> /// An integer specifying a request timeout in milliseconds. Pass -1 to wait ReceiveTimeout. /// </param> /// <remarks> /// A Probe is used to discover services on a network. The Probe method sends a UDP request to the /// Dpws multicast address, 239.255.255.250:3702. Any service that implements types specified in the /// filters parameter should respond with a ProbeMatches message. The ProbeMatches mesgage is unicast /// back to the that client that made the request. If a null filter is supplied any Dpws complient /// service should reply with a ProbeMatches reponse. Probe waits DpwsDiceoveryCleint.ReceiveTimout /// for probe matches. /// </remarks> /// <returns> /// A collection of ProbeMatches objects. A ProbeMatch object contains endpoint details used /// used to locate the actual service on a network and the types supported by the service. /// </returns> public DpwsServiceDescriptions Probe(DpwsServiceTypes filters, int maxProbeMatches, int timeout) { // Build the probe request message WsMessageCheck messageCheck = new WsMessageCheck(); string messageID = null; WsMessage probeRequest = BuildProbeRequest(DiscoVersion.DiscoveryWellKnownAddress, filters, out messageID); DpwsServiceDescriptions probeMatches = new DpwsServiceDescriptions(); System.Ext.Console.Write(""); System.Ext.Console.Write("Sending Probe:"); System.Ext.Console.Write(probeRequest.Body as byte[]); System.Ext.Console.Write(""); // Create a new UdpClient using(Socket udpClient = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) { IPEndPoint localEP = new IPEndPoint(IPAddress.Parse(WsNetworkServices.GetLocalIPV4Address()), m_discoResponsePort); udpClient.Bind(localEP); // Very important - Set default multicast interface for the underlying socket udpClient.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastInterface, (int)WsNetworkServices.GetLocalIPV4AddressValue()); udpClient.ReceiveTimeout = timeout; // Random back off implemented as per soap over udp specification // for unreliable multicast message exchange Thread th = SendWithBackoff((byte[])probeRequest.Body, udpClient); // Create probe matches collection and set expiration loop timer byte[] probeResponse = new byte[c_MaxUdpPacketSize]; EndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0); int responseLength; DpwsDiscoClientProcessor soapProcessor = new DpwsDiscoClientProcessor(m_version); while (true) { // Since MF sockets does not have an IOControl method catch 10054 to get around the problem // with Upd and ICMP. try { // Wait for response responseLength = udpClient.ReceiveFrom(probeResponse, c_MaxUdpPacketSize, SocketFlags.None, ref remoteEP); } catch (SocketException se) { if ((SocketError)se.ErrorCode == SocketError.ConnectionReset) { Thread.Sleep(100); continue; } // Timeout if ((SocketError)se.ErrorCode == SocketError.TimedOut) break; throw se; } // If we received process probe match if (responseLength > 0) { System.Ext.Console.Write(""); System.Ext.Console.Write("ProbeMatches Response From: " + ((IPEndPoint)remoteEP).Address.ToString()); System.Ext.Console.Write(probeResponse); // Process the response try { WsWsaHeader header = new WsWsaHeader(); XmlReader reader = WsSoapMessageParser.ParseSoapMessage(probeResponse, ref header, m_version); WsMessage msg = new WsMessage(header, null, WsPrefix.Wsdp); msg.Reader = reader; DpwsServiceDescriptions tempMatches = soapProcessor.ProcessProbeMatch(msg, messageID, (IPEndPoint)remoteEP, messageCheck); if (tempMatches != null) { int count = maxProbeMatches < tempMatches.Count ? maxProbeMatches : tempMatches.Count; for (int i = 0; i < count; i++) { probeMatches.Add(tempMatches[i]); } maxProbeMatches -= count; } } catch (Exception e) { System.Ext.Console.Write(""); System.Ext.Console.Write(e.Message); System.Ext.Console.Write(""); } // If maxProbeRequest is set check count if (maxProbeMatches <= 0) { break; } } } th.Join(); } // Display results if (probeMatches.Count == 0) System.Ext.Console.Write("Probe timed out."); else System.Ext.Console.Write("Received " + probeMatches.Count + " probeMatches matches."); return probeMatches; }
public MFTestResults ClientTest_DpwsServiceTypes() { /// <summary> /// 1. Verifies the properties of a DpwsServiceTypes object /// 2. Adds elements to it /// 3. Re-verifies /// 4. Empties the object /// 5. Re-verifies /// </summary> /// bool testResult = true; try { DpwsServiceTypes testDSTs = new DpwsServiceTypes(); if (testDSTs.Count != 0) { throw new Exception("Count did not set correctly on new"); } testDSTs.Clear(); if (testDSTs.Count != 0) { throw new Exception("Count did not set correctly after new ... clear"); } String typeName = "typeName"; String namespaceUri = "namespaceUri"; DpwsServiceType testDST1 = new DpwsServiceType(typeName, namespaceUri); String typeName2 = "typeName2"; String namespaceUri2 = "namespaceUri2"; DpwsServiceType testDST2 = new DpwsServiceType(typeName2, namespaceUri2); testDSTs.Add(testDST1); testDSTs.Add(testDST2); if (testDSTs.Count != 2) { throw new Exception("Count did not set correctly on new"); } testDSTs.Remove(testDST1); if (testDSTs.Count != 1) { throw new Exception("Count did not set correctly after remove"); } testDSTs.Clear(); if (testDSTs.Count != 0) { throw new Exception("Count did not set correctly after new ... clear"); } } catch (Exception e) { testResult = false; Log.Comment("Incorrect exception caught: " + e.Message); } return(testResult ? MFTestResults.Pass : MFTestResults.Fail); }
/// <summary> /// Sends a directed Probe request and parses ProbeMatches responses. /// </summary> /// <param name="endpointAddress"> /// A string containing a Dpws devices transport endpoint address. /// For example: http://192.168.0.1:8084/3cb0d1ba-cc3a-46ce-b416-212ac2419b20 /// </param> /// <param name="targetServiceAddress"> /// A string containing the target service address to probe for. /// For example: urn:uuid:3cb0d1ba-cc3a-46ce-b416-212ac2419b20 /// </param> /// <param name="filters"> /// A DpwsServiceTypes object containing a collection of types a service must support to signal a match. /// Null = any type. /// </param> /// <remarks> /// A directed Probe is used to discover services on a network. The DirectedProbe method sends a /// HTTP request to the service specified endpointAddress parameter. A service at the endpoint that /// implements matching types specified in the filters parameter should respond with a ProbeMatches /// message. The ProbeMatches mesgage is returned as the response to the DirectedProbe request. /// If a null filter is supplied any Dpws complient service should reply with a ProbeMatches reponse. /// This method is used to directly ask for service endpoint information. /// </remarks> /// <returns> /// A collection of ProbeMatches objects. A ProbeMatch object contains endpoint details used /// used to locate the actual service on a network and the types supported by the service. /// </returns> /// <exception cref="InvalidOperationException">If a fault response is received.</exception> public DpwsServiceDescriptions DirectedProbe(string endpointAddress, string targetServiceAddress, DpwsServiceTypes filters) { // Build the probe request message string messageID = null; WsMessage probeRequest = BuildProbeRequest(targetServiceAddress, filters, out messageID); System.Ext.Console.Write(""); System.Ext.Console.Write("Sending DirectedProbe:"); System.Ext.Console.Write(probeRequest.Body as byte[]); System.Ext.Console.Write(""); // Create an http client and send the probe request. Use a WspHttpClient to get an array response. WsHttpClient httpClient = new WsHttpClient(m_version); WsMessage probeResponse = httpClient.SendRequest(probeRequest, new Uri(endpointAddress)); // Build probe matches collection DpwsServiceDescriptions probeMatches = new DpwsServiceDescriptions(); DpwsDiscoClientProcessor soapProcessor = new DpwsDiscoClientProcessor(m_version); if (probeResponse != null) { System.Ext.Console.Write(""); System.Ext.Console.Write("ProbeMatches Response From: " + endpointAddress); System.Ext.Console.Write(probeResponse.Body as byte[]); try { DpwsServiceDescriptions tempMatches = soapProcessor.ProcessProbeMatch(probeResponse, messageID, null, null); if (tempMatches != null) { int count = tempMatches.Count; for (int i = 0; i < count; i++) { probeMatches.Add(tempMatches[i]); } } } catch (Exception e) { System.Ext.Console.Write(""); System.Ext.Console.Write(e.Message); System.Ext.Console.Write(""); } } if (probeMatches.Count == 0) return null; else return probeMatches; }
/// <summary> /// Builds a probe request message based on the filters parameter. /// </summary> /// <param name="serviceAddress"> /// A string containing the target service address. /// For example: urn:uuid:3cb0d1ba-cc3a-46ce-b416-212ac2419b20 /// </param> /// <param name="filters"> /// A DpwsServiceTypes object containing a collection of types a service must support to signal a match. /// Null = any type. /// </param> /// <param name="messageID"> /// A string used to return the messageID assigned to this message. /// </param> /// <returns>A byte array containing the probe message or null if an error occures.</returns> private WsMessage BuildProbeRequest(string serviceAddress, DpwsServiceTypes filters, out String messageID) { // Performance debugging DebugTiming timeDebuger = new DebugTiming(); long startTime = timeDebuger.ResetStartTime(""); WsMessage msg = null; // Build Probe request using (XmlMemoryWriter xmlWriter = XmlMemoryWriter.Create()) { WsWsaHeader header = new WsWsaHeader( m_version.DiscoveryNamespace + "/Probe", // Action null, // RelatesTo serviceAddress, // To (m_version is ProtocolVersion11? m_version.AnonymousUri : null), null, null); // ReplyTo, From, Any header.MustUnderstand = true; // If filters are supplied, write filter namespaces if prefixed. Build filter list for use later WsXmlNamespaces namespaces = new WsXmlNamespaces(); // Prefix hack for now: int i = 0; string prefix; string filterList = ""; bool spaceFlag = false; if (filters != null) { int count = filters.Count; for (int j = 0; j < count; j++) { DpwsServiceType serviceType = filters[j]; prefix = namespaces.LookupPrefix(serviceType.NamespaceUri); if (prefix == null) { prefix = "dp" + (i++); namespaces.Add(new WsXmlNamespace(prefix, serviceType.NamespaceUri)); } filterList = filterList + ((spaceFlag == true) ? " " : "") + prefix + ":" + serviceType.TypeName; spaceFlag = true; } } msg = new WsMessage(header, null, WsPrefix.Wsd, namespaces, null); WsSoapMessageWriter smw = new WsSoapMessageWriter(m_version); messageID = smw.WriteSoapMessageStart(xmlWriter, msg); // Performance debuging timeDebuger.PrintElapsedTime("*****Write Header Took"); // write body xmlWriter.WriteStartElement(WsNamespacePrefix.Wsd, "Probe", null); // If filter is supplied add filter types tag else write blank string to probe body, force an empty tag if (filterList.Length != 0) { xmlWriter.WriteStartElement(WsNamespacePrefix.Wsd, "Types", null); xmlWriter.WriteString(filterList); xmlWriter.WriteEndElement(); // End Filter } else { xmlWriter.WriteString(""); } xmlWriter.WriteEndElement(); // End Probe // Performance debuging timeDebuger.PrintElapsedTime("*****Write Body Took"); smw.WriteSoapMessageEnd(xmlWriter); // Performance debuging timeDebuger.PrintTotalTime(startTime, "***Probe Message Build Took"); // return the probe message msg.Body = xmlWriter.ToArray(); } return(msg); }
/// <summary> /// Builds a probe request message based on the filters parameter. /// </summary> /// <param name="serviceAddress"> /// A string containing the target service address. /// For example: urn:uuid:3cb0d1ba-cc3a-46ce-b416-212ac2419b20 /// </param> /// <param name="filters"> /// A DpwsServiceTypes object containing a collection of types a service must support to signal a match. /// Null = any type. /// </param> /// <param name="messageID"> /// A string used to return the messageID assigned to this message. /// </param> /// <returns>A byte array containing the probe message or null if an error occures.</returns> private byte[] BuildProbeRequest(string serviceAddress, DpwsServiceTypes filters, out String messageID) { // Performance debugging DebugTiming timeDebuger = new DebugTiming(); long startTime = timeDebuger.ResetStartTime(""); // Build Probe request MemoryStream soapStream = new MemoryStream(); XmlWriter xmlWriter = XmlWriter.Create(soapStream); WsWsaHeader header = new WsWsaHeader( WsWellKnownUri.WsdNamespaceUri + "/Probe", // Action null, // RelatesTo serviceAddress, // To null, null, null); // ReplyTo, From, Any // If filters are supplied, write filter namespaces if prefixed. Build filter list for use later, // include wsdp:device. WsXmlNamespaces namespaces = new WsXmlNamespaces(); // Prefix hack for now: int i = 0; string prefix; string filterList = ""; bool spaceFlag = false; if (filters != null) { int count = filters.Count; for (int j = 0; j < count; j++) { DpwsServiceType serviceType = filters[j]; prefix = namespaces.LookupPrefix(serviceType.NamespaceUri); if (prefix == null) { prefix = "MyPrefix" + (i++); namespaces.Add(new WsXmlNamespace(prefix, serviceType.NamespaceUri)); } filterList = filterList + ((spaceFlag == true) ? " " : "") + prefix + ":" + serviceType.TypeName; spaceFlag = true; } } messageID = WsSoapMessageWriter.WriteSoapMessageStart(xmlWriter, WsSoapMessageWriter.Prefixes.Wsd, namespaces, header, null); // Performance debuging timeDebuger.PrintElapsedTime("*****Write Header Took"); // write body xmlWriter.WriteStartElement("wsd", "Probe", null); // If filter is supplied add filter types tag else write blank string to probe body, force an empty tag if (filterList.Length != 0) { xmlWriter.WriteStartElement("wsd", "Types", null); xmlWriter.WriteString(filterList); xmlWriter.WriteEndElement(); // End Filter } else { xmlWriter.WriteString(""); } xmlWriter.WriteEndElement(); // End Probe // Performance debuging timeDebuger.PrintElapsedTime("*****Write Body Took"); WsSoapMessageWriter.WriteSoapMessageEnd(xmlWriter); // Performance debuging timeDebuger.PrintTotalTime(startTime, "***Probe Message Build Took"); // Flush and close writer xmlWriter.Flush(); xmlWriter.Close(); // return the probe message return(soapStream.ToArray()); }
/// <summary> /// Probe for a SimpleService endpoint. /// </summary> /// <param name="serviceAddress">A string containing the address of the simple service to find.</param> /// <returns> /// A DpwsMetadata object containing details about a SimpleService, null if /// a SImpleService is not found. /// </returns> public DpwsMetadata GetSimpleService(string serviceAddress) { // Resolve the service address m_dpwsClient.DiscoveryClient.ReceiveTimeout = 10000; DpwsServiceDescription resolveMatch = m_dpwsClient.DiscoveryClient.Resolve(serviceAddress); // Display results string serviceEndpoint = null; string targetService = null; if (resolveMatch != null) { // Print resolve match information System.Ext.Console.Write(""); System.Ext.Console.Write("ResolveMatch:"); System.Ext.Console.Write(" Endpoint Address = " + resolveMatch.Endpoint.Address); System.Ext.Console.Write(" Types:"); targetService = resolveMatch.Endpoint.Address.AbsoluteUri; for (int i = 0; i < resolveMatch.ServiceTypes.Count; ++i) { System.Ext.Console.Write(" Name = " + resolveMatch.ServiceTypes[i].TypeName); System.Ext.Console.Write(" Namespace = " + resolveMatch.ServiceTypes[i].NamespaceUri); } System.Ext.Console.Write(" Xaddrs:"); foreach (string xaddr in resolveMatch.XAddrs) { System.Ext.Console.Write(" TransportAddress = " + xaddr); // Since there's no support for IPV6 look for IPV4 address if (xaddr.IndexOf(':') != -1) { serviceEndpoint = xaddr; } } System.Ext.Console.Write(" Metadata Version = " + resolveMatch.MetadataVersion); } else { System.Ext.Console.Write(""); System.Ext.Console.Write("SimpleDeviceType at address: " + serviceAddress + " failed to resolve. Discovery aborted"); return(null); } // Mae sure we got an address if (serviceEndpoint == null) { System.Ext.Console.Write(""); System.Ext.Console.Write("Resolve did not send an IPV4 xaddr. Discovery aborted."); } // Send DirectedProbe DpwsMetadata m_mexDetails = null; // Create an empty search types collection DpwsServiceTypes searchTypes = new DpwsServiceTypes(); // Build a SimpleDeviceType search type DpwsServiceType searchType1 = new DpwsServiceType("SimpleDeviceType", "http://schemas.example.org/SimpleService"); searchTypes.Add(searchType1); // Get the SimpleDeviceType service details // Note: Uncomment the next line to test DirectedProbe to any MF Dpws service // DpwsServiceDescriptions probeMatches = m_dpwsClient.DiscoveryClient.DirectedProbe(serviceEndpoint, m_dpwsClient.DiscoveryClient.DiscoVersion.WellKnownAddress, searchTypes); // Note: Uncomment the next line to test against a DiscoveryProxy // DpwsServiceDescriptions probeMatches = m_dpwsClient.DiscoveryClient.DirectedProbe(serviceEndpoint, targetService, searchTypes); DpwsServiceDescriptions probeMatches = m_dpwsClient.DiscoveryClient.Probe(searchTypes); if (probeMatches != null && probeMatches.Count > 0) { // Select the probe match DpwsServiceDescription probeMatch = probeMatches[0]; // Note: Uncoment the following line to test DirectedResolve against any MF Dpws Service. // DpwsServiceDescription resolveMatch1 = m_dpwsClient.DiscoveryClient.DirectedResolve(probeMatch.XAddrs[0], m_dpwsClient.DiscoveryClient.DiscoVersion.WellKnownAddress, serviceAddress); // Print the probe match information System.Ext.Console.Write("**********************"); System.Ext.Console.Write("ProbeMatch received: " + probeMatches.Count); System.Ext.Console.Write(""); System.Ext.Console.Write("ProbeMatch:"); System.Ext.Console.Write(" Endpoint Address = " + probeMatch.Endpoint.Address); System.Ext.Console.Write(" Types:"); for (int i = 0; i < probeMatch.ServiceTypes.Count; ++i) { System.Ext.Console.Write(" Name = " + probeMatch.ServiceTypes[i].TypeName); System.Ext.Console.Write(" Namespace = " + probeMatch.ServiceTypes[i].NamespaceUri); } System.Ext.Console.Write(" Xaddrs:"); foreach (string xaddr in probeMatch.XAddrs) { System.Ext.Console.Write(" TransportAddress = " + xaddr); } System.Ext.Console.Write(" Metadata Version = " + probeMatch.MetadataVersion); } // If we had a probe match store the service endpoint and get metadata if (probeMatches != null) { m_dpwsClient.EndpointAddress = serviceAddress; m_mexDetails = m_dpwsClient.MexClient.Get(serviceEndpoint); if (m_mexDetails == null) { System.Ext.Console.Write(""); System.Ext.Console.Write("Get did not receive metadata. Discovery aborted."); return(null); } // Display metadata information System.Ext.Console.Write(" Metadata:"); System.Ext.Console.Write(" ThisModel:"); System.Ext.Console.Write(" Manufacturer: " + m_mexDetails.ThisModel.Manufacturer); System.Ext.Console.Write(" ManufacturerUrl: " + m_mexDetails.ThisModel.ManufacturerUrl); System.Ext.Console.Write(" ModelName: " + m_mexDetails.ThisModel.ModelName); System.Ext.Console.Write(" ModelNumber: " + m_mexDetails.ThisModel.ModelNumber); System.Ext.Console.Write(" ModelUrl: " + m_mexDetails.ThisModel.ModelUrl); System.Ext.Console.Write(" PresentationUrl: " + m_mexDetails.ThisModel.PresentationUrl); System.Ext.Console.Write(" ThisDevice:"); System.Ext.Console.Write(" FirmwareVersion: " + m_mexDetails.ThisDevice.FirmwareVersion); System.Ext.Console.Write(" FriendlyName: " + m_mexDetails.ThisDevice.FriendlyName); System.Ext.Console.Write(" SerialNumber: " + m_mexDetails.ThisDevice.SerialNumber); if (m_mexDetails.Relationship.Host != null) { System.Ext.Console.Write(" Host:"); System.Ext.Console.Write(" Service ID: " + m_mexDetails.Relationship.Host.ServiceID); System.Ext.Console.Write(" Address: " + m_mexDetails.Relationship.Host.EndpointRefs[0].Address.AbsoluteUri); System.Ext.Console.Write(" Types:"); for (int i = 0; i < m_mexDetails.Relationship.Host.ServiceTypes.Count; ++i) { DpwsServiceType serviceType = m_mexDetails.Relationship.Host.ServiceTypes[i]; System.Ext.Console.Write(" Name: " + serviceType.TypeName); System.Ext.Console.Write(" NamespaceUri: " + serviceType.NamespaceUri); } } if (m_mexDetails.Relationship.HostedServices != null) { System.Ext.Console.Write(" HostedServices:"); for (int i = 0; i < m_mexDetails.Relationship.HostedServices.Count; ++i) { DpwsMexService hostedService = m_mexDetails.Relationship.HostedServices[i]; System.Ext.Console.Write(" Service ID: " + hostedService.ServiceID); System.Ext.Console.Write(" Address: " + hostedService.EndpointRefs[0].Address.AbsoluteUri); System.Ext.Console.Write(" Types:"); for (int ii = 0; ii < hostedService.ServiceTypes.Count; ++ii) { System.Ext.Console.Write(" Type name: " + hostedService.ServiceTypes[ii].TypeName); System.Ext.Console.Write(" NamespaceUri: " + hostedService.ServiceTypes[ii].NamespaceUri); } } } } return(m_mexDetails); }
/// <summary> /// Sends a Probe request and parses ProbeMatches responses. /// </summary> /// <param name="filters"> /// A DpwsServiceTypes object containing a collection of types a service must support to signal a match. /// Null = any type. /// </param> /// <remarks> /// A Probe is used to discover services on a network. The Probe method sends a UDP request to the /// Dpws multicast address, 239.255.255.250:3702. Any service that implements types specified in the /// filters parameter should respond with a ProbeMatches message. The ProbeMatches mesgage is unicast /// back to the that client that made the request. If a null filter is supplied any Dpws complient /// service should reply with a ProbeMatches reponse. Probe waits DpwsDiscoveryClient.ReceiveTimout /// for probe matches. /// </remarks> /// <returns> /// A collection of ProbeMatches objects. A ProbeMatch object contains endpoint details used /// used to locate the actual service on a network and the types supported by the service. /// </returns> public DpwsServiceDescriptions Probe(DpwsServiceTypes filters) { return(Probe(filters, 5, m_receiveTimeout)); }
/// <summary> /// Sends a Probe request and parses ProbeMatches responses. /// </summary> /// <param name="filters"> /// A DpwsServiceTypes object containing a collection of types a service must support to signal a match. /// Null = any type. /// </param> /// <remarks> /// A Probe is used to discover services on a network. The Probe method sends a UDP request to the /// Dpws multicast address, 239.255.255.250:3702. Any service that implements types specified in the /// filters parameter should respond with a ProbeMatches message. The ProbeMatches mesgage is unicast /// back to the that client that made the request. If a null filter is supplied any Dpws complient /// service should reply with a ProbeMatches reponse. Probe waits DpwsDiceoveryCleint.ReceiveTimout /// for probe matches. /// </remarks> /// <returns> /// A collection of ProbeMatches objects. A ProbeMatch object contains endpoint details used /// used to locate the actual service on a network and the types supported by the service. /// </returns> public DpwsServiceDescriptions Probe(DpwsServiceTypes filters) { return(Probe(filters, 0, -1)); }
public MFTestResults DiscoveryTest_DpwsServiceDescription() { /// <summary> /// 1. Verifies each of the proerties of a ByeEventArgs object /// 2. Sets and re-verifies for simple properties. /// </summary> /// ProtocolVersion v = new ProtocolVersion10(); bool testResult = true; try { WsWsaEndpointRef ep = new WsWsaEndpointRef(new System.Uri(v.AnonymousUri)); DpwsServiceTypes st = new DpwsServiceTypes(); DpwsServiceDescription testBEA = new DpwsServiceDescription(ep, st); Log.Comment("Endpoint"); if (testBEA.Endpoint != null) { if (testBEA.Endpoint.GetType() != Type.GetType("Ws.Services.WsaAddressing.WsWsaEndpointRef")) { throw new Exception("Endpoint wrong type"); } } if (testBEA.Endpoint != ep) { throw new Exception("Endpoint bad data"); } Log.Comment("MetadataVersion"); if (testBEA.MetadataVersion != null) { if (testBEA.MetadataVersion.GetType() != Type.GetType("System.String")) { throw new Exception("MetadataVersion wrong type"); } } if (testBEA.MetadataVersion != null) { throw new Exception("MetadataVersion bad data"); } Log.Comment("XAddrs"); if (testBEA.XAddrs != null) { if (testBEA.XAddrs.GetType() != Type.GetType("System.String")) { throw new Exception("XAddrs wrong type"); } } if (testBEA.XAddrs != null) { throw new Exception("XAddrs bad data"); } Log.Comment("ServiceTypes"); if (testBEA.ServiceTypes != null) { if (testBEA.ServiceTypes.GetType() != Type.GetType("Dpws.Client.DpwsServiceTypes")) { throw new Exception("ServiceTypes wrong type"); } } if (testBEA.ServiceTypes.Count != 0) { throw new Exception("ServiceTypes bad data"); } } catch (Exception e) { testResult = false; Log.Comment("Incorrect exception caught: " + e.Message); } return(testResult ? MFTestResults.Pass : MFTestResults.Fail); }
/// <summary> /// Sends a Probe request and parses ProbeMatches responses. /// </summary> /// <param name="filters"> /// A DpwsServiceTypes object containing a collection of types a service must support to signal a match. /// Null = any type. /// </param> /// <param name="maxProbeMatches"> /// An integer representing the maximum number of matches to reveive within the timout period. Pass 0 to receive /// as many matches as possible before the timeout expires. /// </param> /// <param name="timeout"> /// An integer specifying a request timeout in milliseconds. Pass -1 to wait ReceiveTimeout. /// </param> /// <remarks> /// A Probe is used to discover services on a network. The Probe method sends a UDP request to the /// Dpws multicast address, 239.255.255.250:3702. Any service that implements types specified in the /// filters parameter should respond with a ProbeMatches message. The ProbeMatches mesgage is unicast /// back to the that client that made the request. If a null filter is supplied any Dpws complient /// service should reply with a ProbeMatches reponse. Probe waits DpwsDiceoveryCleint.ReceiveTimout /// for probe matches. /// </remarks> /// <returns> /// A collection of ProbeMatches objects. A ProbeMatch object contains endpoint details used /// used to locate the actual service on a network and the types supported by the service. /// </returns> public DpwsServiceDescriptions Probe(DpwsServiceTypes filters, int maxProbeMatches, int timeout) { // Build the probe request message WsMessageCheck messageCheck = new WsMessageCheck(); string messageID = null; byte[] probeRequest = BuildProbeRequest(DiscoVersion.WellKnownAddress, filters, out messageID); System.Ext.Console.Write(""); System.Ext.Console.Write("Sending Probe:"); System.Ext.Console.Write(new string(new UTF8Encoding().GetChars(probeRequest))); System.Ext.Console.Write(""); // Create a new UdpClient Socket udpClient = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); IPEndPoint localEP = new IPEndPoint(IPAddress.Any, m_discoResponsePort); udpClient.Bind(localEP); // Very important - Set default multicast interface for the underlying socket byte[] ipBytes = IPAddress.Parse(WsNetworkServices.GetLocalIPV4Address()).GetAddressBytes(); long longIP = (long)((ipBytes[0] + (ipBytes[1] << 0x08) + (ipBytes[2] << 0x10) + (ipBytes[3] << 0x18)) & 0xFFFFFFFF); udpClient.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastInterface, (int)longIP); // Random back off implemented as per soap over udp specification // for unreliable multicast message exchange SendWithBackoff(probeRequest, udpClient); // Create probe matches collection and set expiration loop timer DpwsServiceDescriptions probeMatches = new DpwsServiceDescriptions(); byte[] probeResponse = new byte[c_MaxUdpPacketSize]; EndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0); int responseLength; // Multiply receive time by 10000 to convert milliseconds to 100 nano ticks long endTime = (long)(DateTime.Now.Ticks + (timeout < 0 ? m_receiveTimeout * 10000 : timeout * 10000)); DpwsDiscoClientProcessor soapProcessor = new DpwsDiscoClientProcessor(); // Build probe matches collection as long as timeout has not expired int noReceived = 0; while (DateTime.Now.Ticks < endTime) { if (udpClient.Available > 0) { // If maxProbeRequest is set check count if (maxProbeMatches > 0) { if (noReceived > maxProbeMatches) break; } // Since MF sockets does not have an IOControl method catch 10054 to get around the problem // with Upd and ICMP. try { // Wait for response responseLength = udpClient.ReceiveFrom(probeResponse, c_MaxUdpPacketSize, SocketFlags.None, ref remoteEP); } catch (SocketException se) { if (se.ErrorCode == 10054) continue; throw se; } // If we received process probe match if (responseLength > 0) { System.Ext.Console.Write(""); System.Ext.Console.Write("ProbeMatches Response From: " + ((IPEndPoint)remoteEP).Address.ToString()); System.Ext.Console.Write(new String(System.Text.Encoding.UTF8.GetChars(probeResponse))); // Process the response try { DpwsServiceDescriptions tempMatches = soapProcessor.ProcessProbeMatch(probeResponse, messageID, (IPEndPoint)remoteEP, messageCheck); if (tempMatches != null) { int count = tempMatches.Count; for (int i = 0; i < count; i++) { probeMatches.Add(tempMatches[i]); } } } catch (Exception e) { System.Ext.Console.Write(""); System.Ext.Console.Write(e.Message); System.Ext.Console.Write(""); } // Increment the number received counter ++noReceived; } } else { Thread.Sleep(1); } } udpClient.Close(); udpClient = null; // Display results if (probeMatches == null) System.Ext.Console.Write("Probe timed out."); else System.Ext.Console.Write("Received " + probeMatches.Count + " probeMatches matches."); return probeMatches; }
/// <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) { DpwsServiceDescriptions descs = m_simpleServiceClient.DiscoveryClient.Probe(typeProbes, 3, 1000); for (int i = 0; i < descs.Count; i++) { DpwsServiceDescription desc = descs[i]; if (desc.XAddrs != null && desc.XAddrs.Length > 0) { CheckConnection(desc.ServiceTypes, desc.Endpoint.Address.AbsoluteUri); } } } // 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) { // Test service host call System.Ext.Console.Write("Testing Host service..."); DpwsSubscribeRequest subReq; subReq = new DpwsSubscribeRequest(m_eventingServiceClient.EventSources["SimpleEvent"], m_eventingServiceClient.EndpointAddress, m_eventingServiceClient.TransportAddress, "PT1H", null); m_simpleEventSubscription = m_eventingServiceClient.EventingClient.Subscribe(subReq); subReq = new DpwsSubscribeRequest(m_eventingServiceClient.EventSources["IntegerEvent"], m_eventingServiceClient.EndpointAddress, m_eventingServiceClient.TransportAddress, "PT1H", null); m_integerEventSubscription = m_eventingServiceClient.EventingClient.Subscribe(subReq); firstPass = false; } // Make 1Way and 2Way service calls if (m_deviceSelected.WaitOne(0, false)) { PrintMetadataInfo(); System.Ext.Console.Write(""); System.Ext.Console.Write(">>>>>>>>>>>>> Sending 1way(10) request to: " + m_selectedService.ThisDevice.FriendlyName); try { m_simpleServiceClient.OneWay(new OneWayRequest()); } catch (Exception e) { 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) { 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) { 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) { System.Ext.Console.Write(""); System.Ext.Console.Write("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! TwoWay method failed. " + e.Message); } } twoWayAttach = !twoWayAttach; } } else { firstPass = true; } } }
/// <summary> /// Builds a probe request message based on the filters parameter. /// </summary> /// <param name="serviceAddress"> /// A string containing the target service address. /// For example: urn:uuid:3cb0d1ba-cc3a-46ce-b416-212ac2419b20 /// </param> /// <param name="filters"> /// A DpwsServiceTypes object containing a collection of types a service must support to signal a match. /// Null = any type. /// </param> /// <param name="messageID"> /// A string used to return the messageID assigned to this message. /// </param> /// <returns>A byte array containing the probe message or null if an error occures.</returns> private byte[] BuildProbeRequest(string serviceAddress, DpwsServiceTypes filters, out String messageID) { // Performance debugging DebugTiming timeDebuger = new DebugTiming(); long startTime = timeDebuger.ResetStartTime(""); // Build Probe request MemoryStream soapStream = new MemoryStream(); XmlWriter xmlWriter = XmlWriter.Create(soapStream); WsWsaHeader header = new WsWsaHeader( WsWellKnownUri.WsdNamespaceUri + "/Probe", // Action null, // RelatesTo serviceAddress, // To null, null, null); // ReplyTo, From, Any // If filters are supplied, write filter namespaces if prefixed. Build filter list for use later, // include wsdp:device. WsXmlNamespaces namespaces = new WsXmlNamespaces(); // Prefix hack for now: int i = 0; string prefix; string filterList = ""; bool spaceFlag = false; if (filters != null) { int count = filters.Count; for (int j = 0; j < count; j++) { DpwsServiceType serviceType = filters[j]; prefix = namespaces.LookupPrefix(serviceType.NamespaceUri); if (prefix == null) { prefix = "MyPrefix" + (i++); namespaces.Add(new WsXmlNamespace(prefix, serviceType.NamespaceUri)); } filterList = filterList + ((spaceFlag == true) ? " " : "") + prefix + ":" + serviceType.TypeName; spaceFlag = true; } } messageID = WsSoapMessageWriter.WriteSoapMessageStart(xmlWriter, WsSoapMessageWriter.Prefixes.Wsd, namespaces, header, null); // Performance debuging timeDebuger.PrintElapsedTime("*****Write Header Took"); // write body xmlWriter.WriteStartElement("wsd", "Probe", null); // If filter is supplied add filter types tag else write blank string to probe body, force an empty tag if (filterList.Length != 0) { xmlWriter.WriteStartElement("wsd", "Types", null); xmlWriter.WriteString(filterList); xmlWriter.WriteEndElement(); // End Filter } else xmlWriter.WriteString(""); xmlWriter.WriteEndElement(); // End Probe // Performance debuging timeDebuger.PrintElapsedTime("*****Write Body Took"); WsSoapMessageWriter.WriteSoapMessageEnd(xmlWriter); // Performance debuging timeDebuger.PrintTotalTime(startTime, "***Probe Message Build Took"); // Flush and close writer xmlWriter.Flush(); xmlWriter.Close(); // return the probe message return soapStream.ToArray(); }
void SimpleServiceClient_HelloEvent(object obj, DpwsServiceDescription helloEventArgs) { m_receivedHelloEvent = true; DpwsMetadata m_mexDetails = null; try { // Print Hello information //Log.Comment(""); //Log.Comment("SimpleService received a hello request."); ////Log.Comment("Endpoint address: " + helloEventArgs.Endpoint.Address.AbsoluteUri); string types = ""; int count = helloEventArgs.ServiceTypes.Count; for (int i = 0; i < count; i++) { DpwsServiceType type = helloEventArgs.ServiceTypes[i]; types += "NamespaceUri: " + type.NamespaceUri + " " + "TypeName: " + type.TypeName + "\n"; } ////Log.Comment("Types: " + types); if (helloEventArgs.XAddrs != null) { foreach (String xaddr in helloEventArgs.XAddrs) { ////Log.Comment("Xaddrs: " + xaddr); } } ////Log.Comment("Metadata version: " + helloEventArgs.MetadataVersion); ////Log.Comment(""); // Probe for services. For each valid probe match, print service information. DpwsServiceType searchType = new DpwsServiceType("SimpleService", "http://schemas.example.org/SimpleService"); DpwsServiceTypes searchTypes = new DpwsServiceTypes(); searchTypes.Add(searchType); // Accept the first 10 found within the first 10 seconds DpwsServiceDescriptions probeMatches = this.DiscoveryClient.Probe(searchTypes, 1, 10000); // retry if (probeMatches.Count == 0) { probeMatches = this.DiscoveryClient.Probe(searchTypes, 1, 10000); } if (probeMatches != null) { // Print the probe match information ////Log.Comment("**********************"); ////Log.Comment("ProbeMatches received: " + probeMatches.Count); int probeMatchCount = probeMatches.Count; for (int i = 0; i < probeMatchCount; i++) { DpwsServiceDescription probeMatch = probeMatches[i]; ////Log.Comment(""); ////Log.Comment("ProbeMatch:"); ////Log.Comment(" Endpoint Address = " + probeMatch.Endpoint.Address.AbsoluteUri); ////Log.Comment(" Types:"); PrintServiceTypes(probeMatch.ServiceTypes); //////Log.Comment(" Xaddrs:"); //foreach (string xaddr in probeMatch.XAddrs) // //Log.Comment(" TransportAddress = " + xaddr); ////Log.Comment(" Metadata Version = " + probeMatch.MetadataVersion); // Resolve this endpoint DpwsServiceDescription resolveMatch = this.DiscoveryClient.Resolve(probeMatch.Endpoint.Address.AbsoluteUri, 10000); if (resolveMatch != null) { // Print resolve match information ////Log.Comment(""); ////Log.Comment("ResolveMatch:"); ////Log.Comment(" Endpoint Address = " + resolveMatch.Endpoint.Address.AbsoluteUri); ////Log.Comment(" Types:"); PrintServiceTypes(resolveMatch.ServiceTypes); ////Log.Comment(" Xaddrs:"); //foreach (string xaddr in resolveMatch.XAddrs) // //Log.Comment(" TransportAddress = " + xaddr); //Log.Comment(" Metadata Version = " + resolveMatch.MetadataVersion); // For each Xaddr, get metadata foreach (string xaddr in resolveMatch.XAddrs) { // Call Get m_mexDetails = this.MexClient.Get(xaddr); if (m_mexDetails == null) { ////Log.Comment("Get failed. Address: " + xaddr); } else { m_getMex = true; // Display metadata information ////Log.Comment(" Metadata:"); ////Log.Comment(" ThisModel:"); ////Log.Comment(" Manufacturer: " + m_mexDetails.ThisModel.Manufacturer); ////Log.Comment(" ManufacturerUrl: " + m_mexDetails.ThisModel.ManufacturerUrl); ////Log.Comment(" ModelName: " + m_mexDetails.ThisModel.ModelName); ////Log.Comment(" ModelNumber: " + m_mexDetails.ThisModel.ModelNumber); ////Log.Comment(" ModelUrl: " + m_mexDetails.ThisModel.ModelUrl); ////Log.Comment(" PresentationUrl: " + m_mexDetails.ThisModel.PresentationUrl); ////Log.Comment(" ThisDevice:"); ////Log.Comment(" FirmwareVersion: " + m_mexDetails.ThisDevice.FirmwareVersion); ////Log.Comment(" FriendlyName: " + m_mexDetails.ThisDevice.FriendlyName); ////Log.Comment(" SerialNumber: " + m_mexDetails.ThisDevice.SerialNumber); if (m_mexDetails.Relationship.Host != null) { ////Log.Comment(" Host:"); ////Log.Comment(" Service ID: " + m_mexDetails.Relationship.Host.ServiceID); ////Log.Comment(" Address: " + m_mexDetails.Relationship.Host.EndpointRefs[0].Address.AbsoluteUri); ////Log.Comment(" Types:"); PrintServiceTypes(m_mexDetails.Relationship.Host.ServiceTypes); } if (m_mexDetails.Relationship.HostedServices != null) { ////Log.Comment(" HostedServices:"); int hostedServiceCount = m_mexDetails.Relationship.HostedServices.Count; for (int j = 0; j < hostedServiceCount; j++) { DpwsMexService hostedService = m_mexDetails.Relationship.HostedServices[j]; ////Log.Comment(" Service ID: " + hostedService.ServiceID); ////Log.Comment(" Address: " + hostedService.EndpointRefs[0].Address.AbsoluteUri); ////Log.Comment(" Types:"); PrintServiceTypes(hostedService.ServiceTypes); } } } } if (m_mexDetails != null) { // Look for the SimpleService in the HostedServices collection, create an HTTP // client, call TwoWayRequest on the service endpoint, and display the result. int hostedServiceCount = m_mexDetails.Relationship.HostedServices.Count; for (int j = 0; j < hostedServiceCount; j++) { DpwsMexService hostedService = m_mexDetails.Relationship.HostedServices[j]; if (hostedService.ServiceTypes["SimpleService"] != null) // found a SimpleService endpoint { string endpointAddress = hostedService.EndpointRefs[0].Address.AbsoluteUri; ////Log.Comment(""); ////Log.Comment("Calling TwoWayRequest at endpoint: " + endpointAddress); // Create HttpClient and send request int x = 150; int y = 180; byte[] TwoWayRequest = Build2wayRequest(x, y, endpointAddress); //Log.Comment(new String(System.Text.Encoding.UTF8.GetChars(TwoWayRequest))); //DpwsHttpClient httpClient = new DpwsHttpClient(); //DpwsSoapResponse response = httpClient.SendRequest(TwoWayRequest, endpointAddress, false, false); WsHttpClient httpClient = new WsHttpClient(m_version); WsMessage response = httpClient.SendRequest(new WsMessage(null, TwoWayRequest, WsPrefix.Wsdp), new Uri(endpointAddress)); if (response != null) // got a response { try { int sum = Parse2WayResponse(response.Header, response.Reader); //Log.Comment(""); //Log.Comment("Received sum of " + sum.ToString() + " from " + endpointAddress); if ((x + y) == sum) { m_twoWay = true; } } finally { response.Reader.Close(); } } } } } //Log.Comment(""); } } } } finally { } if (m_mexDetails != null) { arHello.Set(); } }
/// <summary> /// Sends a Probe request and parses ProbeMatches responses. /// </summary> /// <param name="filters"> /// A DpwsServiceTypes object containing a collection of types a service must support to signal a match. /// Null = any type. /// </param> /// <remarks> /// A Probe is used to discover services on a network. The Probe method sends a UDP request to the /// Dpws multicast address, 239.255.255.250:3702. Any service that implements types specified in the /// filters parameter should respond with a ProbeMatches message. The ProbeMatches mesgage is unicast /// back to the that client that made the request. If a null filter is supplied any Dpws complient /// service should reply with a ProbeMatches reponse. Probe waits DpwsDiscoveryClient.ReceiveTimout /// for probe matches. /// </remarks> /// <returns> /// A collection of ProbeMatches objects. A ProbeMatch object contains endpoint details used /// used to locate the actual service on a network and the types supported by the service. /// </returns> public DpwsServiceDescriptions Probe(DpwsServiceTypes filters) { return Probe(filters, 5, m_receiveTimeout); }
/// <summary> /// Sends a directed Probe request and parses ProbeMatches responses. /// </summary> /// <param name="endpointAddress"> /// A string containing a Dpws devices transport endpoint address. /// For example: http://192.168.0.1:8084/3cb0d1ba-cc3a-46ce-b416-212ac2419b20 /// </param> /// <param name="targetServiceAddress"> /// A string containing the target service address to probe for. /// For example: urn:uuid:3cb0d1ba-cc3a-46ce-b416-212ac2419b20 /// </param> /// <param name="filters"> /// A DpwsServiceTypes object containing a collection of types a service must support to signal a match. /// Null = any type. /// </param> /// <remarks> /// A directed Probe is used to discover services on a network. The DirectedProbe method sends a /// HTTP request to the service specified endpointAddress parameter. A service at the endpoint that /// implements matching types specified in the filters parameter should respond with a ProbeMatches /// message. The ProbeMatches mesgage is returned as the response to the DirectedProbe request. /// If a null filter is supplied any Dpws complient service should reply with a ProbeMatches reponse. /// This method is used to directly ask for service endpoint information. /// </remarks> /// <returns> /// A collection of ProbeMatches objects. A ProbeMatch object contains endpoint details used /// used to locate the actual service on a network and the types supported by the service. /// </returns> /// <exception cref="InvalidOperationException">If a fault response is received.</exception> public DpwsServiceDescriptions DirectedProbe(string endpointAddress, string targetServiceAddress, DpwsServiceTypes filters) { // Build the probe request message string messageID = null; WsMessage probeRequest = BuildProbeRequest(targetServiceAddress, filters, out messageID); System.Ext.Console.Write(""); System.Ext.Console.Write("Sending DirectedProbe:"); System.Ext.Console.Write(probeRequest.Body as byte[]); System.Ext.Console.Write(""); // Create an http client and send the probe request. Use a WspHttpClient to get an array response. WsHttpClient httpClient = new WsHttpClient(m_version); WsMessage probeResponse = httpClient.SendRequest(probeRequest, new Uri(endpointAddress)); // Build probe matches collection DpwsServiceDescriptions probeMatches = new DpwsServiceDescriptions(); DpwsDiscoClientProcessor soapProcessor = new DpwsDiscoClientProcessor(m_version); if (probeResponse != null) { System.Ext.Console.Write(""); System.Ext.Console.Write("ProbeMatches Response From: " + endpointAddress); System.Ext.Console.Write(probeResponse.Body as byte[]); try { DpwsServiceDescriptions tempMatches = soapProcessor.ProcessProbeMatch(probeResponse, messageID, null, null); if (tempMatches != null) { int count = tempMatches.Count; for (int i = 0; i < count; i++) { probeMatches.Add(tempMatches[i]); } } } catch (Exception e) { System.Ext.Console.Write(""); System.Ext.Console.Write(e.Message); System.Ext.Console.Write(""); } } if (probeMatches.Count == 0) { return(null); } else { return(probeMatches); } }
public DpwsMexService(XmlReader reader, ProtocolVersion version) { reader.ReadStartElement(); this.EndpointRefs = new WsWsaEndpointRefs(); while (reader.IsStartElement("EndpointReference", version.AddressingNamespace)) { this.EndpointRefs.Add(new WsWsaEndpointRef(reader, version.AddressingNamespace)); } if (EndpointRefs.Count == 0) { throw new XmlException(); // must have at least one EndpointReference } if (reader.IsStartElement("Types", version.WsdpNamespaceUri)) { this.ServiceTypes = new DpwsServiceTypes(reader); } this.ServiceID = reader.ReadElementString("ServiceId", version.WsdpNamespaceUri); XmlReaderHelper.SkipAllSiblings(reader); // xs:any reader.ReadEndElement(); }
/// <summary> /// Sends a Probe request and parses ProbeMatches responses. /// </summary> /// <param name="filters"> /// A DpwsServiceTypes object containing a collection of types a service must support to signal a match. /// Null = any type. /// </param> /// <param name="maxProbeMatches"> /// An integer representing the maximum number of matches to reveive within the timout period. Pass 0 to receive /// as many matches as possible before the timeout expires. /// </param> /// <param name="timeout"> /// An integer specifying a request timeout in milliseconds. Pass -1 to wait ReceiveTimeout. /// </param> /// <remarks> /// A Probe is used to discover services on a network. The Probe method sends a UDP request to the /// Dpws multicast address, 239.255.255.250:3702. Any service that implements types specified in the /// filters parameter should respond with a ProbeMatches message. The ProbeMatches mesgage is unicast /// back to the that client that made the request. If a null filter is supplied any Dpws complient /// service should reply with a ProbeMatches reponse. Probe waits DpwsDiceoveryCleint.ReceiveTimout /// for probe matches. /// </remarks> /// <returns> /// A collection of ProbeMatches objects. A ProbeMatch object contains endpoint details used /// used to locate the actual service on a network and the types supported by the service. /// </returns> public DpwsServiceDescriptions Probe(DpwsServiceTypes filters, int maxProbeMatches, int timeout) { // Build the probe request message WsMessageCheck messageCheck = new WsMessageCheck(); string messageID = null; WsMessage probeRequest = BuildProbeRequest(DiscoVersion.DiscoveryWellKnownAddress, filters, out messageID); DpwsServiceDescriptions probeMatches = new DpwsServiceDescriptions(); System.Ext.Console.Write(""); System.Ext.Console.Write("Sending Probe:"); System.Ext.Console.Write(probeRequest.Body as byte[]); System.Ext.Console.Write(""); // Create a new UdpClient using (Socket udpClient = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) { // Very important - Set default multicast interface for the underlying socket uint ipLocal = WsNetworkServices.GetLocalIPV4AddressValue(); IPAddress localIP = IPAddress.Parse(WsNetworkServices.GetLocalIPV4Address()); IPEndPoint localEP = new IPEndPoint(localIP, 0); udpClient.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastInterface, (int)ipLocal); udpClient.ReceiveTimeout = timeout; udpClient.Bind(localEP); // Random back off implemented as per soap over udp specification // for unreliable multicast message exchange Thread th = SendWithBackoff((byte[])probeRequest.Body, udpClient); // Create probe matches collection and set expiration loop timer byte[] probeResponse = new byte[c_MaxUdpPacketSize]; EndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0); int responseLength; DpwsDiscoClientProcessor soapProcessor = new DpwsDiscoClientProcessor(m_version); while (true) { // Since MF sockets does not have an IOControl method catch 10054 to get around the problem // with Upd and ICMP. try { // Wait for response responseLength = udpClient.ReceiveFrom(probeResponse, c_MaxUdpPacketSize, SocketFlags.None, ref remoteEP); } catch (SocketException se) { if ((SocketError)se.ErrorCode == SocketError.ConnectionReset) { Thread.Sleep(100); continue; } // Timeout if ((SocketError)se.ErrorCode == SocketError.TimedOut) { break; } throw se; } // If we received process probe match if (responseLength > 0) { System.Ext.Console.Write(""); System.Ext.Console.Write("ProbeMatches Response From: " + ((IPEndPoint)remoteEP).Address.ToString()); System.Ext.Console.Write(probeResponse); // Process the response try { WsWsaHeader header = new WsWsaHeader(); XmlReader reader = WsSoapMessageParser.ParseSoapMessage(probeResponse, ref header, m_version); WsMessage msg = new WsMessage(header, null, WsPrefix.Wsdp); msg.Reader = reader; DpwsServiceDescriptions tempMatches = soapProcessor.ProcessProbeMatch(msg, messageID, (IPEndPoint)remoteEP, messageCheck); if (tempMatches != null) { int count = maxProbeMatches < tempMatches.Count ? maxProbeMatches : tempMatches.Count; for (int i = 0; i < count; i++) { probeMatches.Add(tempMatches[i]); } maxProbeMatches -= count; } } catch (Exception e) { System.Ext.Console.Write(""); System.Ext.Console.Write(e.Message); System.Ext.Console.Write(""); } // If maxProbeRequest is set check count if (maxProbeMatches <= 0) { break; } } } th.Join(); } // Display results if (probeMatches.Count == 0) { System.Ext.Console.Write("Probe timed out."); } else { System.Ext.Console.Write("Received " + probeMatches.Count + " probeMatches matches."); } return(probeMatches); }
public DpwsMexService(XmlReader reader) { reader.ReadStartElement(); this.EndpointRefs = new WsWsaEndpointRefs(); while ( (reader.IsStartElement("EndpointReference", WsWellKnownUri.WsaNamespaceUri_2005_08)) || (reader.IsStartElement("EndpointReference", WsWellKnownUri.WsaNamespaceUri_2004_08)) ) { this.EndpointRefs.Add(new WsWsaEndpointRef(reader)); } if (EndpointRefs.Count == 0) { throw new XmlException(); // must have at least one EndpointReference } if (reader.IsStartElement("Types", WsWellKnownUri.WsdpNamespaceUri)) { this.ServiceTypes = new DpwsServiceTypes(reader); } this.ServiceID = reader.ReadElementString("ServiceId", WsWellKnownUri.WsdpNamespaceUri); XmlReaderHelper.SkipAllSiblings(reader); // xs:any reader.ReadEndElement(); }
/// <summary> /// Creates an instance of a DpwsServiceDescription class initialized with a service endpoint and a list of /// supported service types. /// </summary> /// <param name="endpoint">A WsWsaEndpointRef object containing a Dpws Device servie endpoint.</param> /// <param name="serviceTypes">A string array containing a list of service types supporte by a Dpws devie service endpoint.</param> public DpwsServiceDescription(WsWsaEndpointRef endpoint, DpwsServiceTypes serviceTypes) { this.Endpoint = endpoint; this.ServiceTypes = serviceTypes; }
/// <summary> /// Sends a Probe request and parses ProbeMatches responses. /// </summary> /// <param name="filters"> /// A DpwsServiceTypes object containing a collection of types a service must support to signal a match. /// Null = any type. /// </param> /// <param name="maxProbeMatches"> /// An integer representing the maximum number of matches to reveive within the timout period. Pass 0 to receive /// as many matches as possible before the timeout expires. /// </param> /// <param name="timeout"> /// An integer specifying a request timeout in milliseconds. Pass -1 to wait ReceiveTimeout. /// </param> /// <remarks> /// A Probe is used to discover services on a network. The Probe method sends a UDP request to the /// Dpws multicast address, 239.255.255.250:3702. Any service that implements types specified in the /// filters parameter should respond with a ProbeMatches message. The ProbeMatches mesgage is unicast /// back to the that client that made the request. If a null filter is supplied any Dpws complient /// service should reply with a ProbeMatches reponse. Probe waits DpwsDiceoveryCleint.ReceiveTimout /// for probe matches. /// </remarks> /// <returns> /// A collection of ProbeMatches objects. A ProbeMatch object contains endpoint details used /// used to locate the actual service on a network and the types supported by the service. /// </returns> public DpwsServiceDescriptions Probe(DpwsServiceTypes filters, int maxProbeMatches, int timeout) { // Build the probe request message WsMessageCheck messageCheck = new WsMessageCheck(); string messageID = null; byte[] probeRequest = BuildProbeRequest(DiscoVersion.WellKnownAddress, filters, out messageID); System.Ext.Console.Write(""); System.Ext.Console.Write("Sending Probe:"); System.Ext.Console.Write(new string(new UTF8Encoding().GetChars(probeRequest))); System.Ext.Console.Write(""); // Create a new UdpClient Socket udpClient = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); IPEndPoint localEP = new IPEndPoint(IPAddress.Any, m_discoResponsePort); udpClient.Bind(localEP); // Very important - Set default multicast interface for the underlying socket byte[] ipBytes = IPAddress.Parse(WsNetworkServices.GetLocalIPV4Address()).GetAddressBytes(); long longIP = (long)((ipBytes[0] + (ipBytes[1] << 0x08) + (ipBytes[2] << 0x10) + (ipBytes[3] << 0x18)) & 0xFFFFFFFF); udpClient.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastInterface, (int)longIP); // Random back off implemented as per soap over udp specification // for unreliable multicast message exchange SendWithBackoff(probeRequest, udpClient); // Create probe matches collection and set expiration loop timer DpwsServiceDescriptions probeMatches = new DpwsServiceDescriptions(); byte[] probeResponse = new byte[c_MaxUdpPacketSize]; EndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0); int responseLength; // Multiply receive time by 10000 to convert milliseconds to 100 nano ticks long endTime = (long)(DateTime.Now.Ticks + (timeout < 0 ? m_receiveTimeout * 10000 : timeout * 10000)); DpwsDiscoClientProcessor soapProcessor = new DpwsDiscoClientProcessor(); // Build probe matches collection as long as timeout has not expired int noReceived = 0; while (DateTime.Now.Ticks < endTime) { if (udpClient.Available > 0) { // If maxProbeRequest is set check count if (maxProbeMatches > 0) { if (noReceived > maxProbeMatches) { break; } } // Since MF sockets does not have an IOControl method catch 10054 to get around the problem // with Upd and ICMP. try { // Wait for response responseLength = udpClient.ReceiveFrom(probeResponse, c_MaxUdpPacketSize, SocketFlags.None, ref remoteEP); } catch (SocketException se) { if (se.ErrorCode == 10054) { continue; } throw se; } // If we received process probe match if (responseLength > 0) { System.Ext.Console.Write(""); System.Ext.Console.Write("ProbeMatches Response From: " + ((IPEndPoint)remoteEP).Address.ToString()); System.Ext.Console.Write(new String(System.Text.Encoding.UTF8.GetChars(probeResponse))); // Process the response try { DpwsServiceDescriptions tempMatches = soapProcessor.ProcessProbeMatch(probeResponse, messageID, (IPEndPoint)remoteEP, messageCheck); if (tempMatches != null) { int count = tempMatches.Count; for (int i = 0; i < count; i++) { probeMatches.Add(tempMatches[i]); } } } catch (Exception e) { System.Ext.Console.Write(""); System.Ext.Console.Write(e.Message); System.Ext.Console.Write(""); } // Increment the number received counter ++noReceived; } } else { Thread.Sleep(1); } } udpClient.Close(); udpClient = null; // Display results if (probeMatches == null) { System.Ext.Console.Write("Probe timed out."); } else { System.Ext.Console.Write("Received " + probeMatches.Count + " probeMatches matches."); } return(probeMatches); }