Issue with "Get" message with gmail api v1 (Net) - vb.net

Im trying to get info of a gmail message in a datagridview but only returns the datagridview empty (even when I erase the "return nothing" line) but when I try in apis-explorer I get the 200 ok response. What am I doing wrong?
The code Im using is from the google developers documentation:
Imports Google.Apis.Auth.OAuth2
Imports Google.Apis.Services
Imports Google.Apis.Tasks.v1
Imports Google.Apis.Tasks.v1.Data.Tasks
Imports Google.Apis.Tasks.v1.Data
Imports System.Collections.Generic
Imports Google.Apis.Util.Store
Imports System.Threading
Imports System
Imports Google.Apis.Gmail.v1
Imports Google.Apis.Gmail.v1.Data
Public Class Form1
Dim Secrets = New ClientSecrets()
Dim scope = New List(Of String)
Dim initializer = New BaseClientService.Initializer
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Secrets.ClientId = "CLIENT_ID"
Secrets.ClientSecret = "CLIENT_SECRET"
End Sub
Public Shared Function GetMessage(service As GmailService, userId As [String], messageId As [String]) As Message
Try
Return service.Users.Messages.Get(userId, messageId).Execute()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
'Return Nothing
End Function
Private Sub Button14_Click(sender As Object, e As EventArgs) Handles Button14.Click
Dim userId As String = "GMAIL ACCOUNT"
Dim messageId As String = "MESSAGE ID"
Try
scope.Add(GmailService.Scope.MailGoogleCom)
Dim credential = GoogleWebAuthorizationBroker.AuthorizeAsync(Secrets, scope, "XXXXXXXXXXXX#developer.gserviceaccount.google.com", CancellationToken.None).Result()
initializer.HttpClientInitializer = credential
initializer.ApplicationName = "APP NAME"
Dim service = New GmailService(initializer)
Me.DataGridView1.DataSource = GetMessage(service, userId, messageId)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class

Thanks Eric but I already solved making some changes. I hope this helps other people because the google developers documentation its not too clear
Imports Google.Apis.Auth.OAuth2
Imports Google.Apis.Services
Imports System.Collections.Generic
Imports Google.Apis.Util.Store
Imports System.Threading
Imports System
Imports Google.Apis.Gmail.v1
Imports Google.Apis.Gmail.v1.Data
Public Class Form1
Dim Secrets = New ClientSecrets()
Dim scope = New List(Of String)
Dim initializer = New BaseClientService.Initializer
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Secrets.ClientId = "CLIENT ID"
Secrets.ClientSecret = "CLIENT SECRET"
End Sub
Public Shared Function GetMessage(service As GmailService, userId As [String], messageId As [String]) As Message
Try
Return service.Users.Messages.Get(userId, messageId).Execute
Catch ex As Exception
MsgBox(ex.ToString)
End Try
Return Nothing
End Function
Private Sub Button14_Click(sender As Object, e As EventArgs) Handles Button14.Click
Try
scope.Add(GmailService.Scope.MailGoogleCom)
Dim credential = GoogleWebAuthorizationBroker.AuthorizeAsync(Secrets, scope, "XXXXXXXXXXXXX#developer.gserviceaccount.google.com", CancellationToken.None).Result()
initializer.HttpClientInitializer = credential
initializer.ApplicationName = "APP NAME"
Dim service = New GmailService(initializer)
Dim userId As String = "EMAIL"
Dim messageId As String = "MESSAGE ID"
Me.DataGridView1.DataSource = GetMessage(service, userId, messageId).Payload.Headers
TextBox1.Text = (GetMessage(service, userId, messageId).Snippet)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class

Related

VB.NET - Data not sending until the stream is closed

I'm trying to make a program that sends the client's screen to the server on load but the data doesn't send until the datastream is closed in the client program. I know flush is supposed to send the data but there is no difference when there is and when there isn't flush in the program.
Here is the main server code:
Imports System.IO
Imports System.Drawing.Imaging
Public Class Form1
Dim encodeType As ImageFormat = ImageFormat.Bmp
Dim decodingString As String = String.Empty
Dim encodingTypeString = "data:image/bmp;base64"
Public Function base64c(ByVal base64code As String) As Image
Dim imageBytes As Byte() = Convert.FromBase64String(base64code)
Dim ms As New MemoryStream(imageBytes, 0, imageBytes.Length)
Return Image.FromStream(ms, True)
End Function
Private Server As TCPControl
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Server = New TCPControl
AddHandler Server.MessageReceived, AddressOf OnLineReceived
End Sub
Private Delegate Sub UpdateDesktopDelegate(Img As PictureBox, base64 As String)
' update image
Private Sub OnLineReceived(sender As TCPControl, Data As String)
Desktop.Image = base64c(Data)
End Sub
Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
Server.IsListening = False
End Sub
End Class
The TCPControl server code:
Imports System.IO
Imports System.Net
Imports System.Net.Sockets
Imports System.Threading
Public Class TCPControl
Public Event MessageReceived(sender As TCPControl, Data As String)
'Config
Public ServerIp As IPAddress = IPAddress.Parse("192.168.254.14")
Public ServerPort As Integer = 64555
Public Server As TcpListener
Private CommThread As Thread
Public IsListening As Boolean = True
'Clients
Private Client As TcpClient
Private ClientData As StreamReader
Public Sub New()
Server = New TcpListener(ServerIp, ServerPort)
Server.Start()
CommThread = New Thread(New ThreadStart(AddressOf Listening))
CommThread.Start()
End Sub
Private Sub Listening()
' create listener loop
Do Until IsListening = False
' accept incoming connections
If Server.Pending = True Then
Client = Server.AcceptTcpClient
ClientData = New StreamReader(Client.GetStream)
End If
' raise event for incoming messages
Try
RaiseEvent MessageReceived(Me, ClientData.ReadLine)
Catch ex As Exception
End Try
Thread.Sleep(300)
Loop
End Sub
End Class
The main client code:
Imports System.IO
Imports System.Threading
Imports System.Drawing.Imaging
Public Class Form1
Private Client As TCPControl
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Client = New TCPControl("192.168.254.14", 64555)
Do Until False
If Client.Client.Connected = True Then
Dim bounds As Rectangle
Dim screenshot As System.Drawing.Bitmap
Dim newimg As System.Drawing.Bitmap
Dim graph As Graphics
bounds = Screen.PrimaryScreen.Bounds
bounds.Size = New Size(1920, 1080)
screenshot = New System.Drawing.Bitmap(2600, 1330, System.Drawing.Imaging.PixelFormat.Format32bppArgb)
graph = Graphics.FromImage(screenshot)
graph.CopyFromScreen(bounds.X, bounds.Y, 0, 0, bounds.Size, CopyPixelOperation.SourceCopy)
Using ms As New MemoryStream()
newimg = New Bitmap(screenshot, New Size(960, 540))
newimg.Save(ms, ImageFormat.Bmp)
Dim imageBytes As Byte() = ms.ToArray()
Client.Send(Convert.ToBase64String(imageBytes))
End Using
Thread.Sleep(333)
End If
Loop
End Sub
Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
If Client.Client.Connected = True Then
Client.DataStream.Close()
Client.Client.Close()
End If
End Sub
End Class
And the client TCPControl code:
Imports System.Net
Imports System.Net.Sockets
Imports System.IO
Public Class TCPControl
Public Client As TcpClient
Public DataStream As StreamWriter
Public Sub New(Host As String, Port As Integer)
' client
Client = New TcpClient(Host, Port)
DataStream = New StreamWriter(Client.GetStream)
End Sub
Public Sub Send(Data)
DataStream.Write(Data)
DataStream.Flush()
End Sub
End Class
I have been trying to solve this problem for hours now and posting on this website was my last resort. If any code is unorganized or is not as it should be then it is because I haven't focused on checking my code yet.

Binding an observable collection to a printer queue

I am trying to monitor a print queue using a Observable Collection however when an item is added to the printer queue it does not updated. am I missing something. Here is my code so far.
Imports System.Printing
Imports System.Text
Imports System.IO
Imports System.Collections
Imports System.Management
Imports System.Drawing.Printing
Imports System.Collections.ObjectModel
Imports System.Collections.Specialized
Public Class Form1
Dim localPrintServer2 As LocalPrintServer
Dim defaultPrintQueue2 As PrintQueue
Dim listSentToPrinter As New List(Of String)()
Dim listPrinterQueue As New List(Of String)()
Dim listJobsInQueue As New List(Of String)()
' Private m_queueObList As New ObservableCollection(Of String)
Public queueObList As New ObservableCollection(Of String)
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
AddHandler queueObList.CollectionChanged, AddressOf Me.OnCollectionChanged
End Sub
Private Sub OnCollectionChanged(sender As Object, e As NotifyCollectionChangedEventArgs)
Try
Dim obsSender As ObservableCollection(Of String) = TryCast(sender, ObservableCollection(Of String))
Dim editedOrRemovedItems As New List(Of String)()
getPrintQueue()
If e.Action = NotifyCollectionChangedAction.Add Then
MsgBox("Item Added")
'search listSentToPrinter
End If
If e.Action = NotifyCollectionChangedAction.Remove Then
MsgBox("Item Removed")
End If
'Label1.Text = queueObList.Count
Dim action As NotifyCollectionChangedAction = e.Action
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub getPrintQueue()
Try
localPrintServer2 = New LocalPrintServer()
defaultPrintQueue2 = LocalPrintServer.GetDefaultPrintQueue()
Timer1.Enabled = True
Timer1.Interval = 50
Dim jobs As PrintJobInfoCollection = defaultPrintQueue2.GetPrintJobInfoCollection
For Each job As PrintSystemJobInfo In jobs
'listPrinterQueue.Add(job.Name)
queueObList.Add(job.Name)
Label1.Text = queueObList.Count
'lstPrinterQueue.Items.Add(job.Name & " " & job.JobStatus)
Next
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub Iletarerate()
ListBox1.Items.Clear()
For Each item As String In queueObList
ListBox1.Items.Add(item)
Next
End Sub
Public Sub FindJobInQueue(ByVal item As String)
If listJobsInQueue.Contains(item) Then
Else
If (listPrinterQueue.Count >= 1) Then
If listPrinterQueue.Contains(item) Then
lstJobInQueue.Items.Add("Found " & item)
listJobsInQueue.Add(item)
'Update stutus if successfully updated
listSentToPrinter.Remove(item)
End If
Else
' list is empty
End If
End If
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
queueObList.RemoveAt(0)
Iletarerate()
End Sub
End Class
The code works to add everything to the observable collection which is in the queue. The buttons work to add and remove items. The actual print queue does not update the collection

Close form from second form

My first form is login form, when user correctly log in i am hiding login form and showing up second form. Now instead of hiding login form i want to close it from second form. I thought i will be able to do it but somehow i got troubles with it.
So far i did like this below.
I made interface which my FrmLogin implements:
Public Class FrmLogin
Implements ICloseLogin
Interface:
Public Interface ICloseLogin
Sub Close()
End Interface
FrmLogin implementing interface:
Private Sub ICloseLogin_Close() Implements ICloseLogin.Close
Me.Close()
End Sub
Now i am passing FrmLogin (Me) to second form constructor:
Private Sub ShowMainForm()
Dim FrmMain As New FrmMainMDI(Me)
FrmMain.IsMdiContainer = True
FrmMain.StartPosition = FormStartPosition.CenterScreen
FrmMain.Show()
'Me.Hide() 'not anymore
End Sub
Second form:
Public Class FrmMainMDI
Private closeloginfform As ICloseLogin
Sub New(frmlogin As ICloseLogin)
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
closeloginfform = frmlogin
End Sub
Private Sub FrmMainMDI_Shown(sender As Object, e As EventArgs) Handles MyBase.Shown
closeloginfform.Close()
End Sub
and when i debug and when it comes to line: closeloginfform.Close() i suppose to see only FrmLogin to be closed, but all is closing somehow. Why?
For further discussion:
Imports DataAccessLayer
Imports FormsUtils
Imports BusinessLayer
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Reflection
Imports System.IO
Imports Microsoft.WindowsAPICodePack.Dialogs
Imports Probix
Public Class FrmLogin
Private Property Form As New FormUtils
Private Property DB As New Procs
Private Property _login As String
Private Property _password As String
Private Sub btnLogin_Click(sender As System.Object, e As System.EventArgs) Handles btnLogin.Click
CheckAccess()
End Sub
Private Sub btnClose_Click(sender As System.Object, e As System.EventArgs) Handles btnClose.Click
Me.Close()
End Sub
Private Sub FrmLogin_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Try
DB.OpenConn()
If DB.conn.State = ConnectionState.Open Then
Call Form.InitCombo(CboLogin, "SELECT * from tbLogin", DB.conn, "Login", "Login")
Call Form.InitCombo(CboLanguage, "SELECT * from tbLanguage where Active = 1", DB.conn, "Language", "Id")
Lang.name = DirectCast([Enum].Parse(GetType(Lang.LangShortcut), CboLanguage.GetItemText(CboLanguage.SelectedItem)), Lang.LangShortcut)
Else
Logger.LogIt(Modules.FrmLogin.ToString & ": " & Methods.FrmLogin_Load.ToString, WriteMsg.Write(IssueCode.SqlServerConnectionError_pl), Application.StartupPath & "\log.txt", False)
Application.Exit()
End If
Catch ex As Exception
Logger.LogIt(ex.tostring)
Application.Exit()
Finally
DB.CloseConn()
End Try
End Sub
Private Sub CheckAccess()
Try
_login = CboLogin.SelectedValue
_password = txtPassword.Text
If Not String.IsNullOrEmpty(txtPassword.Text) And Form.WybranoCombo(CboLogin, "Zaznacz login") Then
Dim strcon = New AppSettingsReader().GetValue("ConnectionString", GetType(System.String)).ToString()
Using con As New SqlConnection(strcon)
Using cmd As New SqlCommand("Select COUNT(*) FROM tbLogin WHERE Login = #Login And Password = #Password", con)
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("#Login", _login)
cmd.Parameters.AddWithValue("#Password", _password)
con.Open()
Dim o As Integer = cmd.ExecuteScalar()
'--CREDENTIALS OK
If o > 0 Then
CboLogin.Hide()
txtPassword.Hide()
btnLogin.Hide()
Label1.Hide()
Label2.Hide()
Try
Catch ex As Exception
MsgBox(ex.ToString)
End
End Try
'--CREDENTIALS NOT OK !!
Else
MsgBox("Wrong credentials")
End If
End Using
End Using
Else
MsgBox("Write some password !!")
End If
Catch ex As Exception
Logger.LogIt(Modules.FrmLogin.ToString & ":" & Methods.FrmLogin_Load.ToString, WriteMsg.Write(IssueCode.Unknown_pl) & " ------> EX-MESSAGE: " & ex.ToString, Application.StartupPath & " \log.txt", False)
Return
End Try
End Sub
Public Sub taskDialog_Opened(sender As Object, e As EventArgs)
Dim taskDialog As TaskDialog = TryCast(sender, TaskDialog)
taskDialog.Icon = taskDialog.Icon
If Not taskDialog.FooterIcon = TaskDialogStandardIcon.None Then
taskDialog.FooterIcon = taskDialog.FooterIcon
End If
taskDialog.InstructionText = taskDialog.InstructionText
End Sub
End Class
Module Program:
Module Program
Public Sub main()
Application.EnableVisualStyles()
Dim result As DialogResult
Using frmL As New FrmLogin
result = frmL.ShowDialog
End Using
If result = DialogResult.OK Then
Dim FrmMainMDI As New FrmMainMDI()
Application.Run(FrmMain)
End If
End Sub
End Module
Further discussion 2
Solved???: I've added line within CheckAccess() sub, this line:
Me.DialogResult = DialogResult.OK
so this peace of code has been changed only:
...
'--CREDENTIALS OK
If o > 0 Then
CboLogin.Hide()
txtPassword.Hide()
btnLogin.Hide()
Label1.Hide()
Label2.Hide()
Try
'*************************************
Me.DialogResult = DialogResult.OK '<=========================================
'*************************************
Catch ex As Exception
MsgBox(ex.ToString)
End
End Try
'--CREDENTIALS NOT OK !!
Else
MsgBox("Wrong credentials")
End If
...
A less involved way to do this is to start your app from Sub Main and only start the app if the LogIn is correct. For this:
Add a module to your App, and name it Program. Add a Public Sub Main to it
Go to Project Properties and Uncheck Enable Application Framework
Now, for the Startup Object, select "Sub Main"
You can actually name the module anything, "Program" is descriptive and the convention used in C#. Then the Sub Main code:
Public Sub Main()
Application.EnableVisualStyles()
Dim result As DialogResult
Using frmL As New frmLogin
result = frmL.ShowDialog
End Using
If result = DialogResult.OK Then
frmMain = New MainFrm()
Application.Run(frmMain)
End If
End Sub
Now, your two forms don't even have to know about each other. The MainForm will not even exist if/when the login fails. Whatever overhead there is related to starting/Loading the MainForm is also delayed until (and unless) the log in passes.
Your login button would be something like this (depending on how many failed attempts are allowed):
Private Sub btnLogIn_Click(sender As Object, e As EventArgs) Handles btnLogIn.Click
If IsValidUser(tbName.Text, tbPW.Text) Then
DialogResult = Windows.Forms.DialogResult.OK
Else
If tries >= 3 Then
DialogResult = Windows.Forms.DialogResult.Cancel
Else
tries += 1
Exit Sub
End If
End If
Me.Hide()
End Sub

Visual basic 2010 vbulletin Loader

I am trying to create a vbulletin Loader for my site.
The main question is how to create a loader for vbulletin
The Loader works so it has permissions from vbulletin; if a user is a V.I.P., then he/she has access to inject a V.I.P .dll. A regular user can't inject that .dll, only limited to some not all and they cannot download the .dll. I am currently working on the login and its not working, nor that secure.
Module1.vb code;
Imports System.Security.Cryptography
Imports System.Text
Imports System.Net
Imports System
Imports System.IO
Module Module1
Public Function Login(ByVal Username As String, ByVal Password As String)
Password = MD5(Password)
Dim valid As Boolean = False
Dim data As String = "vb_login_username=" & Username & "&vb_login_password=&s=&do=login&vb_login_md5password=" & Password & "&vb_login_md5password_utf=" & Password
Try
Dim request As HttpWebRequest = WebRequest.Create("http://www.mywebsite.com/login.php?do=login")
request.Method = WebRequestMethods.Http.Post
request.ContentType = "application/x-www-form-urlencoded"
request.UserAgent = "-- vBulletin Vaidation --"
request.ContentLength = data.Length
Dim rStream As New StreamWriter(request.GetRequestStream)
rStream.Write(data)
rStream.Flush()
rStream.Close()
Dim response As HttpWebResponse = request.GetResponse
Dim resReader As New StreamReader(response.GetResponseStream)
Dim str As String = resReader.ReadToEnd
If str.Contains("Successful Login!") Then
valid = True
Else
valid = False
End If
response.Close()
Catch ex As Exception
MessageBox.Show(ex.Message, "Error Failed to connect to www.mywebsite.com", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
Return valid
End Function
Public Function MD5(ByVal number As String) As String
Dim ASCIIenc As New ASCIIEncoding
Dim strReturn As String = String.Empty
Dim ByteSourceText() As Byte = ASCIIenc.GetBytes(number)
Dim Md5Hash As New MD5CryptoServiceProvider
Dim ByteHash() As Byte = Md5Hash.ComputeHash(ByteSourceText)
For Each b As Byte In ByteHash
strReturn &= b.ToString("x2")
Next
Return strReturn
End Function
End Module
Form1 code;
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
MsgBox("Copyright Notice: Copyright website 2013 - 2014 All Rights Reserved. - Click 'OK' to lunch Loader.")
End Sub
Private Sub CheckBox1_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles CheckBox1.CheckedChanged
If CheckBox1.Checked Then
My.Settings.mystring.Add(ComboBox1.Text)
ComboBox1.Items.Add(ComboBox1.Text)
My.Settings.Save()
End If
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
If Login(ComboBox1.Text, TextBox1.Text) Then
MsgBox("Successfully Logged In!")
Me.Show()
Me.Close()
Else
MsgBox("Unknown Username and Password. Try Again.")
End If
End Sub

compiling assembly from the other just compiled assembly

I need to compile assembly in memory, that can compile another one. There is a form with one button. Here is a code of the form
Imports System
Imports System.Threading
Imports System.CodeDom
Imports System.CodeDom.Compiler
Imports System.Collections
Imports System.ComponentModel
Imports System.Diagnostics
Imports System.Drawing
Imports System.IO
Imports System.Windows.Forms
Imports Microsoft.VisualBasic
Public Class testtwo
Shared str_tb As String
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Call openkubik()
End Sub
Private Sub openkubik()
Dim th As Thread = New Thread(AddressOf sborkakub)
th.Start()
End Sub
Private Sub sborkakub()
Dim evi As System.Security.Policy.Evidence = AppDomain.CurrentDomain.Evidence
Dim assemblyDomain As AppDomain
Dim assemblyDomainSetup As AppDomainSetup = New AppDomainSetup
assemblyDomainSetup.ApplicationBase = System.Environment.CurrentDirectory
assemblyDomainSetup.DisallowBindingRedirects = False
assemblyDomainSetup.DisallowCodeDownload = True
assemblyDomainSetup.ConfigurationFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile
assemblyDomainSetup.LoaderOptimization = LoaderOptimization.MultiDomainHost
assemblyDomain = AppDomain.CreateDomain("AssemblyDomain", evi, assemblyDomainSetup)
assemblyDomain.DoCallBack(AddressOf assamblykub)
Call assamblykub()
End Sub
Private Shared Sub assamblykub()
Call createtext()
Dim objCodeCompiler As System.CodeDom.Compiler.CodeDomProvider = System.CodeDom.Compiler.CodeDomProvider.CreateProvider("VB")
Dim objCompilerParameters As New System.CodeDom.Compiler.CompilerParameters()
For Each asm In AppDomain.CurrentDomain.GetAssemblies()
objCompilerParameters.ReferencedAssemblies.Add(asm.Location)
Next
objCompilerParameters.CompilerOptions = "/target:winexe"
objCompilerParameters.GenerateExecutable = True
objCompilerParameters.GenerateInMemory = True
objCompilerParameters.IncludeDebugInformation = False
Dim objCompileResults As System.CodeDom.Compiler.CompilerResults = objCodeCompiler.CompileAssemblyFromSource(objCompilerParameters, str_tb)
If objCompileResults.Errors.HasErrors Then
MessageBox.Show(String.Format("Error: Line>{0}, {1} # {2}", objCompileResults.Errors(0).Line, objCompileResults.Errors(0).ErrorText, objCompileResults.Errors(0).ErrorNumber))
Return
End If
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
Try
objTheClass.GetType.InvokeMember("Main", System.Reflection.BindingFlags.InvokeMethod, _
Nothing, objTheClass, Nothing)
Catch ex As Exception
MsgBox("Error:" & ex.Message)
End Try
End Sub
Private Shared Sub createtext()
Dim tempfile As New IO.FileStream(Application.StartupPath & "/temp_open.txt", IO.FileMode.Open, IO.FileAccess.Read)
Dim tempfilesr As New IO.StreamReader(tempfile, System.Text.Encoding.GetEncoding(1251))
str_tb = tempfilesr.ReadToEnd
tempfilesr.Close()
tempfile.Close()
tempfile = Nothing
tempfilesr = Nothing
End Sub
End Class
And the code of "temp_open.txt" file
Imports System
Imports System.Diagnostics
Imports System.Windows.Forms
Imports System.Windows
Imports Microsoft.VisualBasic
Imports System.Threading
Imports System.IO
Public Class MainClass
Inherits MarshalByRefObject
Public Shared Sub Main()
Dim tf As New testtwo
application.run(tf)
End Sub
End Class
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class testtwo
Inherits System.Windows.Forms.Form
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
Try
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
Finally
MyBase.Dispose(disposing)
End Try
End Sub
Private components As System.ComponentModel.IContainer
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
Me.Button1 = New System.Windows.Forms.Button
Me.SuspendLayout()
Me.Button1.Location = New System.Drawing.Point(114, 40)
Me.Button1.Name = "Button1"
Me.Button1.Size = New System.Drawing.Size(231, 39)
Me.Button1.TabIndex = 0
Me.Button1.Text = "Button1"
Me.Button1.UseVisualStyleBackColor = True
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(465, 133)
Me.Controls.Add(Me.Button1)
Me.Name = "test"
Me.Text = "test"
Me.ResumeLayout(False)
End Sub
Friend WithEvents Button1 As System.Windows.Forms.Button
End Class
Public Class testtwo
Shared str_tb As String
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Call openkubik()
End Sub
Private Sub openkubik()
Dim th As Thread = New Thread(AddressOf sborkakub)
th.Start()
End Sub
Private Sub sborkakub()
Dim evi As System.Security.Policy.Evidence = AppDomain.CurrentDomain.Evidence
Dim assemblyDomain As AppDomain
Dim assemblyDomainSetup As AppDomainSetup = New AppDomainSetup
assemblyDomainSetup.ApplicationBase = System.Environment.CurrentDirectory
assemblyDomainSetup.DisallowBindingRedirects = False
assemblyDomainSetup.DisallowCodeDownload = True
assemblyDomainSetup.ConfigurationFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile
assemblyDomainSetup.LoaderOptimization = LoaderOptimization.MultiDomainHost
assemblyDomain = AppDomain.CreateDomain("AssemblyDomain", evi, assemblyDomainSetup)
assemblyDomain.DoCallBack(AddressOf assamblykub)
End Sub
Private Shared Sub assamblykub()
Call createtext()
Dim objCodeCompiler As System.CodeDom.Compiler.CodeDomProvider = System.CodeDom.Compiler.CodeDomProvider.CreateProvider("VB")
Dim objCompilerParameters As New System.CodeDom.Compiler.CompilerParameters()
dim asm as System.Reflection.Assembly
For Each asm In AppDomain.CurrentDomain.GetAssemblies()
objCompilerParameters.ReferencedAssemblies.Add(asm.Location)
Next
'objCompilerParameters.OutputAssembly = "res1"
objCompilerParameters.CompilerOptions = "/target:winexe"
objCompilerParameters.GenerateExecutable = True
objCompilerParameters.GenerateInMemory = True
objCompilerParameters.IncludeDebugInformation = False
Dim objCompileResults As System.CodeDom.Compiler.CompilerResults = objCodeCompiler.CompileAssemblyFromSource(objCompilerParameters, str_tb)
If objCompileResults.Errors.HasErrors Then
MessageBox.Show(String.Format("Error: Line>{0}, {1} # {2}", objCompileResults.Errors(0).Line, objCompileResults.Errors(0).ErrorText, objCompileResults.Errors(0).ErrorNumber))
Return
End If
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
Try
objTheClass.GetType.InvokeMember("Main", System.Reflection.BindingFlags.InvokeMethod, _
Nothing, objTheClass, Nothing)
Catch ex As Exception
MsgBox("Error:" & ex.Message)
End Try
End Sub
Private Shared Sub createtext()
Dim tempfile As New IO.FileStream(Application.StartupPath & "/temp_open.txt", IO.FileMode.Open, IO.FileAccess.Read)
Dim tempfilesr As New IO.StreamReader(tempfile, System.Text.Encoding.GetEncoding(1251))
str_tb = tempfilesr.ReadToEnd
tempfilesr.Close()
tempfile.Close()
tempfile = Nothing
tempfilesr = Nothing
End Sub
End Class
When I click Button1 in first form -> appears second form. but when I click Button 1 in the second form I have an FileNotFound Exception. What am I doing wrong?
There is an interesting moment. This example with some changes work in C#(http://stackoverflow.com/questions/5729403/compilling-assembly-from-the-other-just-compilled-assembly) Maybe There are people who knows vb and c# and helps me to understand differences between two examples?
Did you tried to replace assemblyDomain.DoCallBack(AddressOf assamblykub) with simple call of assamblykub function ?