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?
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)
except ValueError:
try:
complex(s)
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']:
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:
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)
except ValueError:
try:
complex(s)
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']:
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.Write(buffer, 0, buffer.Length)
post.Close()
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"
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
Dim Req As HttpWebRequest = CType(WebRequest.Create("http://someurlhere/cgi-bin/cgi.cgi?WSDL"), HttpWebRequest)
Req.Headers.Add("SOAPAction:" & soapAction)
Req.ContentType = "text/xml;charset=""utf-8"""
Req.Accept = "text/xml"
Req.Method = "POST"
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 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()
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