Click here to Skip to main content
15,884,629 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
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?
Python
#!/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:

Python
#!/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

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
Posted
Updated 27-Sep-16 3:52am
v2
Comments
[no name] 26-Sep-16 13:47pm    
"How to translate the script as .NET use", AFAIK you don't. It's not a translation. It called rewriting using the equivalent .NET classes.
Jacob Himes 26-Sep-16 14:03pm    
This site is for questions, not a free do-my homework/job for me emporium.

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.
 
Share this answer
 
Comments
Luiey Ichigo 27-Sep-16 2:41am    
I have try using Web Reference, HTTP Request but none return the data structure. Instead, it returning calling structure. Updated code block that I have tried several days
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
C#
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[^]
 
Share this answer
 
v2
Comments
Luiey Ichigo 27-Sep-16 2:42am    
the response is returning a set of web service structure instead of response data structure. the structure having nested xml variable before can get the data
Foothill 27-Sep-16 9:06am    
Your WSDL data is nested inside the web response?
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.
VB
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!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900