Visual Studio Test vs Form application - vb.net

This is Visual Studio 2017 V15.5.2, and none of the proposed fixes apply.
I have a simple test which fails to execute with an exception on the "Dim comp" line.
System.BadImageFormatException: 'Could not load file or assembly 'System.IO.FileSystem, Version=4.0.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. Reference assemblies should not be loaded for execution. They can only be loaded in the Reflection-only loader context. (Exception from HRESULT: 0x80131058)'
Test code below but the almost identical code when copied to a Windows Forms Application works perfectly.
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Xunit
Public Class ExpressionTests
<Fact>
Public Sub SystemConvert()
Dim tree As SyntaxTree = VisualBasicSyntaxTree.ParseText(
"Imports System
Imports System.Collections.Generic
Imports System.Text
Class TestClass
Private Sub TestMethod()
Dim x = ""Hello, World!""
End Sub
End Class")
Dim comp As Compilation = VisualBasicCompilation.Create("HelloWorld").
AddReferences(MetadataReference.CreateFromFile(GetType(Object).Assembly.Location),
MetadataReference.CreateFromFile(GetType(ExpressionTests).Assembly.Location)).
AddSyntaxTrees(tree)
Dim model As SemanticModel = comp.GetSemanticModel(tree)
End Sub
End Class
Form Code below
Public Class Form1
Dim tree As SyntaxTree = VisualBasicSyntaxTree.ParseText("Imports System
Imports System.Collections.Generic
Imports System.Text
Class TestClass
Private Sub TestMethod()
Dim x = ""Hello, World!""
End Sub
End Class")
Dim comp As Compilation = VisualBasicCompilation.Create("HelloWorld").
AddReferences(MetadataReference.CreateFromFile(GetType(Object).Assembly.Location),
MetadataReference.CreateFromFile(GetType(Form1).Assembly.Location)).
AddSyntaxTrees(tree)
Dim model As SemanticModel = comp.GetSemanticModel(tree)
End Class

With some help from Suni and one additional step I have a solution. Step 1 change target framework of Test Project (I changed from 4.7.1 to 4.6.2 and then back to 4.7.1). STEP 2!!! in the NuGet Command Windows type Update-Package -reinstall. When that completes everything works.

Related

How to use an ApplicationContext as the startup object in visual studio (without application framework)?

I have created a "Empty Project(.NET Framework) Visual Basic"
I then added an empty Class object
Next I added the reference to System.Windows.Forms
And put the following code in the Class to make it an ApplicationContext
Imports System.Windows.forms
Public Class Class1
Inherits ApplicationContext
End Class
Lastly I tried setting the Startup Object to my Class1
However that is not an option ?
I tried adding a Sub Main to my Class1
but this had no effect
Imports System.Windows.forms
Public Class Class1
Inherits ApplicationContext
Sub main()
End Sub
End Class
At this point, hitting start fails with this error
Error BC30737 No accessible 'Main' method with an appropriate signature was found in 'Project4'.
At this point I could add a module with the following code
and that would compile without errors and run
Module Module1
Sub main()
End Sub
End Module
But that runs for an instant and terminates
In another similar program I have made, I know I could put the following code in a module instead
Module Module1
Public myClass1 As Class1
Sub main()
myClass1 = New Class1
Application.Run(myClass1)
End Sub
End Module
And that would run until I called Application.Exit()
However in this specific case, the Application Framework is disabled so this solution does not work.
So another solution I have found is to use Sleep(50) in a while loop
Imports System.Threading
Module Module1
Public myClass1 As Class1
Sub main()
While True : Thread.Sleep(50) : End While
End Sub
End Module
While I cannot find anything explicitly wrong with this, it strikes me as very inelegant.
It doesn't consume noticeable cpu time or memory
I just wonder if there isn't an equivalent way to do that using just ApplicationContext and dispose of the module entirely ?
If you have any suggestion I would love to hear them at this point.
I wrote this hoping to find a solution as I write the question but I am stuck at this point.
Where does the code go after Application.Run(myClass1)
It's probably looping something inoffensive while waiting for something to happen but what ?
thanks
Here is how to make the barest bone (console or non-console) application using the ApplicationContext Class.
In Visual Studio create a "Empty Project(.NET Framework) Visual Basic"
then add an empty class
Add the following reference by right-clicking on Reference in the Solution Explorer
System.Windows.Forms
Now paste the following code in your class
Imports System.Windows.Forms
Public Class Class1
Inherits ApplicationContext
Shared Sub Main()
Dim myClass1 As Class1
myClass1 = New Class1
System.Windows.Forms.Application.Run(myClass1)
End Sub
End Class
Now hit start and you've got a perfectly working useless application that does nothing with least amount of stuff that I could manage.
If you are here, I suspect that you also would like to manually compile this project from anywhere without having visual studio installed.
Very easy ! In your project folder, create a text file and rename it compile.bat
Paste this code in compile.bat
path=%path%;c:\windows\microsoft.net\framework\v4.0.30319
VBC /OUT:bin\Debug\app.exe /imports:System.Windows.Forms /T:winexe *.vb
pause
BONUS ROUND
This app does nothing, how do you know the events even work ?
Let's add, a tray icon, a resource file to add the tray icon and some events
First add a new reference to system.drawing
Go to project properties
Create a new resource file
Add some random *.ico file
Now replace the following code in the class
Imports System.Windows.Forms
Public Class Class1
Inherits ApplicationContext
Shared Sub Main()
Dim myClass1 As Class1
myClass1 = New Class1
System.Windows.Forms.Application.Run(myClass1)
End Sub
Private WithEvents Tray As NotifyIcon
Public Sub New()
Tray = New NotifyIcon
Tray.Icon = My.Resources.appico
Tray.Text = "Formless tray application"
Tray.Visible = True
End Sub
Private Sub AppContext_ThreadExit(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles Me.ThreadExit
'Guarantees that the icon will not linger.
Tray.Visible = False
End Sub
Private Sub Tray_Click(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles Tray.Click
Console.WriteLine("Tray_Click")
End Sub
Private Sub Tray_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles Tray.DoubleClick
Console.WriteLine("Tray_DoubleClick")
System.Windows.Forms.Application.Exit()
End Sub
End Class
And now, to compile this manually
First, find resgen.exe somewhere on your harddrive
and copy it in your "My Project" folder, you can probably download it from somewhere
Make sure you've got version 4 or above of resgen though
And overwrite the compile.bat with this new code
path=%path%;c:\windows\microsoft.net\framework\v4.0.30319
cd "My Project"
resgen /usesourcepath "Resources.resx" "..\bin\debug\Resources.resources"
cd ..
VBC /OUT:bin\Debug\app.exe /resource:"bin\debug\Resources.resources" /imports:System.Drawing,System.Windows.Forms /T:winexe *.vb "My Project\*.vb"
pause
Unfortunately, this last compile.bat doesn't work for me, it might work for you.
Mine compiles just fine, but the app crashes on start.
This worked in another project where I made the Resource files by hand but something is wrong with
I tried adding the root namespace to the build with /rootnamespace:Project5 but this had no effect
Still good enough for now, this last bit will be edited if a fix is ever found

Extracting Zip File in Visual Basic .NET

I am working on a Visual Basic Project and i am getting stuck on something super simple. Unzipping a file.
I have the following imports
`Imports System.Net
Imports System
Imports System.IO
Imports System.IO.Compression`
My References are as follows
System
System.Core
System.Data
System.Data.DataSetExtensions
System.Deployment
System.Drawing
System.IO.Compression
System.IO.Compression.FileSystem
System.Net.Http
System.Windows.Forms
System.Xml
System.Xml.Linq
So what my code should be doing is checking if a software is installed,
if it is not it will download a zip file with the installed.
once the zip is downloaded it should extract it and run the setup.
Everything is working except this code block right here:
Private Sub client_OMSADownloadCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.AsyncCompletedEventArgs)
MessageBox.Show("Download Complete")
Try
ZipFile.ExtractToDirectory("C:\end.zip", "C:\end")
Catch ex As Exception
MsgBox("Can't Extract file" & vbCrLf & ex.Message)
End Try
End Sub
Public NotInheritable Class ZipFile
Public Shared Sub ExtractToDirectory(
sourceArchiveFileName As String,
destinationDirectoryName As String
)
End Sub
End Class
I get no exceptions, it just doesn't unzip, it basically skips right over the block.
Please help!
According your code, you have inherit the method ExtractToDirectory of ZipFile class that do nothing.
Public NotInheritable Class ZipFile
Public Shared Sub ExtractToDirectory(sourceArchiveFileName As String,
destinationDirectoryName As String)
End Sub
End Class
To solve this issue, simple delete this method from your code.
You're declaring ZipFile class yourself, while you should use existing one from System.IO.Compression namespace. So, just remove following part of your code:
Public NotInheritable Class ZipFile
Public Shared Sub ExtractToDirectory(
sourceArchiveFileName As String,
destinationDirectoryName As String
)
End Sub
End Class
...and everything should work as expected.

Could not load file or assembly 'accoremgd,Version=20.0.0.0, Culture=neutral, PublicKeyToken=null' one of its dependencies

I am beginner to AutoCAD customization in VB.net.
I have added following references to my project.
1. accoremgd.dll
2. AcCui.dll
3. acmgd.dll
4. acdbmgd.dll
following is my code:
Imports Autodesk.AutoCAD.ApplicationServices
Imports Autodesk.AutoCAD.DatabaseServices
Imports Autodesk.AutoCAD.Runtime
Imports System.IO
Imports Autodesk.AutoCAD.Interop
Imports Autodesk.AutoCAD.Interop.Common
Imports System.Runtime.InteropServices
Public Class Form1
Private Sub btnShow_Click(sender As Object, e As EventArgs) Handles btnShow.Click
Dim str_path As String
str_path = Application.DocumentManager.MdiActiveDocument.Name
txtbox1.Text = str_path
End Sub
End Class
And I am getting following exception:
An unhandled exception of type 'System.IO.FileNotFoundException' occurred in System.Windows.Forms.dll
Additional information: Could not load file or assembly 'accoremgd, Version=20.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.
What to do?
Thanks in advance :)
If you are trying to use Ac****Mgd.dll references from a .EXE project (Windows Application), then it will not work. See this reply.
In most of the cases I encountered this error it was one of ... its dependencies....
In this case you can add a handler to catch the AssemblyResolve event:
AddHandler AppDomain.CurrentDomain.AssemblyResolve, AddressOf AppDomain_AssemblyResolve
Private Shared Function AppDomain_AssemblyResolve(sender As Object, e As ResolveEventArgs) As Reflection.Assembly
Debug.WriteLine(e.Name)
Return Nothing
End Function
Then have a look at the output and see if there are assemblies missing.

VB.NET getting error: Class 'Application' must implement 'Sub InitializeComponent()'

I'm doing a VB.NET WPF application using VS2013, and I am just trying to find and use the right entry point.
I have read tons of answers on this, one saying something and the other saying the opposite. Mainly they say: the entry point of your project is the autogenerated main() you can find in your Application.g.vb. Yes, ok, very nice but...it is a generated file, not a good idea to modify it. So I searched the net on how to implement my own main() method, and the common answer I've found is:
Select Application.xaml and change its build action to "Page"
Create your own main method in Application.xaml.vb with this signature:
_
Public Shared Sub Main()
Dim app As Application = New Application()
app.InitializeComponent()
app.Run()
End Sub
Go to your project properties, untick "Enable applpication framework" and select Sub Main as startup for your application.
And so I have done but I continuously get this error:
Error 3 Class 'Application' must implement 'Sub InitializeComponent()' for interface 'System.Windows.Markup.IComponentConnector'.
this is the Application.g.i.vb file it generates:
#ExternalChecksum("..\..\Application.xaml","{406ea660-64cf-4c82-b6f0-42d48172a799}","DB788882721B2B27C90579D5FE2A0418")
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.42000
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict Off
Option Explicit On
Imports System
Imports System.Diagnostics
Imports System.Windows
Imports System.Windows.Automation
Imports System.Windows.Controls
Imports System.Windows.Controls.Primitives
Imports System.Windows.Data
Imports System.Windows.Documents
Imports System.Windows.Ink
Imports System.Windows.Input
Imports System.Windows.Markup
Imports System.Windows.Media
Imports System.Windows.Media.Animation
Imports System.Windows.Media.Effects
Imports System.Windows.Media.Imaging
Imports System.Windows.Media.Media3D
Imports System.Windows.Media.TextFormatting
Imports System.Windows.Navigation
Imports System.Windows.Shapes
Imports System.Windows.Shell
'''<summary>
'''Application
'''</summary>
<Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Public Class Application
Inherits System.Windows.Application
Implements System.Windows.Markup.IComponentConnector
Private _contentLoaded As Boolean
'''<summary>
'''InitializeComponent
'''</summary>
<System.Diagnostics.DebuggerNonUserCodeAttribute(), _
System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")> _
Public Sub InitializeComponent()
#ExternalSource("..\..\Application.xaml",4)
Me.StartupUri = New System.Uri("MainWindow.xaml", System.UriKind.Relative)
#End ExternalSource
If _contentLoaded Then
Return
End If
_contentLoaded = True
Dim resourceLocater As System.Uri = New System.Uri("/FatLink;component/application.xaml", System.UriKind.Relative)
#ExternalSource("..\..\Application.xaml",1)
System.Windows.Application.LoadComponent(Me, resourceLocater)
#End ExternalSource
End Sub
<System.Diagnostics.DebuggerNonUserCodeAttribute(), _
System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0"), _
System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never), _
System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes"), _
System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity"), _
System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")> _
Sub System_Windows_Markup_IComponentConnector_Connect(ByVal connectionId As Integer, ByVal target As Object) Implements System.Windows.Markup.IComponentConnector.Connect
Me._contentLoaded = True
End Sub
End Class
so...as Sub InitializeComponent() is there, why the hell do I keep getting this error?
**EDIT:**My Application.xaml.vb is just that:
Partial Public Class Application
<System.STAThreadAttribute(), _
System.Diagnostics.DebuggerNonUserCodeAttribute(), _
System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")> _
Public Shared Sub Main()
Dim app As Application = New Application()
app.InitializeComponent()
app.Run()
End Sub
End Class
I have managed to reproduce you problem:
Create a new WPF VB.NET application
Create the custom Main in the Application.xaml.vb file as from your post
In the project properties uncheck the Enable Application Framework (automatically the startup object becomes our Main sub)
Set for the Application.xaml file the Build Action property to Page
At this point, the line that call app.InitializeComponent() is underlined with a red squiggle to signify that the project cannot find the InitializeComponent method. If you try to compile at this point you get the mentioned error.
Final step:
In Application.xaml file remove the
StartupUri="MainWindow.xaml"
Now the squiggle disappears and the compilation ends correctly.
If you want to start you own main window you could change the Run line with
app.Run(New MainWindow())
If you get that error, you probably haven't stated that your app is to start with your Main() method. So:
"Go to your project settings and untick the Enable application framework checkbox (if it's ticked) and select Sub Main as the Startup object , then add your main-method to Application.xaml.vb (plus the logger and other stuff)."
When you have done that, VS won't create "its own" Main-method and will rather call the one you defined in Application.xaml.
Taken from: https://social.msdn.microsoft.com/Forums/vstudio/en-US/d7ef493f-27be-4f32-8ff4-a014078f572c/custom-systemwindowsapplication-in-vb-net?forum=wpf
Check also this: http://ugts.azurewebsites.net/data/UGTS/document/2/3/32.aspx

'TcpListener' is ambiguous in the namespace 'System.Net.Sockets'

I got 11 errors in my VB program. All the errors look similar: X is ambiguous in the namespace Y
Error line: Imports System.Net.Sockets
Imports System.Text
Module Module1
Sub Main()
Dim serverSocket As New TcpListener(System.Net.IPAddress.Parse("192.168.1.100"), 8888)
How might I resolve this?
I suspect that you've added two different references for assemblies that define System.Net.Sockets. (Probably System.dll for .NET 2.0 and .NET 4.0, but that's neither here nor there.)
I say this because there's nothing wrong with your code:
Imports System.Net.Sockets
Imports System.Text
Module Module1
Sub Main()
Dim serverSocket As New TcpListener(System.Net.IPAddress.Parse("192.168.1.100"), 8888)
End Sub
End Module
result: success time: 0.16s memory: 25064 kB returned value: 0