Эквивалентная консоль C#/VB. NET из скрипта Python
Привет,
Я написал сценарий для использования данных WSDL. Скрипт работает отлично и возвращает правильное значение. Но я не могу достичь этого ни в одном C# или VB.NET проект windows.
Как перевести скрипт как .NET use?
#!/usr/bin/env python #!/usr/bin/python #!/usr/local/lib #!/bin/env python #! python # ^ print "Content-type: text/html\n\n" import random import datetime import hmac import base64 import urllib2 import time import socket import thread import site; site.getsitepackages() from distutils.sysconfig import get_python_lib; print get_python_lib() import re from pysimplesoap.client import SoapClient import sys import re import json import requests my_dict = {} jsndata='' def is_number(s): try: float(s) # for int, long and float except ValueError: try: complex(s) # for complex except ValueError: return False return True def wait_for_internet_connection(): while True: try: request = requests.get('http://someurlhere.com') if request.status_code == 200: return else: pass except urllib2.URLError: pass except socket.timeout, e: pass except Exception, e: print str(datetime.datetime.now()).split('.')[0] + " - Exception: Server not response currently" pass time.sleep(5) if __name__ == '__main__': while True: wait_for_internet_connection() try: clients = SoapClient( wsdl="http://someurlhere.com/cgi-bin/cgi.cgi?WSDL", trace=False ) except: print("SOAP XML WSDL socket timedout") pass wait_for_internet_connection() try: response = clients.GetDeviceList() except Exception, e: print str(datetime.datetime.now()).split('.')[0] + " - Exception: Unable to retrieve slave list." pass for result in response['GetDeviceListResult']: #LOOP EVERY DEVICELIST TO RETRIEVE ITS DATA ctrlname = result['Slave']['Name'] ctrldesc = result['Slave']['Description'] if re.match('Device01',str(ctrlname)): my_dict = {'DeviceID':'Device01'} try: resp = clients.GetDeviceDetails('Device01') except Exception, e: print str(datetime.datetime.now()).split('.')[0] + " - Exception: Unable to retrieve device list." pass for list in resp['GetDeviceDetailsResult']: if list == 'Items': for dict in resp['GetDeviceDetailsResult'][list]: if is_number(dict['Item']['Value']): my_dict.update({dict['Item']['Name']:num(dict['Item']['Value'])}) jsndata = json.dumps(my_dict, default=datetime_handler, sort_keys = True) msg_txt = jsndata time.sleep(15)
ОБНОВЛЕННЫЙ БЛОК КОДА ДЛЯ .NET
*** ОТВЕТ ВОЗВРАЩАЕТ СТРУКТУРУ ИМЕНИ ВЕБ-СЕРВИСА ВМЕСТО ВОЗВРАЩАЕМОГО ЗНАЧЕНИЯ ИЗ SOAPACTION. ВОЗВРАТ ОТ PYTHON, ИМЕЮЩЕГО СВОИ XML-ДАННЫЕ НЕПОСРЕДСТВЕННО ИЗ ЗАПРОСА В SOAP. У МЕНЯ ЕСТЬ INSTALL SOAPCLIENT И SIMPLESOAPCLIENT, НО Я НЕ ЗНАЮ, КАК ДВИГАТЬСЯ ДАЛЬШЕ.
Что я уже пробовал:
#!/usr/bin/env python #!/usr/bin/python #!/usr/local/lib #!/bin/env python #! python # ^ print "Content-type: text/html\n\n" import random import datetime import hmac import base64 import urllib2 import time import socket import thread import site; site.getsitepackages() from distutils.sysconfig import get_python_lib; print get_python_lib() import re from pysimplesoap.client import SoapClient import sys import re import json import requests my_dict = {} jsndata='' def is_number(s): try: float(s) # for int, long and float except ValueError: try: complex(s) # for complex except ValueError: return False return True def wait_for_internet_connection(): while True: try: request = requests.get('http://someurlhere.com') if request.status_code == 200: return else: pass except urllib2.URLError: pass except socket.timeout, e: pass except Exception, e: print str(datetime.datetime.now()).split('.')[0] + " - Exception: Server not response currently" pass time.sleep(5) if __name__ == '__main__': while True: wait_for_internet_connection() try: clients = SoapClient( wsdl="http://someurlhere.com/cgi-bin/cgi.cgi?WSDL", trace=False ) except: print("SOAP XML WSDL socket timedout") pass wait_for_internet_connection() try: response = clients.GetDeviceList() except Exception, e: print str(datetime.datetime.now()).split('.')[0] + " - Exception: Unable to retrieve slave list." pass for result in response['GetDeviceListResult']: #LOOP EVERY DEVICELIST TO RETRIEVE ITS DATA ctrlname = result['Slave']['Name'] ctrldesc = result['Slave']['Description'] if re.match('Device01',str(ctrlname)): my_dict = {'DeviceID':'Device01'} try: resp = clients.GetDeviceDetails('Device01') except Exception, e: print str(datetime.datetime.now()).split('.')[0] + " - Exception: Unable to retrieve device list." pass for list in resp['GetDeviceDetailsResult']: if list == 'Items': for dict in resp['GetDeviceDetailsResult'][list]: if is_number(dict['Item']['Value']): my_dict.update({dict['Item']['Name']:num(dict['Item']['Value'])}) jsndata = json.dumps(my_dict, default=datetime_handler, sort_keys = True) msg_txt = jsndata time.sleep(15)
ЭТО ТО, ЧТО Я ПОПРОБОВАТЬ НА КОНСОЛИ VB.NET НО ВОЗВРАЩЕНИЕ ДЕРЕВА В ФОРМАТЕ ВЕБ-СЕРВИСА, ЧТО ОПРЕДЕЛЕНИЕ КАЖДОЙ ФУНКЦИИ ТИП ДАННЫХ
Imports System.IO Imports System.Net Imports System.Text Imports System.Xml Imports System.Diagnostics Imports System.Xml.Serialization Imports System Imports System.Web.Services.Protocols Imports System.ComponentModel Imports System.Web.Services Imports System.Xml.Schema Imports System.Web.Services.Description Imports SimpleSOAPClient.SoapClient Module Module1 Sub Main() Console.WriteLine(GetWebData()) Console.ReadLine() End Sub Public Function GetWebData() As String Dim serverResponse As String = Nothing Dim serverAddress As New Uri("http://someurlhere/") Dim request = TryCast(WebRequest.Create(serverAddress), HttpWebRequest) Dim response = TryCast(request.GetResponse(), HttpWebRequest) Using memStream As New MemoryStream() Using responseStream As Stream = response.GetResponseStream() responseStream.CopyTo(memStream) End Using serverResponse = Encoding.UTF8.GetString(ReadFully(memStream)) End Using Return serverResponse End Function Public Function ReadFully(ByVal stream As Stream) As Byte() Dim buffer(32767) As Byte Using ms As New MemoryStream() Do Dim read As Integer = stream.Read(buffer, 0, buffer.Length) If read <= 0 Then Return ms.ToArray() End If ms.Write(buffer, 0, read) Loop End Using End Function Private Sub MethodWay() Dim uri = New Uri("http://someurlhere/cgi-bin/cgi.cgi?WebService=GetDeviceList") Dim req = CType(WebRequest.CreateDefault(uri), HttpWebRequest) req.ContentType = "text/xml; charset=utf-8" req.Method = "POST" req.Accept = "text/xml" req.Headers.Add("SOAPAction", "http://someurlhere/cgi-bin/cgi.cgi?WebService=GetVersion") Dim strSoapMessage = "" & ControlChars.CrLf & "" Using stream = New StreamWriter(req.GetRequestStream(), Encoding.UTF8) stream.Write(strSoapMessage) End Using Dim buffer() As Byte = Encoding.ASCII.GetBytes(strSoapMessage) Dim request As HttpWebRequest = TryCast(WebRequest.Create("http://someurlhere/cgi-bin/cgi.cgi?WSDL"), HttpWebRequest) request.Method = "POST" request.ContentType = "text/xml;charset=UTF-8" request.ContentLength = buffer.Length Dim post As Stream = request.GetRequestStream() ' post data and close connection post.Write(buffer, 0, buffer.Length) post.Close() ' build response object Dim response As HttpWebResponse = TryCast(request.GetResponse(), HttpWebResponse) Dim responsedata As Stream = response.GetResponseStream() Dim responsereader As New StreamReader(responsedata) Dim respons = responsereader.ReadToEnd() Console.WriteLine(respons) End Sub Private Sub TryThis() Dim uriBuilder As New UriBuilder("http://someurlhere") uriBuilder.Query = "WSDL" Dim webRequest As System.Net.HttpWebRequest = CType(System.Net.WebRequest.Create(uriBuilder.Uri), System.Net.HttpWebRequest) webRequest.ContentType = "text/xml;charset=""utf-8""" webRequest.Method = "GET" webRequest.Accept = "text/xml" 'webRequest.Credentials = New NetworkCredential("userName", "password") Dim xmlDocument As New XmlDocument() Dim nsmgr As New XmlNamespaceManager(xmlDocument.NameTable) nsmgr.AddNamespace("wsdl", "http://schemas.xmlsoap.org/wsdl/") nsmgr.AddNamespace("soap", "http://schemas.xmlsoap.org/wsdl/soap/") Using response As System.Net.WebResponse = webRequest.GetResponse() Using stream As System.IO.Stream = response.GetResponseStream() xmlDocument.Load(stream) Dim xNodes As XmlNodeList = xmlDocument.SelectNodes("//wsdl:definitions/wsdl:binding/wsdl:operation/soap:operation", nsmgr) If xNodes IsNot Nothing Then Dim builder As New StringBuilder() For Each node As XmlNode In xNodes builder.AppendLine(node.Attributes("soapAction").InnerText) Next node Console.WriteLine(builder.ToString()) End If End Using End Using End Sub Public Sub Execute() Dim request As HttpWebRequest = CreateSOAPWebRequest("http://someurlhere/cgi-bin/cgi.cgi?WebService=GetDeviceList") Dim soapEnvelopeXml As New XmlDocument() soapEnvelopeXml.LoadXml("" & ControlChars.CrLf & "") Using stream As Stream = request.GetRequestStream() soapEnvelopeXml.Save(stream) End Using Using response As WebResponse = request.GetResponse() Using rd As New StreamReader(response.GetResponseStream()) Dim soapResult As String = rd.ReadToEnd() Console.WriteLine(soapResult) End Using End Using End Sub Public Function CreateSOAPWebRequest(ByVal soapAction As String) As HttpWebRequest 'Making Web Request Dim Req As HttpWebRequest = CType(WebRequest.Create("http://someurlhere/cgi-bin/cgi.cgi?WSDL"), HttpWebRequest) 'SOAPAction Req.Headers.Add("SOAPAction:" & soapAction) 'Content_type Req.ContentType = "text/xml;charset=""utf-8""" Req.Accept = "text/xml" 'HTTP method Req.Method = "POST" 'return HttpWebRequest Return Req End Function Public Function CreateWebRequest(ByVal url As String, ByVal soapAction As String) As HttpWebRequest Dim webRequest As HttpWebRequest = CType(webRequest.Create(url), HttpWebRequest) webRequest.ContentType = "application/soap+xml charset=UTF-8 action=\"" & soapAction & " \ "" webRequest.Method = "POST" Return webRequest End Function Public Function CreateWebRequest() As HttpWebRequest Dim webRequest As HttpWebRequest = CType(webRequest.Create("http://someurlhere/cgi-bin/cgi.cgi?WSDL"), HttpWebRequest) webRequest.Headers.Add("SOAP:http://someurlhere/cgi-bin/cgi.cgi?WebService=GetDeviceList") webRequest.ContentType = "text/xml;charset=""utf-8""" webRequest.Accept = "text/xml" webRequest.Method = "POST" Return webRequest End Function 'Private Sub MainExec() ' 'Build the URL request string ' Dim uriBuilder As New UriBuilder("http://someurlhere/cgi-bin/cgi.cgi?WSDL") ' uriBuilder.Query = "WSDL" ' Dim webRequest As HttpWebRequest = CType(webRequest.Create(uriBuilder.Uri), HttpWebRequest) ' webRequest.ContentType = "text/xml;charset=""utf-8""" ' webRequest.Method = "GET" ' webRequest.Accept = "text/xml" ' 'Submit a web request to get the web service's WSDL ' Dim serviceDescription As ServiceDescription ' Using response As WebResponse = webRequest.GetResponse() ' Using stream As Stream = response.GetResponseStream() ' serviceDescription = ServiceDescription.Read(stream) ' End Using ' End Using ' 'Loop through the port types in the service description and list all of the ' 'web service's operations and each operations input/output ' For Each portType As PortType In serviceDescription.PortTypes ' For Each operation As Operation In portType.Operations ' Console.Out.WriteLine(operation.Name) ' For Each message In operation.Messages ' If TypeOf message Is OperationInput Then ' Console.Out.WriteLine("Input Message: {0}", (CType(message, OperationInput)).Message.Name) ' End If ' If TypeOf message Is OperationOutput Then ' Console.Out.WriteLine("Output Message: {0}", (CType(message, OperationOutput)).Message.Name) ' End If ' For Each messagePart As Message In serviceDescription.Messages ' If messagePart.Name <> (CType(message, OperationMessage)).Message.Name Then ' Continue For ' End If ' For Each part As MessagePart In messagePart.Parts ' Console.Out.WriteLine(part.Name) ' Next part ' Next messagePart ' Next message ' Console.Out.WriteLine() ' Next operation ' Next portType 'End listing of types ' 'Drill down into the WSDL's complex types to list out the individual schema elements ' 'and their data types ' Dim types As Types = serviceDescription.Types ' Dim xmlSchema As XmlSchema = types.Schemas(0) ' For Each item As Object In xmlSchema.Items ' Dim schemaElement As XmlSchemaElement = TryCast(item, XmlSchemaElement) ' Dim complexType As XmlSchemaComplexType = TryCast(item, XmlSchemaComplexType) ' If schemaElement IsNot Nothing Then ' Console.Out.WriteLine("Schema Element: {0}", schemaElement.Name) ' Dim schemaType As XmlSchemaType = schemaElement.SchemaType ' Dim schemaComplexType As XmlSchemaComplexType = TryCast(schemaType, XmlSchemaComplexType) ' If schemaComplexType IsNot Nothing Then ' Dim particle As XmlSchemaParticle = schemaComplexType.Particle ' Dim sequence As XmlSchemaSequence = TryCast(particle, XmlSchemaSequence) ' If sequence IsNot Nothing Then ' For Each childElement As XmlSchemaElement In sequence.Items ' Console.Out.WriteLine(" Element/Type: {0}:{1}", childElement.Name, childElement.SchemaTypeName.Name) ' Next childElement ' End If ' End If ' ElseIf complexType IsNot Nothing Then ' Console.Out.WriteLine("Complex Type: {0}", complexType.Name) ' OutputElements(complexType.Particle) ' End If ' Console.Out.WriteLine() ' Next item ' Console.Out.WriteLine() ' Console.In.ReadLine() 'End Sub Private Sub OutputElements(ByVal particle As XmlSchemaParticle) Dim sequence As XmlSchemaSequence = TryCast(particle, XmlSchemaSequence) Dim choice As XmlSchemaChoice = TryCast(particle, XmlSchemaChoice) Dim all As XmlSchemaAll = TryCast(particle, XmlSchemaAll) If sequence IsNot Nothing Then Console.Out.WriteLine(" Sequence") For i As Integer = 0 To sequence.Items.Count - 1 Dim childElement As XmlSchemaElement = TryCast(sequence.Items(i), XmlSchemaElement) Dim innerSequence As XmlSchemaSequence = TryCast(sequence.Items(i), XmlSchemaSequence) Dim innerChoice As XmlSchemaChoice = TryCast(sequence.Items(i), XmlSchemaChoice) Dim innerAll As XmlSchemaAll = TryCast(sequence.Items(i), XmlSchemaAll) If childElement IsNot Nothing Then Console.Out.WriteLine(" Element/Type: {0}:{1}", childElement.Name, childElement.SchemaTypeName.Name) Else OutputElements(TryCast(sequence.Items(i), XmlSchemaParticle)) End If Next i ElseIf choice IsNot Nothing Then Console.Out.WriteLine(" Choice") For i As Integer = 0 To choice.Items.Count - 1 Dim childElement As XmlSchemaElement = TryCast(choice.Items(i), XmlSchemaElement) Dim innerSequence As XmlSchemaSequence = TryCast(choice.Items(i), XmlSchemaSequence) Dim innerChoice As XmlSchemaChoice = TryCast(choice.Items(i), XmlSchemaChoice) Dim innerAll As XmlSchemaAll = TryCast(choice.Items(i), XmlSchemaAll) If childElement IsNot Nothing Then Console.Out.WriteLine(" Element/Type: {0}:{1}", childElement.Name, childElement.SchemaTypeName.Name) Else OutputElements(TryCast(choice.Items(i), XmlSchemaParticle)) End If Next i Console.Out.WriteLine() ElseIf all IsNot Nothing Then Console.Out.WriteLine(" All") For i As Integer = 0 To all.Items.Count - 1 Dim childElement As XmlSchemaElement = TryCast(all.Items(i), XmlSchemaElement) Dim innerSequence As XmlSchemaSequence = TryCast(all.Items(i), XmlSchemaSequence) Dim innerChoice As XmlSchemaChoice = TryCast(all.Items(i), XmlSchemaChoice) Dim innerAll As XmlSchemaAll = TryCast(all.Items(i), XmlSchemaAll) If childElement IsNot Nothing Then Console.Out.WriteLine(" Element/Type: {0}:{1}", childElement.Name, childElement.SchemaTypeName.Name) Else OutputElements(TryCast(all.Items(i), XmlSchemaParticle)) End If Next i Console.Out.WriteLine() End If End Sub Public Sub getAuthenticationToken() Dim xml As New StringBuilder() xml.Append("") xml.Append("") getUKMailData(xml.ToString(), "http://someurlhere/cgi-bin/cgi.cgi?WSDL") End Sub Public Sub getUKMailData(ByVal xml As String, ByVal address As String) Dim result As String = "" Dim request As HttpWebRequest = CreateWebRequest(address) Dim soapEnvelopeXml As New XmlDocument() soapEnvelopeXml.LoadXml(xml) Using stream As Stream = request.GetRequestStream() soapEnvelopeXml.Save(stream) End Using Using response As WebResponse = request.GetResponse() ' Error occurs here Using rd As New StreamReader(response.GetResponseStream()) Dim soapResult As String = rd.ReadToEnd() Console.WriteLine(soapResult) End Using End Using End Sub Public Function CreateWebRequest(ByVal url As String) As HttpWebRequest Dim webRequest As HttpWebRequest = CType(webRequest.Create(url), HttpWebRequest) webRequest.Headers.Add("SOAP:""http://someurlhere/cgi-bin/cgi.cgi?WebService=GetDeviceList""") webRequest.ContentType = "text/xml;charset=""utf-8""" webRequest.Accept = "gzip,deflate" webRequest.Method = "POST" Return webRequest End Function End Module
[no name]
"Как перевести скрипт .Чистая польза", насколько мне известно, вы не. Это не перевод. Это называется переписывание с использованием эквивалента .Чистые классы.
Jacob Himes
Этот сайт предназначен для вопросов, а не для бесплатного выполнения моей домашней работы/работы для меня emporium.