Python脚本中的等效C#/ VB.NET控制台 [英] Equivalent C#/VB.NET console from Python script
问题描述
我编写了一个脚本来使用WSDL数据。脚本运行完美并返回正确的值。但我无法在任何C#或VB.NET Windows项目中实现它。
如何在.NET使用时翻译脚本?
# !/ usr / bin / env python
# !/ usr / bin / python
# !/ usr / local / lib
# !/ bin / env python
# ! python
# ^
print 内容类型:text / html \ n \ n
import random
import datetime
import hmac
import base64
import urllib2
import time
import socket
import thread
import site; site.getsitepackages()
来自 distutils.sysconfig import get_python_lib; print get_python_lib()
import re
来自 pysimplesoap.client import SoapClient
import sys
import re
import json
导入请求
my_dict = {}
jsndata = ' '
def is_number:
try :
float(s)# 对于int,long和float
< span class =code-keyword> except ValueError:
try :
complex(s)# 复杂
除了 ValueError:
return False
return True
def wait_for_internet_connection():
True :
尝试:
request = requests.get(' http://someurlhere.com')
如果 request.status_code == 200 :
return
else :
传递
除 urllib2.URLError:
传递
除了 socket.timeout,e:
传递
除了例外,e:
print str(datetime.datetime.now ())。split(' 。')[ 0 ] + - 例外:服务器当前没有响应
传递
time.sleep( 5 )
if __name__ == ' __ main __':
while True :
wait_for_internet_connection()
try :
clients = SoapCl ient(
wsdl = http://someurlhere.com/cgi-bin/cgi.cgi?WSDL ,
trace = False
)
除:
print ( SOAP XML WSDL socket timedout)
传递
wait_for_internet_connection()
尝试:
response = clients.GetDeviceList( )
除了例外,e:
print str(datetime.datetime.now) ())。split(' 。')[ 0 ] + - Excep :无法检索从属列表。
传递
结果在响应[' GetDeviceListResult' ]:# LOOP每个DEVICELIST都要检索其数据
ctrlname = result [ Slave'] [' 名称']
ctrldesc =结果[' Slave' ] [' 描述']
如果 re.match(' Device01',str(ctrlname)):
my_dict = {' DeviceID':' Device01'}
try :
resp = clients.GetDeviceDetails(' Device01')
除例外,e:
print str(datetime.datetime.now())。split(' 。')[ 0 ] + - 异常:无法检索设备列表。
传递
for list in resp [' GetD eviceDetailsResult']:
如果 list == ' 项目:
dict in resp [< span class =code-string>' GetDeviceDetailsResult'] [list]:
if is_number(dict [' Item'] [' Value']):
my_dict.update({dict ['' 项目'] [' 名称' ]:num(dict [' Item'] [' Value'])})
jsndata = json.dumps(my_dict,default = datetime_handler,sort_keys = True )
msg_txt = jsndata
time.sleep( 15 )
.NET的更新代码块
***响应返回一个WEBSERVICE名称结构,从SOAPACTION返回值。从PYTHON返回的XML数据直接从请求到SOAP。我已经安装了SOAPCLIENT和SIMPLESOAPCLIENT,但我不知道如何进一步移动。
我尝试了什么: < br $> b $ b
# !/ usr / bin / env python
# !/ usr / bin / python
# !/ usr / local / lib
# !/ bin / env python
# ! python
# ^
print 内容类型:text / html \ n \ n
import random
import datetime
import hmac
import base64
import urllib2
import time
import socket
import thread
import site; site.getsitepackages()
来自 distutils.sysconfig import get_python_lib; print get_python_lib()
import re
来自 pysimplesoap.client import SoapClient
import sys
import re
import json
导入请求
my_dict = {}
jsndata = ' '
def is_number:
try :
float(s)# 对于int,long和float
< span class =code-keyword> except ValueError:
try :
complex(s)# 复杂
除了 ValueError:
return False
return True
def wait_for_internet_connection():
True :
尝试:
request = requests.get(' http://someurlhere.com')
如果 request.status_code == 200 :
return
else :
传递
除 urllib2.URLError:
传递
除了 socket.timeout,e:
传递
除了例外,e:
print str(datetime.datetime.now ())。split(' 。')[ 0 ] + - 例外:服务器当前没有响应
传递
time.sleep( 5 )
if __name__ == ' __ main __':
while True :
wait_for_internet_connection()
try :
clients = SoapCl ient(
wsdl = http://someurlhere.com/cgi-bin/cgi.cgi?WSDL ,
trace = False
)
除:
print ( SOAP XML WSDL socket timedout)
传递
wait_for_internet_connection()
尝试:
response = clients.GetDeviceList( )
除了例外,e:
print str(datetime.datetime.now) ())。split(' 。')[ 0 ] + - Excep :无法检索从属列表。
传递
结果在响应[' GetDeviceListResult' ]:# LOOP每个DEVICELIST都要检索其数据
ctrlname = result [ Slave'] [' 名称']
ctrldesc =结果[' Slave' ] [' 描述']
如果 re.match(' Device01',str(ctrlname)):
my_dict = {' DeviceID':' Device01'}
try :
resp = clients.GetDeviceDetails(' Device01')
除例外,e:
print str(datetime.datetime.now())。split(' 。')[ 0 ] + - 异常:无法检索设备列表。
传递
for list in resp [' GetD eviceDetailsResult']:
如果 list == ' 项目:
dict in resp [< span class =code-string>' GetDeviceDetailsResult'] [list]:
if is_number(dict [' Item'] [' Value']):
my_dict.update({dict ['' 项目'] [' 名称' ]:num(dict [' Item'] [' Value'])})
jsndata = json.dumps(my_dict,default = datetime_handler,sort_keys = True )
msg_txt = jsndata
time.sleep( 15 )
这就是我在VB.NET控制台上尝试的东西但返回的是WEBSERVICE TREEVIEW格式,它定义了每种功能数据类型
< pre lang =VB> Imports System.IO
Imports System.Net
Imports System.Text
Imports System.Xml
Imports System.Diagnostics
Imports System.Xml.Serialization
Imports 系统
Imports System.Web.Services.Protocols
Imports System.ComponentModel
Imports System.Web.Services
Imports System。 Xml.Schema
Imports System.Web.Services.Description
Imports SimpleSOAPClient。 SoapClient
模块 Module1
Sub Main()
Console.WriteLine (GetWebData())
Console.ReadLine()
结束 Sub
公共 功能 GetWebData()作为 字符串
Dim serverResponse 作为 字符串 = 没有
Dim serverAddress 作为 新 Uri( http:// someurlhere /)
Dim request = TryCast (WebRequest.Create(serverAddress),HttpWebRequest)
Dim response = TryCast (request.GetResponse(),HttpWebRequest)
使用 memStream As 新 MemoryStream()
使用 responseStream 作为 Stream = response.GetResponseStream()
responseStream.CopyTo(memStream)
结束 使用
serverResponse = Encoding.UTF8.GetString(Re adFully(memStream))
结束 使用
返回 serverResponse
结束 功能
公共 功能 ReadFully( ByVal stream < span class =code-keyword> As Stream) As Byte ()
Dim 缓冲区( 32767 ) As 字节
使用 ms 作为 新 MemoryStream()
执行
Dim 读取 As Integer = stream.Read(buffer, 0 ,缓冲区。长度)
如果读取< = 0 然后
返回 ms.ToArray()
结束 如果
ms.Write(buffer, 0 ,请阅读)
循环
结束 使用
结束 功能
私有 Sub MethodWay()
Dim uri = 新 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&
使用 stream = 新 StreamWriter(req.GetRequestStream(),Encoding.UTF8)
stream.Write(strSoapMessage)
End 使用
Dim buffer()作为 字节 = 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.Write(buffer, 0 ,buffer.Length)
post.Close()
' 构建响应对象
Dim response As HttpWebResponse = TryCast (request.GetResponse(),HttpWebResponse)
Dim responsedata As Stream = response.GetResponseStream()
Dim responsereader As 新 StreamReader(responsedata)
Dim respons = responsereader.ReadToEnd()
Console.WriteLine(respons)
End Sub
私有 Sub TryThis()
Dim uriBuilder As 新 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 作为 新 XmlDocument()
Dim nsmgr As 新 XmlNamespaceManager (xmlDocument.NameTable)
nsmgr.AddNamespace( wsdl, http://schemas.xmlsoap.org/wsdl/)
nsmgr.AddNamespace( soap, http://schemas.xmlsoap.org/wsdl/soap/)
使用响应 As System.Net .WebResponse = webRequest.GetResponse()
使用 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)
如果 xNodes IsNot 没有 然后
Dim builder 正如 新 StringBuilder()
对于 每个节点 As XmlNode 在 xNodes
builder.AppendLine(node.Attributes( soapAction)。InnerText)
下一个节点
Console.WriteLine(builder.ToString())
结束 如果
结束 使用
结束 使用
结束 Sub
公开 Sub 执行()
Dim request 作为 HttpWebRequest = CreateSOAPWebRequest( http://someurlhere/cgi-bin/cgi.cgi?WebService = GetDeviceList)
Dim soapEnvelopeXml As 新 XmlDocument()
soapEnvelopeXml.LoadXml( & ControlChars.CrLf&
)
使用 stream As Stream = request.GetRequestStream()
soapEnvelopeXml.Save(stream)
结束 使用
使用响应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(
'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\")
webRequ est.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 XmlSchemaEl ement = 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 i nnerChoice 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.Ite ms(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 ModuleNo one is going to translate it all for you. I am also not aware of a translator that could do it which means you have to understand how it works and then re-write it. There is no magic bullet that will do the work for you.
Once you understand how it works in Python then you can google for how to do equivalent in C#. And if you get stuck on something specific please come back and post the specific line(s) of code you are having difficulty getting to work and be clear about what the problem is and we’ll gladly help.I can’t rewrite your scripts but here’s the .Net classes that will get you close with a little example on how to use them.
To make a web request, you will need to use the System.Net, System.IO, and System.Text namespaces
public string GetWebData()
{
string serverResponse = null;
Uri serverAddress = new Uri(\"http://www.mytargetaddress.com/wsdlsvc\");
var request = WebRequest.Create(serverAddress) as HttpWebRequest;
var response = request.GetResponse() as HttmpWebResponse;
using (MemoryStream memStream = new MemoryStream())
{
using (Stream responseStream = response.GetResponseStream())
{
responseStream.CopyTo(memStream);
}
serverResponse = Encoding.UTF8.GetString(memStream.ToByteArray());
}
return serverResponse;
}
This will get you the raw text. From there, you can parse the JSON using this guide: MSDN Serialize and Deserialize JSON[^]
Hmmm..
I don’t know it was this easy because I already tried it but it return a XML format rather than a subset of property and its value..
What I do is:
1. Right click on \"References\" subtree inside project. And select \"Add Service Reference\".
2. Paste WSDL Url into Address input and press \"Go\" button. If the URL is valid, Services section will list subview of function available on the WSDL.
3. Click \"Advanced\" button. Click \"Add Web References\".
4. Paste again URL and click button \"Go\" again.
5. Rename the \"Web reference name\" section as you like \"webref\".
6. Click \"Add Reference\" button and 2 new folder will be created \"Service References\" and \"Web References\" with WebReferenceName you enter earlier.
Start calling for the webref object.
Dim ws As webref.WServices = New webref.WServices()
Dim wsresult As webref.List() = ws.GetList() 'If the WS return array structure, point the declare object as its define on hovering the ws.GetList()
Dim strname = wsresult(i).Name
It was just like that. And by breakpoint to the line, we can see if the object contains data that consume from WS. Same like Python which I see. But more simple!
Hi,
I have write a script to consume WSDL data. The script running perfectly and return the correct value. But I can't achieve it in any C# or VB.NET windows project.
How to translate the script as .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)
UPDATED CODE BLOCK FOR .NET
*** THE RESPONSE RETURN A WEBSERVICE NAME STRUCTURE INSTEAD OF RETURN VALUE FROM SOAPACTION. THE RETURN FROM PYTHON HAVING ITS XML DATA DIRECTLY FROM REQUEST TO SOAP. I HAVE INSTALL SOAPCLIENT AND SIMPLESOAPCLIENT BUT I DON'T KNOW HOW TO FURTHER MOVE.
What I have tried:
#!/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)
THIS IS WHAT I HAVE TRY ON VB.NET CONSOLE BUT THE RETURN IS WEBSERVICE TREEVIEW FORMAT THAT DEFINING EACH FUNCTION DATA TYPE
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 one is going to translate it all for you. I am also not aware of a translator that could do it which means you have to understand how it works and then re-write it. There is no magic bullet that will do the work for you.
Once you understand how it works in Python then you can google for how to do equivalent in C#. And if you get stuck on something specific please come back and post the specific line(s) of code you are having difficulty getting to work and be clear about what the problem is and we'll gladly help.
I can't rewrite your scripts but here's the .Net classes that will get you close with a little example on how to use them.
To make a web request, you will need to use the System.Net, System.IO, and System.Text namespaces
public string GetWebData() { string serverResponse = null; Uri serverAddress = new Uri("http://www.mytargetaddress.com/wsdlsvc"); var request = WebRequest.Create(serverAddress) as HttpWebRequest; var response = request.GetResponse() as HttmpWebResponse; using (MemoryStream memStream = new MemoryStream()) { using (Stream responseStream = response.GetResponseStream()) { responseStream.CopyTo(memStream); } serverResponse = Encoding.UTF8.GetString(memStream.ToByteArray()); } return serverResponse; }This will get you the raw text. From there, you can parse the JSON using this guide: MSDN Serialize and Deserialize JSON[^]
Hmmm..
I don't know it was this easy because I already tried it but it return a XML format rather than a subset of property and its value..
What I do is:
1. Right click on "References" subtree inside project. And select "Add Service Reference".
2. Paste WSDL Url into Address input and press "Go" button. If the URL is valid, Services section will list subview of function available on the WSDL.
3. Click "Advanced" button. Click "Add Web References".
4. Paste again URL and click button "Go" again.
5. Rename the "Web reference name" section as you like "webref".
6. Click "Add Reference" button and 2 new folder will be created "Service References" and "Web References" with WebReferenceName you enter earlier.
Start calling for the webref object.
Dim ws As webref.WServices = New webref.WServices() Dim wsresult As webref.List() = ws.GetList() 'If the WS return array structure, point the declare object as its define on hovering the ws.GetList() Dim strname = wsresult(i).Name
It was just like that. And by breakpoint to the line, we can see if the object contains data that consume from WS. Same like Python which I see. But more simple!
这篇关于Python脚本中的等效C#/ VB.NET控制台的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!