I am trying to store the AutoCAD users' settings in a directory under their Program Files. Originally, I had everything stored in the users favorites folder, but I wanted to keep all the plugin documents/files within the same directory. So, I have been trying all kinds of options to get admin rights during runtime, but still have not been successful. This is, more or less, what I just recently tested:
Public Shared Sub GetAdminAccess()
AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal)
Dim curIdentity As WindowsIdentity = WindowsIdentity.GetCurrent()
Dim principalPerm As PrincipalPermission = New PrincipalPermission(Nothing, "BUILTIN\Administrators")
principalPerm.Demand()
End Sub
<PrincipalPermissionAttribute(SecurityAction.Demand, Role:="BUILTIN\Administrators")>
Private Shared Sub CreateSettingsFile()
Try
IO.File.Create(SettingsFilePath)
SettingsFileData = DefaultFileData
Property_WindowsOnTop = True
Property_SaveBackups = False
Property_SkipCreateSite = False
Property_AlignmentZoomExtents = ToFullExtents
Property_SaveBackups_Method = _TxtValue_Generic_None
Property_SaveBackups_MainDirectoryPath = _TxtValue_Generic_None
Call SetUserSettings(SettingsFileData)
Call SetPropertySettings()
Catch IOE As IO.IOException
MsgBox(IOE.Message)
Catch Ex As Exception
MsgBox(Ex.Message)
End Try
End Sub
Many of my attempts have resulted with this same error:
"Application attempted to perform an operation now allowed by the security policy. To grant this application the required permission, contact your system administrator, or use the Microsoft.NET Framework Configuration tool.
If you click Continue, the application will ignore this error and attempt to continue.
Request for principal permission failed."
An app can't write to the Program Files folder without administrator rights. The program files folder (and subfolders under it) are admin protected to prevent programs from replacing installed executable code with a malicious equivalent. Just don't do that.
If want app-specific data, use the appData folder. You can access that folder using System.Environment.SpecialFolder.ApplicationData and Environment.GetFolderPath
Get comfortable with the SpecialFolder enumeration (and with System.IO.Path.Combine). They are the correct way to access all of the well-known folders in the Windows OS.
Related
I have a problem with "Application.evtx" file. Everytime I run my script I get the message box with "File not found" information and I don't know why. I ran Visual Studio as administrator. Help me with this one, please.
Imports System.IO
Module Module1
Sub Main()
Dim pathReadFile As String = "c:\Windows\System32\winevt\Logs\Application.evtx"
'Dim pathReadFile As String = "%windir%\Sysnative\winevt\Logs\Application.evtx"
'Dim pathReadFile As String = "D:\Dokumenty\MyTest.txt"
Try
If File.Exists(pathReadFile) Then
MsgBox("File found.")
Else
MsgBox("File not found.")
End If
Catch ex As Exception
End Try
End Sub
End Module
Don't use File.Exists(). Ever.
There are many reasons for this, but the one that impacts you right now is that it lies to you and tells you the file does not exist, even if the file actually does exist and the real problem is that you don't have permissions to use it. From the docs:
Return Value
Type: System.Boolean
true if the caller has the required permissions and path contains the name of an existing file; otherwise, false
Remember that normal users have extremely limited file system permissions outside of their own home folders, and even Administrator users need to explicitly run a process as elevated or UAC will just give them normal user permissions.
You have to handle the exception anyway if reading the file fails. Put your development effort into the exception handler.
While I'm here, you may also want to build your path like this:
Dim pathReadFile As String = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "winevt\Logs\Application.evtx")
I'm creating a html page that will import an excel file in to a tracking system. On a button click event excel file is located / ssis package is fired / data imported then closed out. Thats the idea work flow. Problem is the excel file access is being denied before the package even executes
Here is the exact error :
I've tried :
excel file properties have been shared to everyone
identity impersonate set to true
hard coding the path
here is the VB code
Protected Sub bntExecute_Click(sender As Object, e As EventArgs) Handles btnExecute.Click
Dim app As Application = New Application()
Dim package As Package = Nothing
'Dim fileName As String = "C:\Users\Desktop\T. Bryant III\PTSID_Update_Template"'
Try
Dim fileName As String = Server.MapPath(System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName.ToString()))
FileUpload1.PostedFile.SaveAs(fileName)
package = app.LoadPackage("#C:\Users\Desktop\T.Bryant III\KitImport", Nothing)
'excel connection from package'
package.Connections("SourceConnectionExcel").ConnectionString = "provider=Microsoft.Jet.OLEDB.4.0data source =" + fileName + "Extended Properties = Excel 8.0"
'Execute the pakage'
Dim results As Microsoft.SqlServer.Dts.Runtime.DTSExecResult = package.Execute()
Catch ex As Exception
Throw ex
Finally
package.Dispose()
package = Nothing
End Try
End Sub
Thanks in advance or if there is an easier way to do this please let me know. The package when executing it in ssis works fine with its own connection manager etc.
A few things to try. If they don't work for you as permanent solutions, they should at least confirm that your code is working and you are dealing with a persmissions issue (which appears to be the case).
Move your file to the public folder (C:\Users\Public).
Run your application (or web browser) as an administrator (if applicable to your version of Windows).
If you are using a web browser, try using a different one.
If nothing else works, try pasting your code into a Windows Form Application.
If you still get the same error after trying all of this, it's time to take another look at your code. Remove the Try/Catch block to determine precisely which line is throwing the error. If you've tried hard coding, I'm guessing it's the SaveAs method. I'm not sure what class FileUpload1 is, but some SaveAs methods won't overwrite existing files unless you explicitly tell them to. Check the appropriate documentation and see if you don't need to pass a True value somewhere along with filename.
Update us with the results. At the very least, this should narrow down your problem and allow for a better diagnosis of it.
Goal
To verify if a user has access to write / delete files on a specific network folder. For example:
\\MyCompany\Department\DocumentCenter\ is the directory where all the files are stored for the document center program. If a user has access to this folder, he is able to add / edit / delete files. If not, an error is caught by my try-catch.
Current Solution
I have attempted to solve this by setting up a try-catch right before the user deletes the file. If the user encounters an error, he will get a message saying that he does not have access... I find this rather trivial and would like a more concrete way of determining if the user has access to this folder.
How do I verify if a user has access to this specified folder?
When attempting to add / edit / delete a file on the given directory, as mentioned, I provide a try catch like so:
Private Sub DeleteFile(ByVal Path As String)
Try
'Example of Path: \\MyCompany\Department\DocumentCenter\File.PDF
File.Delete(Path)
Catch ex As Exception
MsgBox("Cannot delete this file. Contact your system admnistrator to have access to this directory.")
End Try
End Sub
I'm new here and to vb.net and I'm stuck on something that I feel SHOULD be simple to resolve. I setup my program to let the user decide if he or she wants to have the program run at windows start. It actually works fine as it is assigning the registry value to CurrentUser instead of Local Machine because of admin rights needing to be bypassed. However, when I restart my computer the program comes up like normal, but it will not read my access db that is located in the same folder as the program; it tries to read the DB from Windows\System32.
Is there a way to force it to read from the executablepath instead of System32?
Here is my simple code:
Private Sub startup()
If cbStartup.Checked = True Then
My.Computer.Registry.CurrentUser.OpenSubKey("Software").OpenSubKey("Microsoft").OpenSubKey("Windows").OpenSubKey("CurrentVersion").OpenSubKey("Run", True).SetValue("CC_List", System.Windows.Forms.Application.ExecutablePath)
ElseIf cbStartup.Checked = False Then
My.Computer.Registry.CurrentUser.OpenSubKey("Software").OpenSubKey("Microsoft").OpenSubKey("Windows").OpenSubKey("CurrentVersion").OpenSubKey("Run", True).DeleteValue("CC_List", False)
End If
End Sub
So when the O/S starts your program the Current Directory is %windir%\System32.
You need to either adjust all your existing paths to be explicitly relative to Application.ExecutablePath, or put
My.Computer.FileSystem.CurrentDirectory = My.Application.Info.DirectoryPath
at the start of your program (which is the modern version of ChDir ...).
I am writting an ArcMap-AddIn with vb.net. I got an error when trying to compact my IWorkspace(mdb), the error is:
COMException
You tried to open a database, which was already opened by the user
'ADMIN' on Computer 'XXXXXX'. Try it again when the database is
available.
On ESRI.ArcGIS.Geodatabase.IDatabaseCompact.Compact() on
MyProject.MyClass.CompactGDB(IWorkspace pWS)
How can i compact the used workspace?
There are 8 other functions which also used my workspace.
Any suggestions?
The Code:
' CompactGDB
Public Sub CompactGDB(ByVal pWS As IWorkspace)
Dim pDatabaseCompact As IDatabaseCompact
If (TypeOf pWS Is IDatabaseCompact) Then
pDatabaseCompact = CType(pWS, IDatabaseCompact)
If (pDatabaseCompact.CanCompact) Then
Try
pDatabaseCompact.Compact()
Catch ex As Exception
MessageBox.Show(ex.type & ex.Message & ex.StackTrace, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End If
End If
End Sub
Found the solution:
Before calling the Compact() method make sure there are not any existing locks on the database.
If it is a file geodatabase then open the gdb directory in Windows Explorer and look for LOCK type files, they end in .lock.
For personal geodatabase there will be a .ldb file in the directory with the same name as the .mdb.
If you have a layer or table from the geodatabase loaded in the map
then you will not be able to remove all locks.
If another user is
accessing the geodatabase then you will not be able to remove all
locks.
If you are using arcobjects to temporarily access the
geodatabase then you need to use good practices and close any
geodatabase resources when the calling process ends. This includes
releasing all COM objects when you are finished with them.
Use the ComReleaser Class in ESRI.ArcGIS.ADF.Connection.Local namespace