Variable 'TargetProcess' hides a variable in an enclosing block - vb.net

So im making a dll injector and im getting this error: Variable 'TargetProcess' hides a variable in an enclosing block.
Code:
Dim httpclient = New Net.WebClient
httpclient.Credentials = New Net.NetworkCredential("ftp_username", "ftp_password")
httpclient.DownloadFile("ftp:/you.gifrsite.com/Cheat.dll", Application.StartupPath & "\Cheat.dll")
IO.File.Move(Application.StartupPath & "\Cheat.dll", Cheat)
Dim TargetProcess As Process() = Process.GetProcessesByName("PROCESS NAME")
If TargetProcess.Length = 0 Then Me.TextBox1.Text = ("Waiting for GAME.exe")

The compiler error is meaningful, you have two variables with the same name inside this scope. Rename one of both. Since Process.GetProcessesByName returns an Process()(so possibly multiple) i'd name it targetProcesses(plural):
Dim targetProcesses As Process() = Process.GetProcessesByName("PROCESS NAME")

Related

Running VB.Net code in my program, without creating instances, or parameters. Is it possible?

I am currently trying to make a program where you can type a VB.NET script into a richtextbox (strCode) and then execute it. Like as if I executed it in Visual Studio.
My current code look like this:
Dim objCompilerParameters As New CompilerParameters
objCompilerParameters.ReferencedAssemblies.Add("Microsoft.VisualBasic.dll")
objCompilerParameters.ReferencedAssemblies.Add("System.dll")
objCompilerParameters.ReferencedAssemblies.Add("System.Windows.Forms.dll")
objCompilerParameters.GenerateInMemory = True
Dim objCompileResults As CompilerResults
Dim Provider As CodeDomProvider = CodeDomProvider.CreateProvider("VisualBasic")
objCompileResults = Provider.CompileAssemblyFromSource(objCompilerParameters, strCode)
' Get a reference to the assembly.
'
Dim objAssembly As System.Reflection.Assembly = objCompileResults.CompiledAssembly
' Create an instance of the DynamicCode class referenced in the source code.
'
Dim objTheClass As Object = objAssembly.CreateInstance("Dynam.DynamicCode")
'----------------------------------------------------------------------------------------------------
' Create a parameter to be passed into the ExecuteCode function in class DynamicCode.
Dim objFunctionParameters(0) As Object
objFunctionParameters(0) = "Parameter 1"
'----------------------------------------------------------------------------------------------------
'Creating Result
Dim objResult As Object = objTheClass.GetType.InvokeMember("ExecuteCode", _
BindingFlags.InvokeMethod, Nothing, objTheClass, objFunctionParameters)
'---------------------
This runs fine .. as long as the namespace in my script is "Dynam", and the public class is "TestClass". Also the Public Function has to be named "ExecuteCode". Just like in the script.
Is there a way to create this, without having to hardcode the function and class names? So I can just call the classes, and functions whatever the user wants to call them.
Thanks in advance. I hope it made a little sense. If not, please let me know.

vb.net How to declare thread and call functions with it

I'm trying to use a thread to translate every text found in the Windows Forms to make my system multi-language.
I have a separate class named 'Language' with a sub and a function, sub reads a language source file, and function translates by receiving and returning a string.
Then I have my first Windows Form where I declare my thread:
Dim ThreadTraductor As New Thread(AddressOf ...) 'don't know how to do it
Dim cultureInfo As New System.Globalization.CultureInfo(ConfigurationManager.AppSettings('en').ToString)
ThreadTraductor.CurrentCulture = cultureInfo
ThreadTraductor.CurrentUICulture = cultureInfo
Basically I'm creating this thread to have a background process translating every Windows Form that's opened during execution, problem is I don't know how to declare it properly since I don't want to include any parameter when declaring, but I want the thread to be called from different Forms with parameters to translate, and also I want the thread to use my translate method inside Language class, is that possible? How?
Please assist, I haven't use threads before.
Public Class Lenguaje 'Class used to read language source file and translate strings
Public dicIdioma As New Dictionary(Of String, String)
Public Sub LeerArchivo(ByVal Culture As String)
Dim vectorAux() As String
dicIdioma.Clear()
Try
Dim LectorArchivo As New StreamReader("C:\Users\Joaqo\Desktop\Dorian VB\DorianBdBv1.0\UI\bin\Debug\" + Culture + ".txt")
Dim line As String
While Not LectorArchivo.Peek = -1
line = LectorArchivo.ReadLine()
vectorAux = line.Split(":")
dicIdioma.Add(vectorAux(0), vectorAux(1))
End While
Catch ex As System.IO.FileNotFoundException
MessageBox.Show("No se encuentra el archivo de idioma.")
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Public Function Traducir(ByRef frase As String) As String
Dim StringAux As String
For Each Item As String In dicIdioma.Keys
If Item = Char.ToLower(frase(0)) & frase.Substring(1) Then
StringAux = Char.ToUpper(dicIdioma.Item(Item)(0)) & dicIdioma.Item(Item).Substring(1)
frase = StringAux.Replace("_", " ")
ElseIf Item.Replace("_", " ") = Char.ToLower(frase(0)) & frase.Substring(1) Then
StringAux = Char.ToUpper(dicIdioma.Item(Item)(0)) & dicIdioma.Item(Item).Substring(1)
frase = StringAux.Replace("_", " ")
End If
Next
Return frase
End Function
End Class
Then I iterate every text object in my Windows Forms to translate them:
For Each Item As Label In Me.Controls.OfType(Of Label)()
Item.Text = Traductor.Traducir(Item.Text)
Next
For Each Item As Button In Me.Controls.OfType(Of Button)()
Item.Text = Traductor.Traducir(Item.Text)
Next
And it works just fine, but I'd be calling Traductor, Lenguaje's instance declared on my first interface, from the whole app, isn't that wrong somehow?
I was told that I should use Culture and CultureUI for this, but I'm not familiarized with that. What do you think? Sorry if I'm missing something, it's my first question here.

Extracting `dll` files from the Resources after they been added using CodeDOM in VB.Net

I'v seen a lot of answers here on stackoverflow, but none of them help me with exactly what i need and almost all of them in C# when i need VB, so i hope someone will help me with my problem, which is this :
I have compiled a exe file in vb.net using CodeDOM, and i added two dll file to its resources and that worked just fine and you can even notice that the size of the exe has increase after adding the resources, but when i run the exe file like that My.Resources.Touchless, it gives me an error saying that
"Resources" is not a member of "My".
And what i need is to read these dll files from the compiled exe file and then extract them using File.WriteAllBytes()..., if i didn't try to extract the files from the resources and instead of that i copied them manually to the executable path, the application will work perfectly, so the problem is just with trying to call the dll files from the resources.
Here is some code :
Public Shared Function Compile(ByVal Output As String, ByVal Source As String, ByVal Icon As String, ByVal resources As String) As Boolean
Dim Parameters As New CompilerParameters()
Dim cResults As CompilerResults = Nothing
Dim Compiler As CodeDomProvider = CodeDomProvider.CreateProvider("VB")
Parameters.GenerateExecutable = True
Parameters.TreatWarningsAsErrors = False
Parameters.OutputAssembly = Output
Parameters.MainClass = "MyNamespace.MainWindow"
Parameters.EmbeddedResources.Add(Path.GetTempPath & "TouchlessLib.dll")
Parameters.EmbeddedResources.Add(Path.GetTempPath & "WebCamLib.dll")
Parameters.ReferencedAssemblies.AddRange(New String() {"System.dll", "System.Drawing.dll", "System.Windows.Forms.dll", "System.Management.dll", Path.GetTempPath & "TouchlessLib.dll"})
Parameters.CompilerOptions = "/platform:x86 /target:winexe"
If Not String.IsNullOrEmpty(Icon) Then
File.Copy(Icon, "icon.ico")
Parameters.CompilerOptions += " /win32icon:" & "icon.ico"
End If
cResults = Compiler.CompileAssemblyFromSource(Parameters, Source)
If cResults.Errors.Count > 0 Then
For Each compile_error As CompilerError In cResults.Errors
Dim [error] As CompilerError = compile_error
Console.Beep()
MsgBox("Error: " & [error].ErrorText & vbCr & vbLf & [error].Line)
Next
Return False
End If
If Not (String.IsNullOrEmpty(Icon)) Then
File.Delete("icon.ico")
End If
Return True
End Function
When i call them from the compiled exe file like this :
File.WriteAllBytes(Application.StartupPath & "\TouchlessLib.dll", My.Resources.TouchlessLib)
File.WriteAllBytes(Application.StartupPath & "\WebCamLib.dll", My.Resources.WebCamLib)
... i get the following error message :
"Resources" is not a member of "My".
Try adding this class:
Imports System.Dynamic
Imports System.Reflection
Public Class DynamicResources
Inherits DynamicObject
Public Overrides Function TryGetMember(binder As GetMemberBinder, ByRef result As Object) As Boolean
Dim asm As Assembly = Assembly.GetExecutingAssembly()
Dim resouceNames As String() = asm.GetManifestResourceNames
For Each s As String In resouceNames
Dim name As String = IO.Path.GetFileNameWithoutExtension(s)
Dim Manager As New Resources.ResourceManager(name, asm)
Try
Dim resource = Manager.GetObject(binder.Name)
If Not resource Is Nothing Then
result = resource
Return True
End If
Catch ex As Exception
End Try
Next
Return False
End Function
End Class
You can use it like this:
Dim root as string=Application.StartupPath
File.WriteAllBytes(Path.Combine(root, "TouchlessLib.dll"), DynamicResources.TouchlessLib)
File.WriteAllBytes(Path.Combine(root, "WebCamLib.dll"), DynamicResources.WebCamLib)
The My namespace and any associated functionality is created via auto-generated code. Since your code is now the code generator and not the IDE, you will not have those niceties unless your code provides it.
To extract an embedded resource, you need to include code similar to the following in the source code you are compiling with CodeDOM.
Dim asm As Assembly = Assembly.GetExecutingAssembly()
Dim resouceNames As String() = asm.GetManifestResourceNames
For Each s As String In resouceNames
Dim fi As New FileInfo(s)
Using strm As Stream = asm.GetManifestResourceStream(s)
Using fs As Stream = fi.Create()
strm.CopyTo(fs)
End Using
End Using
Next
Make sure that you also include:
Imports System.Reflection
Imports System.IO
This code retrieves the executing Assembly obtains an array of embedded resource names. It then calls GetManifestResourceStream method to get the named resource as a stream. This stream is copied to a file stream.
Modify the example to suite your needs.
Note that I have not included any error checking/handling in this example. Anything dealing with IO should have some error handling.
Edit:
Based on the comment below, it appears that only a copy/paste type answer will do for the OP.
Dim asm As Assembly = Assembly.GetExecutingAssembly()
Dim resourceName As String
Dim fi As FileInfo
resourceName = "TouchlessLib.dll"
fi = New FileInfo(Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, resourceName))
Using strm As Stream = asm.GetManifestResourceStream(resourceName)
Using fs As Stream = fi.Create()
strm.CopyTo(fs)
End Using
End Using

Compiling and running code in runtime

I am trying to compile and run code at runtime. I am using the below code to achieve this. However, when i trying to invoke the method, simply a "Find Source" file browser dialog opens and the code is not run. Can anyone please help me here.
Dim VBP As New VBCodeProvider
Dim CVB As System.CodeDom.Compiler.ICodeCompiler
CVB = VBP.CreateCompiler
Dim PM As New System.CodeDom.Compiler.CompilerParameters
PM.GenerateInMemory = True
PM.GenerateExecutable = True
PM.OutputAssembly = "RunCode.dll"
PM.MainClass = "MainClass"
PM.IncludeDebugInformation = True
Dim ASM As System.Reflection.Assembly
For Each ASM In AppDomain.CurrentDomain.GetAssemblies
PM.ReferencedAssemblies.Add(ASM.Location)
Next
Dim CompileResults As System.CodeDom.Compiler.CompilerResults
CompileResults = CVB.CompileAssemblyFromSource(PM, sCode)
Dim CompileErrors As System.CodeDom.Compiler.CompilerError
For Each CompileErrors In CompileResults.Errors
RTMainScript.AppendText(vbCrLf & CompileErrors.ErrorNumber & ": " & CompileErrors.ErrorText & ", " & CompileErrors.Line)
Next
Dim objRun As New Object
Dim vArgs() As Object
objRun = CompileResults.CompiledAssembly.CreateInstance("RunCode.MainClass", False, BindingFlags.CreateInstance, Nothing, vArgs, Nothing, Nothing)
If Not objRun Is Nothing Then
Dim oMethodInfo As MethodInfo = objRun.GetType().GetMethod("Main")
Dim oRetObj As Object = oMethodInfo.Invoke(objRun, BindingFlags.Static Or BindingFlags.Instance Or BindingFlags.Public Or BindingFlags.NonPublic, Nothing, Nothing, Nothing) 'Find source dialog appears here
Else
MsgBox("Compile Error")
End If
The code you provided is incomplete. You are using this method to compile the code:
CompileResults = CVB.CompileAssemblyFromSource(PM, sCode)
But you actually never specified what sCode is. If you are getting an open file browser dialog, then I am quite sure that your sCode is the cause of it. It must have been set somewhere while calculating the variable value to open a file.
If you are trying to change a piece of code that was used to compile from a file then changing the method from CompileAssemblyFromFile() to CompileAssemblyFromSource() is not enough. You need to dig more into the code and change all related methods.
Ensure your threading model is STA.
OpenFileDialog and similar objects will not operate correctly if the threading model is set to MTA.
If you must use MTA for some other reason then you can create your own custom OpenFileDialog class; sort of sucks.

Coderush plugin not generating correct try catch end try block

We've created a little plugin to add a block of xml comment and create a try-catch to a function. (we simply add this to each and every function we write)
But with the latest devexpress update I'm having a problem with the following code.
Private Sub cpAddComment_Apply(ByVal sender As System.Object, ByVal ea As DevExpress.CodeRush.Core.ApplyContentEventArgs) Handles cpAddXMLCommentAndTryCatch.Apply
' create elementbuilder and add current code to it
Dim objMethod As New Method
objMethod = objOldMethod.Clone()
objElementBuilder.AddStatement(Nothing, objMethod)
' add try
Dim objTry As DevExpress.CodeRush.StructuralParser.Try = objElementBuilder.AddTry(objMethod)
Dim objCatch As DevExpress.CodeRush.StructuralParser.Catch = objElementBuilder.AddCatch(objMethod, "Exception", "ex")
' add exception
Dim strErrorString As String = """Error in " + objMethod.Location + """, ex"
Dim objThrow As New DevExpress.CodeRush.StructuralParser.Throw
Dim objException As New DevExpress.CodeRush.StructuralParser.TypeReferenceExpression("Exception")
Dim objExceptionString As New DevExpress.CodeRush.StructuralParser.PrimitiveExpression(strErrorString)
Dim objNewException As New DevExpress.CodeRush.StructuralParser.ObjectCreationExpression(objException)
objNewException.AddArgument(objExceptionString)
objThrow.Expression = objNewException
'objThrow.AddFooter(" ") 'This isnt working either
objElementBuilder.AddThrow(objCatch, objThrow)
' substitute code
Dim newCode As String = objElementBuilder.GenerateCode()
ea.TextDocument.Replace(objOldMethod.Range, newCode, "Update Method", True)
end sub
Instead of generating a correct Try-catch block it generates the following incorrect code:
Try
Catch ex As Exception
Throw New Exception("Error in test", ex)End Try
Strangely enough the following code seems to work(its about the same code but then for event handlers to show a messagebox instead of an exception)
If not CodeRush.Language.ActiveExtension.DotNetLanguageType = DotNetLanguageType.CSharp Then
Dim objExceptionString As New DevExpress.CodeRush.StructuralParser.PrimitiveExpression("Messagebox.Show(" + strErrorString + ")" + vbCrLf)
objElementBuilder.AddStatement(objCatch, objExceptionString)
Else
This problem exists in Vb.Net but in C# the brackets are correctly placed.
I have reproduced your issue and registered it in DevExpress Support Center. You are welcome to track its status here. Once it is fixed, you can request a build containing the fix from the Support Team at support # devexpress.com. For now, as a work-around, you can replace this line of code:
objThrow.Expression = objNewException
into this:
objThrow.Expression = New SnippetExpression(CodeRush.Language.GenerateExpressionCode(objNewException) + vbCrLf)
This will generate the try/catch block correctly in Visual Basic.