I'm a beginner so I'll try to be as clear as I can.I want to know if it is possible to run a custom application and have it return and store a result in a boolean,int or string in another application(the one that calls it) ? Basically I want it to behave like a function that returns a value but to another program that calls it instead. I would like to do it in VB.net. Something like this when it comes to using boolean :
a = Process.Start("C:\path_to\myapp.exe")
if (a) then
'execute
end if
At the simplest level, no, the design of the process mechanism doesn't inherently afford the ability to do what you're suggesting. The closest you could get is for the called process to exit with a particular return value, but that requires use of a particular API (GetExitCodeProcess) - not the return from the Start method you've illustrated here.
You can do such things as capture the output of the new process, which isn't a very robust solution, or create a temporary file that contains a value the "calling" process can read, which is even less robust. The other extreme would be to investigate specific techniques for interprocess communication.
If you could expand a bit on your problem, a more specific set of possible solutions could be offered. If your value of interest is being generated by a library or some shared code, that might afford a much more suitable return mechanism.
Here's an example of ConsoleApplication :
Imports System.IO
Module Main
Sub Main()
Dim Output As Boolean = File.Exists(My.Computer.FileSystem.SpecialDirectories.Desktop & "\file.txt")
Console.WriteLine(Output)
End Sub
End Module
And how to read the output (stdout) of the previous console application (this function returns a Boolean) :
Public Function GetOutput(executable As String) As Boolean
Using p As New Process With {.StartInfo = New ProcessStartInfo With {
.CreateNoWindow = True,
.FileName = executable,
.RedirectStandardOutput = True,
.WindowStyle = ProcessWindowStyle.Hidden,
.UseShellExecute = False}}
p.Start()
Dim output As String = p.StandardOutput.ReadToEnd()
p.WaitForExit()
Return CBool(output.Trim)
End Using
End Function
You can now do what you wanted to do by using this :
a = GetOutput("C:\path_to\myapp.exe")
If a Then
'execute
End If
See also (in C#) : How to make a Main Method of a console based application to return a string type.
Related
Public Function PiesTableTest(compairFile As String, version1 As String, Optional silent As Boolean = False) As Boolean
Dim dpgs As New frmDetailProgress
Dim retturn As Boolean
PiesThreadedTableTest(compairFile, version1, silent, dpgs)
End Function
Async Function PiesThreadedTableTest(compairFile As String, version1 As String, silent As Boolean, dpgs As frmDetailProgress) As Task(Of Boolean)
Dim ctl() As xmlControlAry
Dim xmlDoc As XElement
Dim xmlNodes As IEnumerable(Of XElement)
Dim notfound(0) As String
version = version1
nodeErrors = False
If Not silent Then
dpgs.lblTital.Text = "Pies Configuration Check"
dpgs.add("Pies Version = " & version)
dpgs.add("Loading Config Data....")
dpgs.Show()
End If
' load configuration data
GetPiesControl(ctl, version)
' load test xml file
xmlDoc = XElement.Load(compairFile)
xmlNodes = xmlDoc.Elements()
For Each ele As XElement In xmlNodes
NodeDrill("", ele, ctl, dpgs, notfound, silent)
Next
If nodeErrors And Not silent Then
dpgs.add("Testing done with Errors!!!", "R")
Else
dpgs.add("Testing Done NO ERRORS!", "G")
End If
Application.DoEvents()
If silent Then
dpgs.Dispose()
End If
'PiesThreadedTableTest = Not nodeErrors
If nodeErrors Then
Return False
Else
Return True
End If
End Function
I am trying to understand multi threading. frmDetailProgress is a "please wait " kind of form. and i have a animated gif on it. Plus it has a check box to close automatically after completion. Well the form is frozen till the process is done. I am trying to get the piesthreadedtabletest to run in another thread. I have read allot on this but i just don't understand the concept. I don't understand the await function enough to make this work. i get that await is designed to stop processing until something happens. But i want that form freed up to work. I get an error saying that the function will run synchronously unless i have an await - Why?
I got it working. It was a lack of understanding and i probably still need to learn more. I hope this will help someone in the future.
i created a class to call functions in the other class running in the second thread.
imports system.threading
public sub callThreadedProcedure()
dim tp as system.threading.thread ' this will be for the object running in the other thread
dim objectToRun as myclass ' this is the object you want to run in the thread
'this gets the object and puts it into the new thread
tp = new thread(sub() objectToRun.FunctionToRun(<put your parameters here if any>))
' start execution of the object in a new thread.
tp.start()
' that will get it to run in a separate thread. It works, there might be a better way
' and might not work in all situations, but for now it fixed my problem.
end sub
if you are trying to run functions in the original thread you need to pass a
reference to that object to the one in the second thread. you must then use invoke to run a function or sub from the second thread.
Invoke(sub() obj.function(<parameters>))
thanks Idle_mind invoked worked like it should.
I appreciate all that helped me along.
I've built a file copying routine into a common library for a variety of different (WinForms) applications I'm currently working on. What I've built implements the commonly-used CopyFileEx method to actually perform the file copy while displaying the progress, which seems to be working great.
The only real issue I'm encountering is that, because most of the file copying I'm doing is for archival purposes, once the file is copied, I would like to "verify" the new copy of the file. I have the following methods in place to do the comparison/verification. I'm sure many of you will quickly see where the "problem" is:
Public Shared Function CompareFiles(ByVal File1 As IO.FileInfo, ByVal File2 As IO.FileInfo) As Boolean
Dim Match As Boolean = False
If File1.FullName = File2.FullName Then
Match = True
Else
If File.Exists(File1.FullName) AndAlso File.Exists(File2.FullName) Then
If File1.Length = File2.Length Then
If File1.LastWriteTime = File2.LastWriteTime Then
Try
Dim File1Hash As String = HashFileForComparison(File1)
Dim File2Hash As String = HashFileForComparison(File2)
If File1Hash = File2Hash Then
Match = True
End If
Catch ex As Exception
Dim CompareError As New ErrorHandler(ex)
CompareError.LogException()
End Try
End If
End If
End If
End If
Return Match
End Function
Private Shared Function HashFileForComparison(ByVal OriginalFile As IO.FileInfo) As String
Using BufferedFileReader As New IO.BufferedStream(File.OpenRead(OriginalFile.FullName), 1200000)
Using MD5 As New System.Security.Cryptography.MD5CryptoServiceProvider
Dim FileHash As Byte() = MD5.ComputeHash(BufferedFileReader)
Return System.Text.Encoding.Unicode.GetString(FileHash)
End Using
End Using
End Function
This CompareFiles() method checks a few of the "simple" elements first:
Is it trying to compare a file to itself? (if so, always return True)
Do both files actually exist?
Are the two files the same size?
Do they both have the same modification date?
But, you guessed it, here's where the performance takes the hit. Especially for large files, the MD5.ComputeHash method of the HashFileForComparison() method can take a while - about 1.25 minutes for a 500MB file for a total of about 2.5 minutes to compute both hashes for the comparison. Does anyone have a better suggestion for how to more efficiently verify the new copy of the file?
I need to load My.settings from the first Solution into the Second.
In the first project I have a helper class for getting the Settings.
Public Class format
Public NotInheritable Class Helper
Private Sub New()
End Sub
Public Shared Function getAppSetting() As String
Dim returnValue As Object = My.Settings.format
If returnValue Is Nothing Then
Return String.Empty
Else
Return returnValue.ToString
End If
End Function
Public Shared Function getAppSettingTheme() As String
Dim returnValue_theme As Object = My.Settings.theme_selected
If returnValue_theme Is Nothing Then
Return String.Empty
Else
Return returnValue_theme.ToString
End If
End Function
End Class
End Class
This class I have implemented in the other Solutions (Even addiction I have a set)
In other Solutions I have the code for getting the Settings.
Imports MyProject.format.Helper
MsgBox(getAppSettingTheme())
But in the MsgBox I see Default Settings (Unchanged) While in the first solution displays the user-changed settings.
My.Settings I have saved [My.settings.save]
If you choose to do this in a complicated way,what you have to do is,make classes in the first project to read My.Settings,then reference the project in the other project and use it...
However,i'll rather describe an easier way(tho the above one is not that hard) to achieve your goal.
Firstly,i believe that you are using My.Settings to store some data,right ?If so,you can simply save the data to a text file and read it from anywhere you want.This will save plenty of your code and make it tidy :)
As you seem to be a beginner,i would try to keep it as simple as possible and explain in the simplest words...
Now,let's assume,you have 4 My.Settings entries as follows :
UserName
Password
Phone
Age
Instead of writing this data in My.Settings,write it to a text file.Let's assume a user inputs relevant data and it looks somewhat like this :
Zack Rayan
1212121
+090990809809
20
To write a text file, you can simply use File.WriteAllText but as we see that here,our data is in multiline,we can make use of the following :
FIle.WriteAllLines
File.AppendText
Well,let's use File.AppendText method(you can use the below code with WriteAllText as well :)) :
File.AppendText("C:\test.mycustomExtension" , "Zack Rayan" + Environment.NewLine + "1212121" + Environment.NewLine + "+090990809809" + Environment.NewLine + "20")
This will write a text file for you containing the given data in separate lines as well as you will have your own custom extension for the file :)
Now,how to use it ?
Simple :
Dim ReadFile as New List(Of String)(File.ReadAllLines("C:\Test.mycustomextension"))
Now,let's assume,when you were using My.Settings, you used some codes like this :
If My.Settings.UserName = "Zack" Then
......
Scroll up and look closely.UserName was your first entry in My.Settings and when we wrote the text file,ZACK RAYAN-the assumed username was also written in the first line
A few lines above, i created a list which reads the text file.It needs no saying that it will read(and store) the first line first and then move on gradually. So,where you used :
If My.Settings.UserName = "Zack" Then
u should now use :
If ReadFile(0) = "Zack" Then
I hope this helps to enrich your knowledge :)
So I am working with Coded UI to run some automated tests and one of the tests takes an extremely long time to complete.
I used breakpoints and found that after End Get in the bottom block of code, nothing happens for minutes and then finally the Assert.AreEqual completes and the test passes.
I tried changing a few playback settings but nothing changed. Does anyone know what is going on, and how I can fix it?
-The first block of code is a generated Assert method that gets called by the test
-The second block of code is called in the Assert parameters
'''<summary>
'''assert_clicked_columnhead_requestor - Use 'assert_clicked_columnhead_requestorExpectedValues' to pass parameters into this method.
'''</summary>
Public Sub assert_clicked_columnhead_requestor()
Dim uINameCell As HtmlCell = Me.UIAppWindow1.UIAppDocument.UIX978532666mkrdataTblTable1.UINameCell
'Verify that 'Name' cell's property 'InnerText' equals 'Name'
Assert.AreEqual(Me.assert_clicked_columnhead_requestorExpectedValues.UINameCellInnerText, uINameCell.InnerText)
End Sub
Public Overridable ReadOnly Property assert_clicked_columnhead_requestorExpectedValues() As assert_clicked_columnhead_requestorExpectedValues
Get
If (Me.massert_clicked_columnhead_requestorExpectedValues Is Nothing) Then
Me.massert_clicked_columnhead_requestorExpectedValues = New assert_clicked_columnhead_requestorExpectedValues()
End If
Return Me.massert_clicked_columnhead_requestorExpectedValues 'PROBLEM HERE
End Get
End Property
As requested
'''<summary>
'''click_columnhead_requestor
'''</summary>
Public Sub click_columnhead_requestor()
Dim uIRequestorCell As HtmlHeaderCell = Me.UIAppWindow1.UIAppDocument.UIRequestorCell
'Click 'Requestor' cell
Mouse.Click(uIRequestorCell, New Point(51, 23))
End Sub
Public ReadOnly Property UIAppWindow1() As UIAppWindow1
Get
If (Me.mUIAppWindow1 Is Nothing) Then
Me.mUIAppWindow1 = New UIAppWindow1()
End If
Return Me.mUIAppWindow1
End Get
End Property
Public ReadOnly Property UIX978532666mkrdataTblTable1() As UIX978532666mkrdataTblTable1
Get
If (Me.mUIX978532666mkrdataTblTable1 Is Nothing) Then
Me.mUIX978532666mkrdataTblTable1 = New UIX978532666mkrdataTblTable1(Me)
End If
Return Me.mUIX978532666mkrdataTblTable1
End Get
End Property
Coded UI does searches for precisely what is given in the search and filter properties, that operates quite fast. However, if that search fails then Coded UI does a smart match trying to find something similar and that can take a long time. It is necessary because titles etc can change a little from run to run. Changing the tests to avoid needing a smart match can dramatically improve the search speed. The general approach is to modify the search from equality to contains and to remove the part of the string that changes. A Microsoft blog explains in more detail, see http://blogs.msdn.com/b/dave_froslie/archive/2012/08/10/why-do-my-coded-ui-tests-pause-during-playback.aspx
¿? have you tried changing the value of ..
Playback.PlaybackSettings.SearchTimeout = miliseconds;
msdn playbacksettings.searchtimeout
good luck and tell us something
I have developed a Visual Basic.net application that uses serialization to save an object. I am wanting to open and save this object in two different Visual Basic.net applications.
What is the best way to do this? Do I need to create a class library to do this?
Can I please have some help for this?
EDIT
I am wanting to be able to open and save the object in both applications.
Depending on how complicated your data is, you should be able to simply mark your data's class with a <Serializable> attribute. You can then simply call the Serialize method in one application, save to disk, then read the file into your other application and call Deserialize.
You will need to define the class in both applications, which is easiest to do by sharing a common library.
See the MDSN example for basic serialization.
You can write/read to xml, then you would just have to check the folder where you save them from the other app to see if a new file has been created or updated.
Function to serialize object and write to xml
Public Function MyObjectFileGeneration()
Try
Dim strPath As String = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().CodeBase)
strPath = Replace(strPath, "file:\", "")
Dim myObj = Form1.MyObject
Dim objStreamWriter As New StreamWriter(strPath & "\MyFolder\MyObj.xml", False)
Dim x As New XmlSerializer(s.GetType)
x.Serialize(objStreamWriter, MyObj)
objStreamWriter.Close()
Return True
Catch ex As Exception
'Do something here if failure...
Return False
End Try
End Function
Function to read xml and de-serialize to object
Public Function GetMyObjFromXMLFile() As MyObj
'check if file exists first...
If xmlFileExists() Then
Dim strPath As String = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().CodeBase)
Dim objStreamReader As New StreamReader(Replace(strPath & "\MyFolder\MyObj.xml", "file:\", ""))
Dim MyObj As New MyObject
Dim x As New XmlSerializer(MyObj.GetType)
MyObj = x.Deserialize(objStreamReader)
objStreamReader.Close()
Return MyObj
Else
Return New MyObj
End If
End Function
I wish there was an easy way to do this, but unfortunately, I hit this wall also..
Serializable data can only be reread by the SAME application. (it gives you a lovely error message about this.) I tried using a serialized connection for simplified packet transfers, unsuccessfully..
Depending on how good you are at programming, I have a recommendation on this one..
Serialize your variables to a memorystream, then cut the header section out and shove it to another file stream, then when you reload it, save a variable to a memorystream to get the new header, then attach the remaining data, then read serialization..
haven't tried it yet, but when I get back to it, this is my next method.
I did see an XML method, but recommend using a compression/encryption library to keep your data safe.. did see some simple ways to possibly do that..
Sorry, I don't have code on this round, but when I investigate it, I will append this response..