I need to pass an object (a list of structures so defined):
Private attivitaDaTrasferire As New List(Of FileDaTrasferire)
Private Structure FileDaTrasferire
Dim activityID As Integer
Dim DataIns As Date
Dim idUtenteComp As Integer
Dim idVersione As Integer
Dim idFile As Integer
Dim fileNome As String
Dim fileDestinazione As String
Dim fileTipoProdotto As String
Dim fileTipo As String
Dim fileBinarySize As Integer
Dim fileBinaryDate As String
Dim fileBinary As Long
End Structure
from a form (vb.net) to a restful web service. How can I do?
Either use JSON or XML for passing it to the restful service.
JSON on .NET
XML-Serializer
I'm using XML-Serializer. I have two functions: one client side:
Private Function SerializeActivity(singolaAttivitaDaTrasferire As List(Of FileDaTrasferire)) As String
Dim writer As New StringWriter()
Dim serializer As New XmlSerializer(GetType(List(Of FileDaTrasferire)))
Try
serializer.Serialize(writer, singolaAttivitaDaTrasferire)
Catch ex As Exception
Console.WriteLine("Eccezione " + ex.Message)
End Try
Return writer.ToString()
End Function
and one for the web-service.I get the xml file from the web service as a string and try to deserialize it with this function:
Public Function SaveDataPost(sXMLFile As String) As Boolean Implements ILiveUpdateWS.SaveDataPost
Dim reader As New StringReader(sXMLFile)
Dim serializer As New XmlSerializer(GetType(List(Of FileDaAggiornare)))
Dim myFile As List(Of FileDaAggiornare)
'Dim myFile As FileDaAggiornare
Try
myFile = serializer.Deserialize(reader)
Catch ex As Exception
Console.WriteLine("Eccezione: " + ex.Message)
End Try
Return Nothing
End Function
but on the deserialize I obtain an InvalidOperationException. (Error in the xml document)
Related
I have this code that starts some threads by iterating through a list of strings and send each one to a Sub which connects to a webservice and waits for a result:
Public Shared Function StartThreading(names As String())
Dim threads As List(Of Thread) = New List(Of Thread)()
For Each name In names
Dim t As Thread = New Thread(New ParameterizedThreadStart(Sub() CallWebService(name)))
threads.Add(t)
Next
For i As Integer = 0 To threads.Count - 1
Dim t = threads(i)
Dim name = names(i)
t.Start(name)
Next
For Each t As Thread In threads
t.Join()
Next
End Function
The Sub for the webservice caller is:
Public Shared Sub CallWebService(inputxml As String)
Dim _url = "http://10.231.58.173:8080/ps/services/ProcessServer?WSDL"
Dim _action = "http://10.231.58.173:8080/ps/services/ProcessServer"
Dim soapEnvelopeXml As XmlDocument = CreateSoapEnvelope(inputxml)
Dim webRequest As HttpWebRequest = CreateWebRequest(_url, _action)
Dim appPath As String = System.AppDomain.CurrentDomain.BaseDirectory
Dim configpath As String = appPath + "\Config.ini"
Dim configdata As IniData = Functii.ReadIniFile(configpath)
Dim outputxmlsave = configdata("PATHS")("OUTPUTXML")
InsertSoapEnvelopeIntoWebRequest(soapEnvelopeXml, webRequest)
Dim asyncResult As IAsyncResult = webRequest.BeginGetResponse(Nothing, Nothing)
asyncResult.AsyncWaitHandle.WaitOne()
Dim soapResult As String
Using webResponse As WebResponse = webRequest.EndGetResponse(asyncResult)
Using rd As StreamReader = New StreamReader(webResponse.GetResponseStream())
soapResult = rd.ReadToEnd()
End Using
File.WriteAllText(outputxmlsave & "\" & "test.xml", soapResult.ToString)
Console.Write(soapResult)
End Using
End Sub
How can I know that all threads are done successfully or not? Is there something I can use to return a True value if they are all done?
Public Sub openDB()
Dim Lines As New List(Of String)
Try
' Open the file using a stream reader.
Using sr As New StreamReader("Config.txt")
Dim line As String
' Read the stream to a string and write the string to the console.
line = sr.ReadLine()
Do Until String.IsNullOrEmpty(line)
Lines.Add(line)
line = sr.ReadLine
Loop
End Using
Catch e As Exception
Console.WriteLine("The file could not be read:")
Console.WriteLine(e.Message)
End Try
Dim dbname As String = g_DatabaseName
Dim server As String = Lines.Where(Function(str) str.Contains("server =")).ToString
Dim user As String = ""
Dim password As String = ""
conn = New MySqlConnection
conn.ConnectionString = String.Format("server={0}; user id={1}; password={2}; database={3}; pooling=false; Convert Zero Datetime=True", server, user, password, dbname)
conn.Open()
End Sub
Im try to return some string from a text file, so I use StreamReader to read the file and store them into a list. Now I try to declare a variable to get "localhost" from list of string, but the code below is not work for me.
Dim server As String = Lines.Where(Function(str) str.Contains("server
=")).ToString
Enumerable.Where does not return a single string but possibly multiple, using ToString gives you not the first matching line but just the name of the type which is System.Linq.Enumerable+WhereArrayIterator1[System.String].
Either declare it as IEnumerable(Of String) or use First/ FirstOrDefault to get the first line that matches the condition:
Dim serverLine As String = Lines
.Where(Function(str) str.Contains("server ="))
.FirstOrDefault()
You can also use the overload of FirstOrDefault(Nothing if there was no such line):
Dim serverLine As String = Lines.FirstOrDefault(Function(str) str.Contains("server ="))
To extract Localhost:
Dim server As String = serverLine.Substring(serverLine.IndexOf("server =") + "server =".Length).Trim(""""c, " "c)
I have functions which serialize and base64 convert objects and vice versa. It uses Newtonsoft to serialize and deserialize Objects. The code works but is there a way to do this without using Newtonsoft?
Public Shared Function SerializeAndBase64(ObjectToSerialize As Object) As ReturnObject(Of String)
Dim rtnObj As New ReturnObject(Of String)
Try
Dim SerializedObjectJson As String = Newtonsoft.Json.JsonConvert.SerializeObject(ObjectToSerialize)
Dim Base64String As String = Convert.ToBase64String(Encoding.UTF8.GetBytes(SerializedObjectJson))
rtnObj.Item = Base64String
Catch ex As Exception
rtnObj.ErrorID = ErrorHandler.handleError(ex)
rtnObj.ErrorMessage = ex.Message
rtnObj.IsError = True
End Try
Return rtnObj
End Function
Public Shared Function DeserializeFromBase64(Of t)(Base64Json As String) As ReturnObject(Of t)
Dim rtnObj As New ReturnObject(Of t)
Try
Dim SerializedObjectJson As String = Encoding.UTF8.GetString(Convert.FromBase64String(Base64Json))
Dim DeserializedObject As t = Newtonsoft.Json.JsonConvert.DeserializeObject(Of t)(SerializedObjectJson)
rtnObj.Item = DeserializedObject
Catch ex As Exception
rtnObj.ErrorID = ErrorHandler.handleError(ex)
rtnObj.ErrorMessage = ex.Message
rtnObj.IsError = True
End Try
Return rtnObj
End Function
Thanks in advance.
You can Serialize/Deserialize it yourself. You just have to come up with a way to save everything into a single string, or XML or even a byte array if you want. Your choice.
Public Class Class1
Public Property MyValue As String
Public Function Serialize() As String
Return MyValue
End Function
Public Sub Deserialize(ByVal value As String)
MyValue = value
End Sub
End Class
I'm requesting remote SOAP web-service but all operation (from click search button to render interface with answer) took almost two minutes, it's too long. So I wonder if there any possible way to improve performance of the current code.
Operation that parse xml and read data to database working quite well, problem only about reading answer from stream.
Public Shared Function CallWebService(ByVal an As String, ByVal xmlcommand As String) As String
Dim _url = "http://testapi.interface-xml.com/appservices/ws/FrontendService"
Dim soapEnvelopeXml As XmlDocument = CreateSoapEnvelope(xmlcommand)
Dim webRequest As HttpWebRequest = CreateWebRequest(_url, an)
webRequest.Proxy = System.Net.WebRequest.DefaultWebProxy
InsertSoapEnvelopeIntoWebRequest(soapEnvelopeXml, webRequest)
Dim asyncResult As IAsyncResult = webRequest.BeginGetResponse(Nothing, Nothing)
asyncResult.AsyncWaitHandle.WaitOne()
Dim soapResult As String
Using webResponse As WebResponse = webRequest.EndGetResponse(asyncResult)
Using bs As New BufferedStream(webResponse.GetResponseStream())
Using rd As New StreamReader(bs)
soapResult = rd.ReadLine()
Return soapResult
End Using
End Using
End Using
End Function
Here is solution!
Public Shared Function CallWebService(ByVal an As String, ByVal xmlcommand As String) As String
Dim _url = "http://testapi.interface-xml.com/appservices/ws/FrontendService"
Dim soapEnvelopeXml As XmlDocument = CreateSoapEnvelope(xmlcommand)
Dim webRequest As HttpWebRequest = CreateWebRequest(_url, an)
webRequest.Proxy = System.Net.WebRequest.DefaultWebProxy
webRequest.Headers.Add("Accept-Encoding", "gzip, deflate")
InsertSoapEnvelopeIntoWebRequest(soapEnvelopeXml, webRequest)
Dim asyncResult As IAsyncResult = webRequest.BeginGetResponse(Nothing, Nothing)
asyncResult.AsyncWaitHandle.WaitOne()
Dim soapResult As String
Using webResponse As WebResponse = webRequest.EndGetResponse(asyncResult)
Using bs As New BufferedStream(webResponse.GetResponseStream())
Using gz As New GZipStream(bs, CompressionMode.Decompress)
Using rd As New StreamReader(gz)
soapResult = rd.ReadLine()
Return soapResult
End Using
End Using
End Using
End Using
End Function
I would like to read each line of text from the file outputted from this block.
Each line is then used with the service controller to output a list of services running on that computer.
Dim de As New DirectoryEntry()
'Name place to write file to
Dim strFile As String = "C:\DomainUsers.txt"
Dim fileExists As Boolean = File.Exists(strFile)
'get list of all users on domain and write to file
de.Path = "WinNT://domain.com"
'Write each user to a text file as List
Using sw As New StreamWriter(File.Open(strFile, FileMode.OpenOrCreate))
MsgBox("Writing all Users to Memory, Click OK and wait for Window to Close")
For Each d As DirectoryEntry In de.Children()
sw.WriteLine(d.Name)
Next
Console.Clear()
End Using
'Reopen File and read each line
'Return List of Processes for each User in Overwritefashion to New Version of File
Using sr As New StreamReader(File.Open(strFile, FileMode.Open))
Dim InstalledServices As List(Of String) = GetInstalledServices(sr.ReadLine.Trim)
End Using
End Sub
'Lost as to how to go about using this function...
Function GetInstalledServices(ByVal Computer As String) As List(Of String)
End Function
You'll have to check it, but it'll be something like ...
Function GetInstalledServices(ByVal Computer As String) As List(Of String)
Dim RetVal as New List(Of String)
Dim scServices() As ServiceController()
Try
scServices = ServiceController.GetServices(Computer)
For Each Svc as ServiceController In scServices
RetVal.Add(Svc.ServiceName)
Next
Catch Ex as Exception
End Try
Return RetVal
End Function