How can i pass a non specific class to sub - vb.net

I have code which takes a Soap Response and serializes into a xml so i can write it to console. Code works great but as i am trying to clean up my code i am trying to stick the code into a sub so i can use it for different responses.
Dim Response As ATTSoapReference.ATT_ADDR_VAL_RESP = newRequest.submitAddVal(ATT_ADDR)
Dim serxml = New System.Xml.Serialization.XmlSerializer(Response.GetType())
Dim ms = New MemoryStream()
serxml.Serialize(ms, Response)
Dim xml As String = Encoding.UTF8.GetString(ms.ToArray())
Console.WriteLine(xml)
If i want to do it as a sub for only this request type i can use
Private Sub DebugXML(byval myResponse As ATTSoapReference.ATT_ADDR_VAL_RESP)
Dim serxml = New System.Xml.Serialization.XmlSerializer(myResponse.GetType())
Dim ms = New MemoryStream()
serxml.Serialize(ms, myResponse)
Dim xml As String = Encoding.UTF8.GetString(ms.ToArray())
Console.WriteLine(xml)
End Sub
But i am looking for something that will allow me to pass any Soap Data Class to it instead of ATTSoapReference.ATT_ADDR_VAL_RESP

Try as said below and see if it works.
Private Sub DebugXML(byval myResponse As Object)
'May be you require casting, for some specific things.
End Sub

Related

VB.NET Return Form Object using Form Name

I'm basically writing a custom Error Logging Form for one of my applications because users cannot be trusted to report the errors to me.
I am obtaining the Form Name using the 'MethodBase' Object and then getting the DeclaringType Name.
Dim st As StackTrace = New StackTrace()
Dim sf As StackFrame = st.GetFrame(1)
Dim mb As MethodBase = sf.GetMethod()
Dim dt As String = mb.DeclaringType.Name
How can I then use this to obtain the Form Object so I can pass this to my 'screenshot method' that screenshots the particular form referenced.
Public Sub SaveAsImage(frm As Form)
'Dim fileName As String = "sth.png"
'define fileName
Dim format As ImageFormat = ImageFormat.Png
Dim image = New Bitmap(frm.Width, frm.Height)
Using g As Graphics = Graphics.FromImage(image)
g.CopyFromScreen(frm.Location, New Point(0, 0), frm.Size)
End Using
image.Save(_LogPath & Date.Now.ToString("ddMMyyyy") & ".png", format)
End Sub
I posted the same solution to a similar question. Try this:
Dim frm = Application.OpenForms.Item(dt)

Save a Collection of objects to disk Windows 10 Universal App

I have a collection of objects which also contain collections, and I would like to save them to a file and read later. This is Windows 10 UNIVERSAL app .net 4.5 and in VB
I've this, but it gives the error "Synchronous operations should not be performed on the UI thread. Consider wrapping this method in Task.Run."}
Public Sub SaveSpRules(FileName As String)
Dim fs As New FileStream(FileName, FileMode.OpenOrCreate)
Dim serializer As New XmlSerializer(GetType(Rule))
Dim writer As New StreamWriter(fs)
serializer.Serialize(writer, r)
End Sub
Rule is class and the collection is called SpecialRulesCollection, this code does compile but doesn't work
Any help is gratefully received. PLEASE note this for Windows 10 Universal app, I can't get BinaryWriter to compile as this isn't include in the Universal app.
Thanks Oyiwai I found the answer
Public Async Sub SaveSpRules(FileName As String, t As Object)
Dim myfile As StorageFile
myfile = Await ApplicationData.Current.LocalFolder.CreateFileAsync("test.dat", CreationCollisionOption.ReplaceExisting)
Dim KnownTypeList As New List(Of Type)
KnownTypeList.Add(GetType(Rules))
KnownTypeList.Add(GetType(Rule))
Dim r As Streams.IRandomAccessStream
r = Await myfile.OpenAsync(FileAccessMode.ReadWrite)
Using outStream As Streams.IOutputStream = r.GetOutputStreamAt(0)
Dim serializer As New DataContractSerializer(GetType(Rules), KnownTypeList)
serializer.WriteObject(outStream.AsStreamForWrite(), t)
Await outStream.FlushAsync()
outStream.Dispose()
r.Dispose()
End Using
End Sub
Public Async Sub ReadFile()
Dim t As New Collection(Of Rule)
Dim myfile As Stream
Dim r As New Rules
Dim KnownTypeList As New List(Of Type)
KnownTypeList.Add(GetType(Rules))
Dim serializer As New DataContractSerializer(GetType(Rules), KnownTypeList)
myfile = Await ApplicationData.Current.LocalFolder.OpenStreamForReadAsync("test.dat")
r = serializer.ReadObject(myfile)
End Sub

Calling System.IO.ReadAllBytes by string name

This post is related to Visual Basic .NET 2010
So, I'm wondering if there's any way to call a function from a library such as System.ReadAllBytes by string name.
I've been trying Assembly.GetExecutingAssembly().CreateInstance and System.Activator.CreateInstance followed by CallByName(), but none of them seemed to work.
Example of how I tried it:
Dim Inst As Object = Activator.CreateInstance("System.IO", False, New Object() {})
Dim Obj As Byte() = DirectCast(CallByName(Inst, "ReadAllBytes", CallType.Method, new object() {"C:\file.exe"}), Byte())
Help is (as always) much appreciated
It is System.IO.File.ReadAllBytes(), you missed the "File" part. Which is a Shared method, the CallByName statement is not flexible enough to permit calling such methods. You will need to use the more universal Reflection that's available in .NET. Which looks like this for your specific example, spelled out for clarity:
Imports System.Reflection
Module Module1
Sub Main()
Dim type = GetType(System.IO.File)
Dim method = type.GetMethod("ReadAllBytes")
Dim result = method.Invoke(Nothing, New Object() {"c:\temp\test.bin"})
Dim bytes = DirectCast(result, Byte())
End Sub
End Module

Strange error reported in this code, please explain?

I put together this bit of code from a few other samples, and I am getting an error I cant understand. On this line in the code below, on the word Observer,
Dim Results As ManagementObjectCollection = Worker.Get(Observer)
I get the error
"Value of type 'System.Management.ManagementOperationObserver' cannot be converted to 'Integer'"
Can somebody explain what this means?
There are two signatures for ManagementObjectSearcher.Get(), one has no parameters and the other has one parameter, a ManagementOperationObserver for async operation. That is what I am providing, yet the error indicates conversion involving an integer?
Public Shared Sub WMIDriveDetectionASYNC(ByVal args As String())
Dim Observer As New ManagementOperationObserver()
Dim completionHandler As New MyHandler()
AddHandler Observer.Completed, AddressOf completionHandler.Done
Dim Machine = "192.168.0.15"
Dim Scope = New ManagementScope("\\" & Machine & "\root\cimv2")
Dim QueryString = "select Name, Size, FreeSpace from Win32_LogicalDisk where DriveType=3"
Dim Query = New ObjectQuery(QueryString)
Dim Worker = New ManagementObjectSearcher(Scope, Query)
Dim Results As ManagementObjectCollection = Worker.Get(Observer) 'use parameter to make async
For Each item As ManagementObject In Results
Console.WriteLine("{0} {2} {1}", item("Name"), item("FreeSpace"), item("Size"))
Dim FullSpace As Long = (CLng(item("Size")) - CLng(item("FreeSpace"))) \ 1000000
Console.WriteLine(FullSpace)
Next
End Sub
Public Class MyHandler
Private _isComplete As Boolean = False
Public Sub Done(sender As Object, e As CompletedEventArgs)
_isComplete = True
End Sub 'Done
Public ReadOnly Property IsComplete() As Boolean
Get
Return _isComplete
End Get
End Property
End Class
Thanks for any advice!
I think that uses a reference type to get the result and put it in the object you sent as a parameter. So I think it just needs to look like:
Worker.Get(Observer)
instead of trying to set something = to that since it isn't a function that returns a value.
Then use the events you hook up to the object to handle whatever you need to do with the items you find.

How do I validate a string of XML against an XML Schema file

I'm developing a VB Web Application in .NET3.5 using Visual Studio 2008.
I'm having difficulty in validating some XML as a string before I add it to a HTML form to post to a 3rd party. I have an XML schema file from the 3rd party to validate against and at this point I'd like the application to perform the validation before each post.
After searching I've found references to a XmlValidatingReader but this is obsolete and I'm having difficulty finding another way to do it.
Also all the good examples are in C# - for now I'm stuck with VB. This is what I have so far which I'm looking for help with!
Public Function ValidateXML(ByVal strXML As String) As Boolean
' er how do I get the schema file into here?
Dim schema As XmlReader
Dim settings As XmlReaderSettings = New XmlReaderSettings()
settings.Schemas.Add("", schema)
settings.ValidationType = ValidationType.Schema
' When I use LoadXML to get the string I can't use the settings object above to get the schema in??
Dim document As XmlDocument = New XmlDocument()
document.LoadXml(strXML)
document.Validate(AddressOf ValidationEventHandler)
End Function
Private Sub ValidationEventHandler(ByVal sender As Object, ByVal e As ValidationEventArgs)
' Gonna return false here but haven't got to it yet! Prob set a variable for use above
End Sub
Thanks
Here's an example:
XmlSchemaValidator in VB.NET
UPDATE - Try this:
Public Function ValidateXML(ByVal strXML As String) As Boolean
Dim xsdPath As String = "path to your xsd"
Dim schema As XmlReader = XmlReader.Create(xsdPath)
Dim document As XmlDocument = New XmlDocument()
document.LoadXml(strXML)
document.Schemas.Add("", schema)
document.Validate(AddressOf ValidationEventHandler)
End Function
This is what I ended up going with
Public validationErrors As String = ""
Public Function ValidPortalRequest(ByVal XMLPortalRequest As String) As Boolean
Try
Dim objSchemasColl As New System.Xml.Schema.XmlSchemaSet
objSchemasColl.Add("xxx", "xxx")
objSchemasColl.Add("xxx", "xxxd")
Dim xmlDocument As New XmlDocument
xmlDocument.LoadXml(XMLPortalRequest)
xmlDocument.Schemas.Add(objSchemasColl)
xmlDocument.Validate(AddressOf ValidationEventHandler)
If validationErrors = "" Then
Return True
Else
Return False
End If
Catch ex As Exception
Throw
End Try
End Function
Private Sub ValidationEventHandler(ByVal sender As Object, ByVal e As ValidationEventArgs)
validationErrors += e.Message & "<br />"
End Sub
Same as Jose's except I've added 2 XSD as a SchemaSet rather than reading them in with an XMLReader.