How to send a class through named pipe in VB.net - vb.net

Using VB2008, I have 2 applications on 2 computers that needs to communicate. I setup a named pipe and so far, it's working. I can send strings, back and forth between those 2 programs.
Now, I need to be able to send a class, or an object. I have read somewhere that Serialization is the way to go. So, on the client, I have:
Public Class cTest
Dim Var1 As Boolean
Dim Var2 As String = "a test"
Dim Var3 As New Collections.ArrayList
Public Sub AddItem(ByVal Item As String)
Var3.Add(Item)
End Sub
End Class
Private Sub Button8_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button8.Click
Dim oClasse As New cTest
oClasse.AddItem("StarWars")
oClasse.AddItem("StarTrek")
oPipe.SendToPipe(oClasse)
End Sub
End Class
Public Sub SendToPipe(ByVal test As cTest)
Dim xmlTest As New Xml.Serialization.XmlSerializer(GetType(cTest))
xmlTest.Serialize(pipeClient, test)
End Sub
On the server side (on the remote computer):
Public Function ReadString() As String
Dim len As Integer = 0
len = CType(ioStream.ReadByte(), Integer) * 256
len += CType(ioStream.ReadByte(), Integer)
Try
Dim serializer As New Xml.Serialization.XmlSerializer(GetType(cTest))
Dim Test As cTest
Test = CType(serializer.Deserialize(ioStream), cTest)
Catch ex As Exception
End Try
End Function
The serializer.Deserialize throw an exception saying the XML format is not correct.
what I'm doing wrong?
thanks for your time and help

finally, after a lot of testing and googling, I figured it out:
when using the following code on the client side it works:
Dim oClasse As New cTest
oClasse.AddItem("StarWars")
oClasse.AddItem("StarTrek")
Using PStream As IO.Pipes.NamedPipeClientStream = New IO.Pipes.NamedPipeClientStream(".", "VisionEnginePipeRead1", PipeDirection.Out, PipeOptions.None, TokenImpersonationLevel.None)
PStream.Connect()
Dim xmlTest As New Xml.Serialization.XmlSerializer(GetType(cTest))
xmlTest.Serialize(PStream, oClasse)
End Using
and this, on the server side:
Dim Test As cTest
Using PStream As NamedPipeServerStream = New NamedPipeServerStream(pipeName, PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.None)
PStream.WaitForConnection()
Dim serializer As New Xml.Serialization.XmlSerializer(GetType(cTest))
Test = CType(serializer.Deserialize(PStream), cTest)
End Using

If I were you I would use WCF Self Hosted Services and let the two communicate using callbacks

This started as a comment but I was running out of room. I am no expert on named pipe communications but, it has been a couple hours, and it may be that that is not really the problem.
You need to first test the serialization/deserialization in the same application. In other words start by taking the pipes out of the picture. This will isolate whether this is a serialization issue or a named pipe issue. Assuming that you code will work when done in the same application, then you need to compare the xml generated by the two applications - have them both do a Serialize. If the xml is identical (which I doubt) then pass it through the pipe and compare it again.
Going further out on a limb here but you may see that the namespace is different for the ctest object. If this is the case it may help to define your shared classes in a library which is shared between the two applications.

Related

Creating a new IUI Automation Handler object in order to subscribe to an automation event

So, here it goes. To start, A disclaimer, I understand that MS Access is not built for this kind of work. It is my only option at this time.
I have done just a bit of Automation using UIAutomationClient and I have successfully used its other features, however I cannot for the life of me get it to subscribe to events.
Normally, it is supposed to be a bit like this:
Dim CUI as new CUIAutomation
Dim FocusHandler as IUIAutomationFocusChangedEventHandler
Set FocusHandler = new IUIAutomationFocusChangedEventHandler(onFocusChanged)
C.AddFocusChangedEventHandler(Element,TreeScope_Children, null, FocusHandler)
end function
'
'
Function onFocusChanged(src as Object, args as AutomationEventArgs)
''my code here
end function
Yet when I attempt this, I get the error "expected end of statement" on the line:
FocusHandler = new IUIAutomationFocusChangedEventHandler(onFocusChanged)
additionally, if I leave off the (onFocusChanged) I get the error "Invalid use of new Keyword".
It seems like I am missing a reference somewhere. The usual drop down when using "new" does not contain the IUI handler classes though they are in the object library.
I am not sure if there is just some piece I am not accounting for in the code since I am using vba, but all examples seem to be for .net or C#/C++. Any help would be appreciated.
Additionally, I have no problem finding the element in question and all other pieces work fine. If you need any other pieces of the code let me know.
Edit: added set to line 3. No change in the problem though.
After two years this probably isn't relevant any more, but perhaps somebody else encounters this problem... The answer is to create a new class that implements the HandleAutomationEvent method.
Here I created a class named clsInvokeEventHandler and (importantly) set the Instancing property to PublicNotCreatable:
Option Explicit
Implements IUIAutomationEventHandler
Private Sub IUIAutomationEventHandler_HandleAutomationEvent(ByVal sender As UIAutomationClient.IUIAutomationElement, ByVal eventId As Long)
Debug.Print sender.CurrentName
End Sub
And to use it:
Sub StartInvokeHandler()
Dim oUIA As New CUIAutomation8
Dim oRoot As IUIAutomationElement
Dim InvokeHandler As clsInvokeEventHandler
Set InvokeHandler = New clsInvokeEventHandler
Set oRoot = oUIA.GetRootElement
oUIA.AddAutomationEventHandler UIA_Invoke_InvokedEventId, oRoot, TreeScope_Descendants, Nothing, InvokeHandler
End Sub

Error in MATLAB COM Automation

Anyone knows how to do MATLAB COM autiomation in VB.NET? Since I really can't make my program works using the NE builder. I tried using the COM automation as documented here: http://www.mathworks.com/help/matlab/matlab_external/call-a-matlab-function-from-visual-basic-net-client.html
Again, my program is so simple. Here's the matlab code:
function out = addMe(a,b)
out = a + b;
end
Here's the VB code:
Public Class Form1
Dim a As Integer = 4
Dim b As Integer = 10
Dim result As String
Dim Matlab As Object
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Matlab = CreateObject("Matlab.Application")
result = Matlab.Execute("cd C:\Users\Elvin Gentiles\Desktop\Program")
result = Matlab.Execute("addMe(a,b)")
TextBox1.Text = result
End Sub
End Class
The result that I'm getting that is showing in the textbox is: ??? Undefined function or variable 'a'. I already made sure that the COM reference is already added.
But when I tried changing the code to this it is working. By the way, version is a matlab command used to show the version of the MATLAB.
result = Matlab.Execute("version")
I hope you can help me with this. I really needed this. Thanks
Everythings working perfect - COM-wise.
Ask yourself: what did you expect the function to return?
If the code above is complete, you defined neither a nor b in the matlab-session, so matlab of course complains about a not being defined.
Try
result = Matlab.Execute("addMe(1,2)")
instead.

Visual Basic: dynamically create objects using a string as the name

Is there a way to dynamically create an object using a string as the class name?
I've been off VB for several years now, but to solve a problem in another language, I'm forced to develop a wrapper in this one. I have a factory method to dynamically create and return an object of a type based on input from elsewhere. The provided input is meant to be the class name from which to create an object from. Normal syntax means that the entire class has to be explicitly spelled out. To do it this way, there could literally be hundreds of if/then's or cases to handle all the available class/object choices within the referenced libs:
If c_name = "Button" then obj = new System.Windows.Forms.Button
If c_name = "Form" then obj = new System.Windows.Forms.Form
....
I'm hoping instead to reduce all this case handling to a single line: IE...
my_class_name = "whateverclass"
obj = new System.Windows.Forms.my_class_name()
In PHP, this is handled like so...
$my_class_name = "whateverclass";
$obj = new $my_class_name();
Edit: Looking at some of the answers, I think I'm in way over my head here. I did manage to get it working using this CreateInstance method variation of the Assembly class, even though I'm more interested in this variation giving more options, including supplying construct parameters...
my_type_name = "System.Windows.Forms.Button"
asmb_name = "System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
button1 = Reflection.Assembly.Load(asmb_name).CreateInstance(my_type_name)
In other words, it takes a method to do this, and not any inherent language syntax? This Activator variation also worked when the full assembly string and class path is used. I'm suspicious CreateInstance may not have the full ability to let me treat objects as if they were called normally, ie obj = new System.Windows.Forms.Button. This is why I can't use simply CreateObject. If there is no natural language feature allowing you to substitute a class name for a string, does anyone have any insight into what sort of limitations I can expect from using CreateInstance?
Also, is there even a difference between basic Activator.CreateInstance (after Unwrap) and Assembly.CreateInstance methods?
This will likely do what you want / tested working; switch the type comment at the top to see.
Imports System.Reflection
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
' Dim fullyQualifiedClassName as String = "System.Windows.Forms.TextBox"
Dim fullyQualifiedClassName As String = "System.Windows.Forms.Button"
Dim o = fetchInstance(fullyQualifiedClassName)
' sometime later where you can narrow down the type or interface...
Dim b = CType(o, Control)
b.Text = "test"
b.Top = 10
b.Left = 10
Controls.Add(b)
End Sub
Private Function fetchInstance(ByVal fullyQualifiedClassName As String) As Object
Dim nspc As String = fullyQualifiedClassName.Substring(0, fullyQualifiedClassName.LastIndexOf("."c))
Dim o As Object = Nothing
Try
For Each ay In Assembly.GetExecutingAssembly().GetReferencedAssemblies()
If (ay.Name = nspc) Then
o = Assembly.Load(ay).CreateInstance(fullyQualifiedClassName)
Exit For
End If
Next
Catch
End Try
Return o
End Function
I'm pretty sure Activator is used for remoting. What you want to do is use reflection to get the constor and invoke it here's an example http://www.eggheadcafe.com/articles/20050717.asp
EDIT: I was misguided about Activator until jwsample corrected me.
I think the problem your having is that your assembly is the one that GetType is using to try and find Button. You need to call it from the right assembly.
This should do it
Dim asm As System.Reflection.Assembly = System.Reflection.Assembly.LoadWithPartialName("System.Windows.Forms")
Dim obj As Object = Activator.CreateInstance(asm.GetType("System.Windows.Forms.Button"))
Take a look at the Activator.CreateInstance(Type) method.
If your input is the name of a class you should be able do this:
Dim obj As Object = Activator.CreateInstance(GetType("Name_Of_Your_Class"))
You'll have to fiddle with the GetType call to make sure you give it enough information but for most cases just the name of the class should work.
Here is a really easy way I have found while rummaging through the internet:
dynamicControl = Activator.CreateInstance(Type.GetType("MYASSEMBLYNAME." + controlNameString))

VB.NET Read Certain text in a text file

I want my program to read certain text in a text file. For example if I have a text file that contains the following info..
acc=blah
pass=hello
I want my vb.net application to get that the account variable is equal to blah, and the password variable is equal to hello.
Can anyone tell me how to do this?
Thanks
Here is a quick little bit of code that, after you click a button, will:
take an input file (in this case I created one called "test.ini")
read in the values as separate lines
do a search, using regular expressions, to see if it contains any "ACC=" or "PASS=" parameters
then write them to the console
here is the code:
Imports System.IO
Imports System.Text.RegularExpressions
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim strFile As String = "Test.INI"
Dim sr As New StreamReader(strFile)
Dim InputString As String
While sr.Peek <> -1
InputString = sr.ReadLine()
checkIfContains(InputString)
InputString = String.Empty
End While
sr.Close()
End Sub
Private Sub checkIfContains(ByVal inputString As String)
Dim outputFile As String = "testOutput.txt"
Dim m As Match
Dim m2 As Match
Dim itemPattern As String = "acc=(\S+)"
Dim itemPattern2 As String = "pass=(\S+)"
m = Regex.Match(inputString, itemPattern, _
RegexOptions.IgnoreCase Or RegexOptions.Compiled)
m2 = Regex.Match(inputString, itemPattern2, _
RegexOptions.IgnoreCase Or RegexOptions.Compiled)
Do While m.Success
Console.WriteLine("Found account {0}", _
m.Groups(1), m.Groups(1).Index)
m = m.NextMatch()
Loop
Do While m2.Success
Console.WriteLine("Found password {0}", _
m2.Groups(1), m2.Groups(1).Index)
m2 = m2.NextMatch()
Loop
End Sub
End Class
Have a look at this article
Reading and writing text files with VB.NET
Wile reading the file line by line, you can use String.Split Method with the splitter being "=", to split the string into param name, and param value.
Looks like you've got an INI file of some kind... The best way to read these is using the *PrivateProfile* functions of the windows API, which means you can actually have a proper full INI file quite easily for anything you need. There is a wrapper class here you may like to use.
Microsoft recommends that you use the registry to store this sort of information though, and discourages use of INI files.
If you wish to just use a file manually with the syntax you have, it is a simple case of splitting the string on '=' and put the results into a Dictionary. Remember to handle cases where the data was not found in the file and you need a default/error. In modern times though, XML is becoming a lot more popular for data text files, and there are lots of libraries to deal with loading from these.
My suggestion: you use XML. The .NET framework has a lot of good XML tools, if you're willing to make the transition to put all the text files into XML, it'll make life a lot easier.
Not what you're looking for, probably, but it's a cleaner solution than anything you could do with plain text (outside of developing your own parser or using a lower level API).
You can't really selectively read a certain bit of information in the file exclusively. You'll have to scan each line of the file and do a search for the string "pass=" at the beginning of the line. I don't know VB but look up these topics:
File readers (espically ones that can read one line at a time)
String tokenizers/splitting (as Astander mentioned)
File reading examples
Have you thought about getting the framework to handle it instead?
If you add an entry into the settings tab of the project properties with name acc, type string, scope user (or application, depending on requirements) and value pass, you can use the System.Configuration.ApplicationSettingsBase functionality to deal with it.
Private _settings As My.MySettings
Private _acc as String
Private _pass as String
Public ReadOnly Property Settings() As System.Configuration.ApplicationSettingsBase
Get
If _settings Is Nothing Then
_settings = New My.MySettings
End If
Return _settings
End Get
End Property
Private Sub SetSettings()
Settings.SettingsKey = Me.Name
Dim theSettings As My.MySettings
theSettings = DirectCast(Settings, My.MySettings)
theSettings.acc=_acc
theSettings.pass=_pass
Settings.Save()
End Sub
Private Sub GetSettings()
Settings.SettingsKey = Me.Name
Dim theSettings As My.MySettings
theSettings = DirectCast(Settings, My.MySettings)
_acc=theSettings.acc
_pass=theSettings.pass
End Sub
Call GetSettings in whatever load event you need, and SetSettings in closing events
This will create an entry in the application.exe.config file, either in your local settings \apps\2.0\etc etc directory, or your roaming one, or if it's a clickonce deployment, in the clickonce data directory. This will look like the following:-
<userSettings>
<MyTestApp.My.MySettings>
<setting name="acc" serializeAs="String">
<value>blah</value>
</setting>
<setting name="pass" serializeAs="String">
<value>hello</value>
</setting>
</MyTestApp.My.MySettings>
</userSettings>
Writing your own parser is not that hard. I managed to make one for a game (Using C#, but VB appears to have Regex class too. Using that, the acc variable in your file would be everything up to the = sign, and then blah would be everything past the = to the newline character (\n) Then go to the next line and repeat.
I have written this for you, check it and enjoy with the results, have a great day!
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim acc As New List(Of String)
Dim pass As New List(Of String)
Dim lines() As String = System.IO.File.ReadAllLines(".\credentials.txt")
For Each lineItem As String In lines
Dim vals() As String = lineItem.Split(Convert.ToChar("="))
If vals.Length > 0 Then
Dim lineId As String = vals(0)
If lineId = "acc" Then
acc.Add(vals(1))
ElseIf lineId = "pass" Then
pass.Add(vals(1))
End If
End If
Next
TextBox_acc.Text = String.Join(Environment.NewLine, acc)
TextBox_pass.Text = String.Join(Environment.NewLine, pass)
End Sub
End Class

How to mock a method (custom behavior) with Rhino Mocks in VB.NET

How can I mock one method with RhinoMocks in VB.Net? The reference I found is in C#:
Expect.Call(delegate{list.Add(0);}).IgnoreArguments()
.Do((Action<int>)delegate(int item) {
if (item < 0) throw new ArgumentOutOfRangeException();
});
SharpDevelop converts this to:
Expect.Call(Function() Do
list.Add(0)
End Function).IgnoreArguments().Do(DirectCast(Function(item As Integer) Do
If item < 0 Then
Throw New ArgumentOutOfRangeException()
End If
End Function, Action(Of Integer)))
But that doesn't work either (it doesn't compile).
This is what I want to do: create a new object and call a method which sets some properties of that method. In real-life this method, will populate the properties with values found in the database. In test, I would like to mock this method with a custom method/delegate so that I can set the properties myself (without going to the database).
In pseudo-code, this is what I'm trying to do:
Dim _lookup As LookUp = MockRepository.GenerateMock(Of LookUp)()
_luvalue.Expect(Function(l As LookUp) l.GetLookUpByName("test")).Do(Function(l As LookUp) l.Property = "value")
Unfortunately you're attempting to do both a Sub lambda and a Statement Lambda. Neither are supported in VS2008 (but will be in the upcoming version of VS). Here is the expanded version that will work for VB
I'm guessing at the type of m_list
Class MockHelper
Dim m_list as new List(Of Object)
Public Sub New()
Expect(AddressOf CallHelper).IgnoreArguments().Do(AddressOf Do Hepler)
End Sub
Private Sub CallHelper()
m_list.Add(0)
End Sub
Private Sub DoHelper(ByVal item as Integer)
if item < 0 Then
Throw New ArgumentOutOfRangeException
End If
End Sub
End Class
I have never mocked something w/ both a delegate and a lambda so I can't give a full solution to this problem, but I did want to share some example code for the usual "AssertWasCalled" function in Rhino Mocks 3.5 for vb developers because I spent some time trying to grok this... (keep in mind the below is kept simple for brevity)
This is the method under test - might be found inside a service class for the user object
Public Sub DeleteUserByID(ByVal id As Integer) Implements Interfaces.IUserService.DeleteUserByID
mRepository.DeleteUserByID(id)
End Sub
This is the interactive test to assert the repository method gets called
<TestMethod()> _
Public Sub Should_Call_Into_Repository_For_DeleteProjectById()
Dim Repository As IUserRepository = MockRepository.GenerateStub(Of IUserRepository)()
Dim Service As IUserService = New UserService(Repository)
Service.DeleteUserByID(Nothing)
Repository.AssertWasCalled(Function(x) Wrap_DeleteUserByID(x))
End Sub
This is the wrap function used to ensure this works w/ vb
Function Wrap_DeleteUserByID(ByVal Repository As IUserRepository) As Object
Repository.DeleteUserByID(Nothing)
Return Nothing
End Function
I found this to be a very nasty solution, but if it helps someone w/ the same issues I had it was worth the time it took to post this ;)