Extracting Zip File in Visual Basic .NET - vb.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.

Related

How do I reference a Module in VB from a NuGet package

I've created my own private NuGet server and hosted two packages written in VB, one with a single public class and one with a Module containing some extension methods. When I reference the packages in my application, I am able to create a new instance of the class from the package, but I am unable to use any methods declared in the module. I know that modules need to be contained withing the namespace, so I have a feeling I may need to reference it somewhere to make use of it. Does anyone know what I need to do? Thanks.
I've currently got the following:
Namespace TestHelperNamespace
Public Class TestHelper
Public Sub DoSomething()
End Sub
End Class
Public Module TestModule
Public Sub StringSub(s As String)
End Sub
End Module
End Namespace
Import the Module's namespace in your code
Imports NugetModuleNamespace
Here's a MCVE
Imports Namespace2
Namespace Namespace1
Module Module1
Private Sub foo()
Dim a = 1.23#
Dim b = a.Square() ' doesn't work without Imports
End Sub
End Module
End Namespace
Namespace Namespace2
Module Module2
<System.Runtime.CompilerServices.Extension>
Public Function Square(value As Double) As Double
Return value ^ 2
End Function
End Module
End Namespace
This applies to Modules in separate files as well.

Visual Studio Test vs Form application

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.

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

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

Using a custom DLL in Silverlight

I'm testing and trying to understand how to create a DLL and call a function from it in my Silverlight project. I'm getting an exception: Unable to find an entry point named 'WriteTextFile' in DLL 'C:\temp\TestDLL.dll'. So I'm doing something wrong.
Here is my code for the very simple DLL:
Imports System.IO
Public Class Class1
Private Shared dir As String = "C:\TEMP"
Private Shared file As String = "TestDLL.txt"
Public Shared Sub WriteTextFile()
Using wr As New StreamWriter(System.IO.Path.Combine(dir, file))
wr.WriteLine("Call to function WriteTextFile()")
End Using
End Sub
End Class
And this is what I'm doing in my Silverlight:
Imports System.Runtime.InteropServices
Partial Public Class MainPage
Inherits UserControl
<DllImport("C:\temp\TestDLL.dll")> _
<AllowReversePInvokeCalls()> _
Friend Shared Sub WriteTextFile()
End Sub
Public Sub New()
InitializeComponent()
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles Button1.Click
WriteTextFile()
End Sub
End Class
I need some pointing to the right direction here :)
The AllowReversePInvokeCalls part is just something I tried out after doing some reading around the web but it didn't change anything. Also I've tried to set the EntryPoint in the DLLImport but that doesn't do anything either.
Edit:
I tried this DLL and pinvoke in regular WPF application and I get the same error so this is not related to Silverligth. Maybe in my DLL then?
Ok, so it looks like this can't be done simply because using pinvoke requires a standard dll and I can't do those with VB .NET. So I'll need to try something else :)
If anyone has more information about this and like to share it I would appreciate that. Or correct me if I've understood the issue wrong.