Read/Compile vb.net code dynamically from text file - vb.net

I am trying to read and compile code from a text file. I have done some of its portion but feeling difficulties when trying to add controls to the Form. Kindly guide me. I am attaching code.
Public Class Form1
Sub Execute()
' Creates object of the compiler
Dim objCodeCompiler As System.CodeDom.Compiler.ICodeCompiler = New VBCodeProvider().CreateCompiler
'References/Parameters.
Dim objCompilerParameters As New System.CodeDom.Compiler.CompilerParameters()
objCompilerParameters.ReferencedAssemblies.Add("System.dll")
objCompilerParameters.ReferencedAssemblies.Add("System.Windows.Forms.dll")
objCompilerParameters.ReferencedAssemblies.Add("Microsoft.VisualBasic.dll")
'Compiles in memory.
objCompilerParameters.GenerateInMemory = True
'Runs the source code.
'You can use resources, textbox's or even the settings, up to you! :D
'Dim strCode As String = TextBox1.Text
'Compiler Results
'Dim objCompileResults As System.CodeDom.Compiler.CompilerResults = objCodeCompiler.CompileAssemblyFromSource(objCompilerParameters, strCode)
Dim objCompileResults As System.CodeDom.Compiler.CompilerResults = objCodeCompiler.CompileAssemblyFromFile(objCompilerParameters, "H:\VB project\LE21 - CodeDom - Run code from Textbox\LE21 - CodeDom - Run code from Textbox\LE21 - CodeDom - Run code from Textbox\file.txt")
'If an Error occurs
If objCompileResults.Errors.HasErrors Then
MsgBox("Error: Line>" & objCompileResults.Errors(0).Line.ToString & ", " & objCompileResults.Errors(0).ErrorText)
Exit Sub
End If
'Creates assembly
Dim objAssembly As System.Reflection.Assembly = objCompileResults.CompiledAssembly
Dim objTheClass As Object = objAssembly.CreateInstance("MainClass")
If objTheClass Is Nothing Then
MsgBox("Can't load class...")
Exit Sub
End If
'Trys to excute
Try
objTheClass.GetType.InvokeMember("ExecuteCode",
System.Reflection.BindingFlags.InvokeMethod, Nothing, objTheClass, Nothing)
Catch ex As Exception
MsgBox("Error:" & ex.Message)
End Try
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'Runs the source code from textbox1.
Execute()
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim p As New Form2
p.Text = "hahahahah"
p.Show()
End Sub
End Class

"Type Form2 is not defined"
That's because you haven't defined it. You may be dynamically loading and compiling some file which contains code which does define it. But the compiler has no way of knowing that at compile time. Being a statically typed system, the compiler needs to know about all of the types you're using when it compiles the code.
If you're dynamically loading class definitions from a file, then you also need to dynamically invoke those class definitions. That's going to involve a lot of reflection and CodeDOM and whatnot. It's not going to be pretty, and it's definitely not going to have compile-time type checking. (And it's going to be very "stringly typed" in the sense that instead of creating an instance of Form2 you're going to be requesting from reflection to create an instance of "Form2" and hoping for the best.) So you're going to want to put in a lot of error handling for things like, for example, classes which don't exist.

Related

How to do you make a ListBox display all files in a drive?

I'm coding an Anti-Virus at the moment, so it's been very complicated to code it and design it. Anyway, the other day I ran into a problem, where my ListBox is not displaying all the files that are in the selected drive/directory.
I'll put some code and images so you get the idea.
Private Sub Button6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button6.Click
ListBox1.Items.Clear()
ListBox3.Items.Clear()
FolderBrowserDialog1.SelectedPath = Path.GetPathRoot(Environment.SystemDirectory) & "Boot\"
On Error Resume Next
For Each strDir As String In System.IO.Directory.GetDirectories(FolderBrowserDialog1.SelectedPath)
For Each strFile As String In System.IO.Directory.GetFiles(strDir)
ListBox1.Items.Add(strFile)
ListBox3.Items.Add(strFile)
Next
Next
Timer1.Start()
End Sub
However, instead of the files appearing in the ListBox (ListBox3), it just gives a black screen. Maybe I should remove the TabControl that it is surrounded by?
See how it's black? It even happens when I run it.
Hope this helps! Comment if you need more information.
You may want to simplify your events by creating subs and standardizing the code instead of embedding it directly into the button click. I have created a working example of how to load directories and files dynamically.
I would also recommend doing a isolated experiment, you can easily throw together a test project to isolate the directories in question and the layout you are trying to achieve. It could be that there are other events causing noise in your debugging.
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
load_dirs(ListBox2, "H:\")
End Sub
Sub load_files(LB As ListBox,
IO_dir As String)
Dim Files_ = IO.Directory.GetFiles(IO_dir)
With LB.Items
.Clear()
.AddRange(Files_)
End With
End Sub
Sub load_dirs(LB As ListBox,
IO_dir As String)
Dim dir_ = IO.Directory.GetDirectories(IO_dir)
With LB.Items
.Clear()
.AddRange(dir_)
End With
End Sub
Private Sub ListBox2_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox2.SelectedIndexChanged
Try
Dim lb As ListBox = sender
load_files(ListBox1, lb.SelectedItem)
Catch ex As Exception
End Try
End Sub
End Class

Why is this CInt function call *not* throwing an error?

I'm just curious, really.
There was some code that wasn't handling empty strings before converting, essentially calling
Dim StringToConvert As String = ""
Dim a As Integer = CInt(StringToConvert)
Rather then something like
Dim StringToConvert As String = ""
Dim a As Integer = CInt("0" & StringToConvert)
and so it makes sense that it would throw an error...
What I don't understand is that this wasn't throwing an error on my machine when I was debugging. But it does throw an error when compiled!
Here is what calls the CInt function and only sometimes throws an error:
Public NotInheritable Class SomeForm
Inherits Windows.Forms.Form
Private Sub TextBox_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles TextBox.LostFocus
StaticHolderClass.StaticMethod(DirectCast(sender,TextBoxBase))
End Sub
End Class
Public NotInheritable Class StaticHolderClass
Public Shared Sub StaticMethod(ByVal sender As Windows.Forms.TextBoxBase)
sender.Text = Format(CInt(sender.Text),"#,#")
End Sub
End Class
Does anyone know why this would happen?
In VB, occasionally when an error is encountered during form initialization, it doesn't get reported properly. Sometimes the error is not flagged at all, and sometimes it appears to be from a different location. For example, in the following code (on my system), an error is thrown with the button click and not the form load:
Public Class Form1
Dim k As Integer
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
k = CInt("")
End Sub
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
k = CInt("")
End Sub
End Class
It seems to depend on the environment, so "your results may vary". You can work around this sometimes by using the shown event rather than load.

TextBox1 doesn't show the listbox1 value

I'm Visual Basic beginner, yesterday i wrote a dictionary that give you the opposite of the entered word, so i designed the form to look like this
[url]http://img651.imageshack.us/img651/6115/errorbp.jpg[url]
by the way i made a two list boxes as databases so the code will compare if the textbox1.text = listbox1.text then it will command textbox2 to append the value of the listbox : textbox2.appendtext(listbox2.text) but nothing happens
my code:
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub TnsBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If TextBox1.Text = TextBox3.ToString Then
TextBox2.AppendText(ListBox2.Text)
ElseIf TextBox1.Text = TextBox4.Text Then
TextBox2.AppendText(ListBox1.ToString)
End If
End Sub
Private Sub AddBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
ListBox1.Items.Add(TextBox3.Text)
ListBox2.Items.Add(TextBox4.Text)
End Sub
End Class
the point of the code is ok cuz yesterday i finished the coding and the programs works fine but i forget to save it so i coded again and every thing above happens
this is the yesterday program
http://www.mediafire.com/?tavne7xjyth7y7v
virustotal link:
https://www.virustotal.com/file/1d39429ae1498a744e1556188b7e8914526b7e2fbb2d4904c2b4ea22fb278dc7/analysis/1346676641/
Initially you are setting the textbox text to "ListBox" without choosing anything specific so it is calling ToString() on the listbox which is why you get that.
I would change the method so that you have a Dictionary variable like so:
Public Sub Translate(input As String)
TextBox2.Text = OppositeDictionaires(input)
End Sub
Public OppositeDictionary As New Dictionary(Of String, String)
'Call as Add(TextBox3.Text, TextBox4.Text)
Public Sub Add(input As String, opposite As String)
OppositeDictionary.Add(input, opposite)
End Sub
Call add from your event and then Translate from your translate event. You should then get your output as intended, still add them to the listboxes if you want to display to the user but handle the translation in the code behind through a dictionairy object.
http://msdn.microsoft.com/en-us/library/xfhwa508.aspx

BackgroundWorker.ReportProgress exception if run in another module

My BackgroundWorker works perfectly in my main form frmMain. But when I run the ReportProgress method in another module, I get exception "This BackgroundWorker states that it doesn't report progress. Modify WorkerReportsProgress to state that it does report progress." This IS set to report progress; this works fine when run the same way in the main module.
Basically, from a module called by my BackgroundWorker, I want to show progress on my main form.
How can I fix this? The only idea I have is to move the code from the module into my main form, but this seems a backward step, which would involve extra work. Am hoping there are easier ways!
Calling code in class frmMain:
Friend WithEvents BackgroundWorker As New System.ComponentModel.BackgroundWorker
Private Sub btnTest_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnTest.Click
' Specify that we do NOT want the background operation to allow cancellation
BackgroundWorker.WorkerSupportsCancellation = False
' Specify that we want the background operation to report progress.
BackgroundWorker.WorkerReportsProgress = True
' Start running the background operation by calling the RunWorkerAsync method.
BackgroundWorker.RunWorkerAsync()
End Sub
Private Sub BackgroundWorker_DoWork(ByVal sender As Object, _
ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker.DoWork
Dim result As Boolean
result = MyTest()
End Sub
Private Sub BackgroundWorker_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker.ProgressChanged
Me.Text = e.ProgressPercentage.ToString() & "%"
sspStatus.Text = e.UserState.ToString
End Sub
Private Sub BackgroundWorker_RunWorkerCompleted(ByVal sender As Object, _
ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) _
Handles BackgroundWorker.RunWorkerCompleted
If e.Cancelled = True Then
' The background operation was cancelled
Me.Text = "Cancelled!"
ElseIf e.Error IsNot Nothing Then
' The background operation encountered an error
Me.Text = "Error: " & e.Error.Message
Else
' The background operation completed successfully
Me.text = "Done!"
End If
End Sub
Code which generates the exception in separate module Invoices:
Public Function MyTest() As Boolean
frmMain.BackgroundWorker.ReportProgress(0)
End Function
Am using VB.NET in VS 2010, with .NET 3.5.
Try to set it up as
Public Function MyTest(worker as BackgroundWorker) As Boolean
worker.ReportProgress(0)
End Function
to make sure you are talking to the right worker instance.
(And aside: avoid using classnames for instance fields).

Why do I get an InvalidOperationsException error?

Here's the deal. I tried using classes instead of the usual modules(in an attempt to try a different approach[aside from what I know that is] to OOP). So I used classes and in a simple showing and hiding of forms, I got an InvalidOperationsException error. Weirded out, I removed the OOP parts and just tried calling the other form directly on the form itself and still got the same error.
Here's the error I get:
An error occurred creating the form. See Exception.InnerException for details. The error is: The form referred to itself during construction from a default instance, which led to infinite recursion. Within the Form's constructor refer to the form using 'Me.'
Here's the code:
Private Sub btnNewSales_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNewOrder.Click
'This ought to have opened the new form via a method in the class
'order.NewOrder()
frmNewOrder.Show()
Me.Hide()
End Sub
either way, I get the same error.
Tried using modules instead. Here's the code:
Public Sub ShowForm(ByVal frmName As String)
If frmName = "Order" Then
frmOrders.Show()
ElseIf frmName = "AddOrder" Then
frmAddOrder.Show()
End If
End Sub
Now so far (in all my programming experience) this ought to work just fine, but it still returns the same error..
Update!
Tried removing all OOP aspects in form calling and left a module to simply show or hide some controls in one form.
Here's the code in the module:
Public Sub DesignSelect(ByVal design As String)
If design = "Basic" Then
frmAddOrder.lblD3.Hide()
frmAddOrder.cmbD3Color.Hide()
frmAddOrder.cmbD3Type.Hide()
frmAddOrder.lblD4.Hide()
frmAddOrder.cmbD4Color.Hide()
frmAddOrder.cmbD4Type.Hide()
Else
End If
End Sub
Now correct me if I'm wrong, but I do believe nothing is wrong with it right?
Now here's the code of the form where the module was used:
Dim selectedDesign As String = ""
Private Sub frmSalesTrans_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub frmSalesTrans_FormClosing(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Me.FormClosing
'ShowForm("Order")
frmOrders.Show()
End Sub
Private Sub rdbBasic_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rdbBasic.CheckedChanged
selectedDesign = "Basic"
DesignSelect(selectedDesign)
End Sub
And here's the code of the form that calls the form above:
Private Sub frmSales_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub btnNewSales_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNewOrder.Click
Me.Hide()
frmAddOrder.Show()
End Sub
Now it just boggles me why I get this error.. If I removed all OOP (including the subprocedure DesignSelect), it works fine. Kindly enlighten me on this...