VB.net express System.UnauthorizedAccessException - vb.net

I am trying to write a file listing custom class in VB.net 2010 express on a Win7 64 bit machine. I installed VB.net express using an account that has administrator rights on both the machine and the network it belongs to. I should be able to access any file on the machine and from Windows Explorer, I can. I have been stopped cold by a “System.UnauthorizedAccessException”.
I have tried changing the manifest file. Although that should not be needed since the account already has full permissions. It has not worked. Below is a fragment of the offending code.
I am beginning to wonder if it is possible read the files on a drive using managed code. I can revert to the VBA class that in capsules ancient Win32 API calls that I wrote years ago but that violates the purpose of this exercise. Any suggestions would be appreciated.
Private Sub sLoadCatalog(ByVal strPath As String, ByVal intParentID As Integer)
'Get the file list
Dim strsearchPattern As String = "*"
Dim fp As New FileIOPermission(FileIOPermissionAccess.PathDiscovery _
Or FileIOPermissionAccess.Read, strPath)
Try
'fp.Demand()
fp.Assert()
Dim dirInfo As DirectoryInfo = New DirectoryInfo(strPath)
Dim FileList() As FileInfo = dirInfo.GetFiles()
If FileList.Length > 0 Then
… Loop through the file list and do something exciting
End If
Dim dirFolder() As DirectoryInfo = dirInfo.GetDirectories
If dirFolder.Length > 0 Then
… Loop through the folder list and do something exciting
sLoadCatalog(strfolder, intLastID)
Else
Exit Sub
End If
Catch e As SecurityException
MessageBox.Show("Security Cannot access folder " & strPath)
Catch k As UnauthorizedAccessException
MessageBox.Show("Unauthorized Cannot access folder " & strPath)
End Try

Related

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

VB.net UploadFile

I am trying to send a file up to a server using VB.net. I have found many examples exclaiming it to be simple to do but none of the examples I have found have worked.
The current one I am trying is in the following code:
Dim WithEvents wc As New System.Net.WebClient()
Private Sub oWord_DocumentBeforeClose(ByVal Doc As Microsoft.Office.Interop.Word.Document, ByRef Cancel As Boolean) Handles oWord.DocumentBeforeClose
Try
Using wc As New System.Net.WebClient()
wc.Credentials = New NetworkCredential("ehavermale", "ernie1")
wc.UploadFile("http://192.168.95.1:83/GraphTest.txt", "C:\Users\EHovermale\Desktop\GraphTest.txt")
End Using
Catch ex As Exception
MsgBox("Error:" + ex.Message)
End Try
'System.IO.File.Delete("C:\Users\EHovermale\Desktop\GraphTest.txt")
MsgBox("See Ya")
End Sub
When I run this program I get the Error: An Exception has occurred during a WebClient Request.
I have access to read/write files to the server I am trying to hit.
Is there another way to upload files or is something wrong with my code for this way?
Thank you!
Since there is no HTTP service to handle the file upload, you could save the file directly using VBA's Scripting.FileSystemObject. This will work if you can access the network share from wherever your document is located. Remember that if the document is moved to another computer then this may not work.
Public Sub MoveFile()
Dim fso As Object
Dim sourceFile As String
Dim targetFile As String
' You must add reference to "Microsoft Scripting Runtime" to your document
' Tools > References... > scroll down the item.
Set fso = CreateObject("Scripting.FileSystemObject")
sourceFile = "C:\Users\davidr\Desktop\foo.txt"
targetFile = "\\192.168.95.1:83\foo.txt"
' Test if destination file already exists
If fso.FileExists(targetFile) Then
MsgBox ("This file exists!")
Exit Sub
End If
' Move the file
fso.CopyFile sourceFile, targetFile
Set fso = Nothing
End Sub

Use Shell32.dll on mix of XP, Vista, Win7 via XCOPY deploy

I'm trying to use Shell32.dll to unzip a simple compressed file. I have a reference to Shell32.dll which shows up as Interop.Shell.dll on my development PC (Win7 64.) I push exe updates out via file copy from a central location and I would like to do this for the .dll as well.
The program fails on XP using the same file as it installed on my PC. I tried using a Shell.dll from the XP \Windows\System renamed to Interop.Shell.dll but I guess that would be to simple - it gets an error that it cannot load when I try to invoke the dll.
I'm open too another way of doing unzip that uses a dll that is agnostic as to platform. I've used 7Zip via Process.Start() but I'd like to avoid having to install/update a program on the clients.
Is there a common denominator Shell32.dll I could use the would run on any Win OS on/after XP?
Or do I have to create a separate build for each OS if I use Shell32.dll?
Thanks!
Function Unzip(FilePathofZip As String, DestinationFolder As String) As Boolean
Try
Dim sFile As String = FilePathofZip
' requires referenc to windows.system.shell32.dll
Dim sc As New Shell32.Shell()
If IO.Directory.Exists(DestinationFolder) Then IO.Directory.Delete(DestinationFolder, True)
Application.DoEvents()
IO.Directory.CreateDirectory(DestinationFolder)
'Declare the folder where the files will be extracted
Dim output As Shell32.Folder = sc.NameSpace(DestinationFolder)
If FilePathofZip.EndsWith(".kmz") Then
sFile = FilePathofZip & ".zip"
IO.File.Move(FilePathofZip, sFile)
Application.DoEvents()
End If
'Declare your input zip file as folder
Dim input As Shell32.Folder = sc.NameSpace(sFile)
'Extract the files from the zip file using the CopyHere command .
output.CopyHere(input.Items, 4)
Return True
Catch ex As Exception
MsgBox(ex.Message)
Return False
End Try
End Function
I switched to DotNetZip. Add Project Reference to the Ionic.Zip.Reduced.dll. Imports Ionic.Zip
This code is expecting .kmz files downloaded from ESRI REST services but should work with .zip files as well.
Function Unzip(FilePathofZip As String, DestinationFolder As String) As Boolean
' extract .kmz files downloaded from ESRI REST services
Try
Dim sFile As String = FilePathofZip
If IO.Directory.Exists(DestinationFolder) Then IO.Directory.Delete(DestinationFolder, True)
Application.DoEvents()
IO.Directory.CreateDirectory(DestinationFolder)
If FilePathofZip.EndsWith(".kmz") Then
sFile = FilePathofZip & ".zip"
IO.File.Move(FilePathofZip, sFile)
Application.DoEvents()
End If
Try
' Using... required
Using zip As ZipFile = ZipFile.Read(sFile)
Dim e As ZipEntry
For Each e In zip
e.Extract(DestinationFolder)
Next
End Using
Catch ex1 As Exception
MsgBox("Problem with compressed file - notify programmers" & vbCrLf & ex1.Message)
Return False
End Try
Return True
Catch ex As Exception
MsgBox(ex.Message)
Return False
End Try
End Function

ASP.NET - Deleting Computer Accounts Within AD

I'm building out a decommissioning application that will allow an individual to provide an computer name and the utility will go out and purge the computer record from various locations. I'm running into a problem when attempting to delete a computer account from Active Directory. I'm impersonating a service account that only has rights to "Delete All Child Objects" within a particular OU structure. The code below works if I run it with my domain admin account; however fails with an "Access Denied" when I run it with the impersonated service account. I have verified that the permissions are correct within AD as I can launch Active Directory Users and Computers using a "runas" and providing the service account credentials and I can delete computer objects perfectly fine.
Wondering if anyone has run into this before or has a different way to code this while still utilizing my current OU permissions. My gut tells me the "DeleteTree" method is doing more then just deleting the object.
Any assistance would be appreciated.
Sub Main()
Dim strAsset As String = "computer9002"
Dim strADUsername As String = "serviceaccount#domain.com"
Dim strADPassword As String = "password"
Dim strADDomainController As String = "domaincontroller.domain.com"
Dim objDirectoryEntry As New System.DirectoryServices.DirectoryEntry
Dim objDirectorySearcher As New System.DirectoryServices.DirectorySearcher(objDirectoryEntry)
Dim Result As System.DirectoryServices.SearchResult
Dim strLDAPPath As String = ""
Try
objDirectoryEntry.Path = "LDAP://" & strADDomainController
objDirectoryEntry.Username = strADUsername
objDirectoryEntry.Password = strADPassword
objDirectorySearcher.SearchScope = DirectoryServices.SearchScope.Subtree
objDirectorySearcher.Filter = "(&(ObjectClass=Computer)(CN=" & strAsset & "))"
Dim intRecords As Integer = 0
For Each Result In objDirectorySearcher.FindAll
Console.WriteLine(Result.Path)
Diagnostics.Debug.WriteLine("DN: " & Result.Path)
Dim objComputer As System.DirectoryServices.DirectoryEntry = Result.GetDirectoryEntry()
objComputer.DeleteTree()
objComputer.CommitChanges()
intRecords += 1
Next
If intRecords = 0 Then
Console.WriteLine("No Hosts Found")
End If
Catch e As System.Exception
Console.WriteLine("RESULT: " & e.Message)
End Try
End Sub
If you're on .NET 3.5 and up, you should check out the System.DirectoryServices.AccountManagement (S.DS.AM) namespace. Read all about it here:
Managing Directory Security Principals in the .NET Framework 3.5
MSDN docs on System.DirectoryServices.AccountManagement
Basically, you can define a domain context and easily find users and/or groups in AD:
' set up domain context
Dim ctx As New PrincipalContext(ContextType.Domain, "DOMAIN", strADUsername, strADPassword)
' find a computer
Dim computerToDelete As ComputerPrincipal = ComputerPrincipal.FindByIdentity(ctx, strAsset)
If computerToDelete IsNot Nothing Then
' delete the computer, if found
computerToDelete.Delete()
End If
The new S.DS.AM makes it really easy to play around with users and groups in AD!
Delete Tree is different from delete. You're going to need the Delete Subtree permission on the child computer objects for this to work.

Windows Service not able to access mapped folders

I have a very simple VB.net Windows Service written using VS.net 2008. The program after doing several other functions writes a log in one of the network folders. The code is as shown below: If I change the path from "Y:\Activity_Log" to "C:\Activity_Log" it is working like a charm.
What is the problem if I use Y drive which is a valid one and I am able to access it from other VB.net desktop apps. Please help.
Dim strFile As String = "Y:\Activity_Log\" & DateTime.Today.ToString("dd-MMM-yyyy") & ".txt"
Dim fs As FileStream = Nothing
Dim activityfolder As String = "Y:\Activity_Log"
Dim di As System.IO.DirectoryInfo
di = New System.IO.DirectoryInfo(activityfolder)
If (Not di.Exists) Then
di.Create()
End If
If (Not File.Exists(strFile)) Then
Try
Dim sw1 As New StreamWriter(File.Open(strFile, FileMode.OpenOrCreate))
sw1.WriteLine("******************************Activity Log for " & Now.Date & "*******************")
sw1.WriteLine("-----------------------------------------------------------------------------------------------------------------")
sw1.WriteLine(Remarks & " ---" & DateTime.Now)
sw1.Close()
Catch ex As Exception
End Try
Else
Dim sw As StreamWriter
sw = AppendText(strFile)
sw.WriteLine(Remarks & " ---" & DateTime.Now)
sw.Close()
End If
Start->Control Panel->Administrative Tools->Services
Find Your service in the list, right click on the name, Properties
Click the Log On tab
Change from Local System account to 'This Account'
Use a user that has access to that share, start with your username/password to convince yourself that it works ;)
Click Ok, then restart the service.
maybe you need to run the service under a user that has access to that drive?
maybe the generic service user doesn't have access.