Invoke EntryPoint of assembly without showing any window - VB.Net - vb.net

I need to execute an application embeeded in my resources . Heres my code :
Dim MainAssembly As Reflection.Assembly = Reflection.Assembly.GetExecutingAssembly()
Dim resourceStream As Stream = MainAssembly.GetManifestResourceStream("MyApp.Nircmd.exe")
If resourceStream Is Nothing Then
Throw New NullReferenceException("error")
End If
Dim toolAssemblyBuffer(CInt(resourceStream.Length) - 1) As Byte
resourceStream.Read(toolAssemblyBuffer, 0, toolAssemblyBuffer.Length)
resourceStream.Close()
AudioTool = Reflection.Assembly.Load(toolAssemblyBuffer)
Dim args() As String = {Application.StartupPath, "argumentsHere"}
Dim parameters = New Object() {args}
Try
AudioTool.EntryPoint.Invoke(Nothing, parameters)
Catch
End Try
This application opens a new cmd.exe window everytime , so , i need to invoke the EntryPoint without showing any window .
Is there a WindowStyle property or something equal in an assembly ?
Thanks

Related

VB RS.exe - DataSource is not defined

I have this code to programmatically export a report to PDF.
Public Sub Main()
TRY
DIM historyID as string = Nothing
DIM deviceInfo as string = Nothing
DIM extension as string = Nothing
DIM encoding as string
DIM mimeType as string = "application/Excel"
DIM warnings() AS Warning = Nothing
DIM streamIDs() as string = Nothing
DIM results() as Byte
rs.Credentials = System.Net.CredentialCache.DefaultCredentials
Dim dataSources() As DataSource = rs.GetItemDataSources("foldername/reportname")
rs.LoadReport(REPORTSERVER_FOLDER, historyID)
results = rs.Render(FORMAT, deviceInfo, extension, mimeType, encoding, warnings, streamIDs)
DIM stream As FileStream = File.OpenWrite(FILENAME)
stream.Write(results, 0, results.Length)
stream.Close()
Catch e As IOException
Console.WriteLine(e.Message)
End Try
End Sub
When I run it I get an error saying:
error BC30002: Type 'DataSource' is not defined.
Dim dataSources() As DataSource = rs.GetItemDataSources("foldername/reportname")
~~~~~~~~~~
Am I forgetting to import something? If I remove that line it works fine (besides that it needs a data source to be added). Adding the data source beforehand is not an option.
So I figured the answer. I am using the Exec2005 (execution endpoint), which does not include the definition for DataSource. I should instead use the default endpoint (Mgmt2005), but this causes other problems in the code.
In any case, the answer to this question is to not use -e Exec2005.

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)

vb.net running a exe in memory

I'm trying to run a app on memory but I'm having error at Invoke. What am I doing wrong?
I'm trying to do this but in vb.net
Code C#
// read the bytes from the application exe file
FileStream fs = new FileStream(filePath, FileMode.Open);
BinaryReader br = new BinaryReader(fs);
byte[] bin = br.ReadBytes(Convert.ToInt32(fs.Length));
fs.Close();
br.Close();
// load the bytes into Assembly
Assembly a = Assembly.Load(bin);
// search for the Entry Point
MethodInfo method = a.EntryPoint;
if (method != null)
{
// create an istance of the Startup form Main method
object o = a.CreateInstance(method.Name);
// invoke the application starting point
method.Invoke(o, null);
}
in vb:
Dim instance As FileStream = File.Open("teste.exe", FileMode.Open)
Dim br As New BinaryReader(instance)
Dim bin As Byte() = br.ReadBytes(Convert.ToInt32(instance.Length))
instance.Close()
br.Close()
Dim a As Assembly = Assembly.Load(bin)
Dim metodo As MethodInfo = a.EntryPoint
If (IsDBNull(metodo) = False) Then
'create an istance of the Startup form Main method
Dim o As Object = a.CreateInstance(metodo.Name)
'invoke the application starting point
metodo.Invoke(o, Nothing)
Else
MessageBox.Show("Nao encontrado")
End If
UPDATE:
I found the answer. I created the "test.exe" like a ConsoleAplication, than in the module I code
Imports System.Windows.Forms
Module Module1
Sub Main()
Dim Form1 As New Form1
Form1.Show()
Do Until Form1.Visible = False
Application.DoEvents()
Loop
End Sub
End Module
Then I changed from ConsoleApplication to Windowsform And create my Form1. And this
metodo.Invoke(o, Nothing)
to this:
metodo.Invoke(Nothing, New Object() {})
Thank you guys for the support!
The Main method expects that you pass it the args parameter. Your current call is not passing any parameters, so I'm expecting that you are getting the following error if it ever reaches that line:
System.Reflection.TargetParameterCountException: Parameter count mismatch.
To fix it, just pass a one-element object array as the second parameter of the method.Invoke. Also, because the Main method is a static method, you don't need to do a CreateInstance before invoking the method.
So all you need is this:
metodo.Invoke(Nothing, New Object() {Nothing})
If, for some reason, you actually need pass values to the main's args parameter, you can do it like this:
metodo.Invoke(Nothing, New Object() {New String() {"param1", "param2"}})
Assuming the c# code works you mistranslated the null check.
The equivalent of 'if (method != null)' in vb.net is
If method IsNot Nothing Then
Dim o = a.CreateInstance(method.Name)
method.Invoke(o, Nothing)
End If

Form crashes when uploading file on background thread

I am trying to upload a file using a thread. I have placed a simple file upload control and a button on a page.The code looks like this-
Protected Sub btnUpload_Click(ByVal sender As Object,
ByVal e As EventArgs) Handles btnUpload.Click
Dim timeStart As TimeSpan = Nothing
Dim timeEnd As TimeSpan = Nothing
Dim timeDiff As TimeSpan = Nothing
Dim ex As Exception = Nothing
Dim FileNameWithoutExtension As String = String.Empty
Try
Dim objTh As Thread = Nothing
objTh = New Thread(AddressOf SaveFileByBuffering)
timeStart = DateTime.Now.TimeOfDay
objTh.IsBackground = True
FileNameWithoutExtension = System.IO.Path.GetFileName(FldUploadThreading.FileName)
objTh.Start("New_" + FileNameWithoutExtension)
objTh.Name = "ARAThreadFileBuffer"
objTh.Join()
timeEnd = DateTime.Now.TimeOfDay
timeDiff = timeEnd - timeStart
Catch exThAbort As ThreadAbortException
ex = exThAbort
Catch exTh As ThreadStartException
ex = exTh
Catch exCommon As Exception
ex = exCommon
End Try
End Sub
Method to be called using thread:
Public Function SaveFileByBuffering(ByVal lstrFilePath As String)
Dim bufferSize As Integer = 512
Dim buffer As Byte() = New Byte(bufferSize - 1) {}
Dim pathUrl As String = ConfigurationManager.AppSettings("strFilePath").ToString()
Dim uploadObj As UploadDetail = New UploadDetail()
uploadObj.IsReady = True
uploadObj.FileName = lstrFilePath
uploadObj.ContentLength = Me.FldUploadThreading.PostedFile.ContentLength
Me.Session("UploadXDetail") = uploadObj
Dim Upload As UploadDetail = DirectCast(Me.Session("UploadXDetail"), UploadDetail)
Dim fileName As String = Path.GetFileName(Me.FldUploadThreading.PostedFile.FileName)
Using fs As New FileStream(Path.Combine(pathUrl, lstrFilePath), FileMode.Create)
While Upload.UploadedLength < Upload.ContentLength
Dim bytes As Integer = Me.FldUploadThreading.PostedFile.InputStream.Read(buffer, 0, bufferSize)
fs.Write(buffer, 0, bytes)
Upload.UploadedLength += bytes
End While
End Using
End Function
There are two issues:
When someone clicks on the same button simultaneously the thread behavior works in a different way, some time page crashes.
When this process I have tested on multi-user environment with 60 users and file size is 25 mb each user the page crashed.
I have to use .NET 3.5 so I cannot use the advanced version of file upload in 2010 or later.
Error : 1-File uploding is more than 15 minutes but still in progress 2- Internet explorer cannot explore the page -Diagnose Internet problems 3- some user get login probem to the server on which the site has hosted
The course I usually take in .NET is to use ThreadPool.QueueUserWorkItem
If you do this with anonymous lambdas, I find it makes the syntax and life rather nice. You can do something like this:
btnUpload.Enabled = False
ThreadPool.QueueUserWorkItem(Sub()
SaveFileByBuffering(FldUploadThreading.FileName)
RaiseEvent EnableButton
End Sub)
With this event handler:
Public Sub EnableButton() Handles EnableButton
If Me.InvokeRequired Then
Me.BeginInvoke(Sub() EnableButton())
Else
btnUpload.Enabled = True
EndIf
EndSub
My .NET is rusty and I don't have a compiler anywhere, but doing something like this should handle most of your issues.

CodeDom Black Box

VB.Net Code. I want to hide the black box that opens up with a compiled code... how?
It opens a cmd shell whenever I compile it...
Public Shared Function CompileVBCode(sourceFile As String, exeFile As String) As Boolean
Dim vbprovider As VBCodeProvider = New VBCodeProvider()
Dim cp As New CompilerParameters()
cp.ReferencedAssemblies.Add("System.dll")
cp.GenerateInMemory = False
cp.GenerateExecutable = True
cp.OutputAssembly = exeFile
Dim cr As CompilerResults = vbprovider.CompileAssemblyFromSource(cp, sourceFile)
cp.CompilerOptions += "/t:winexe"