IDatabaseCompact.Compact() on an used IWorkspace - vb.net

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

Related

FileVersionInfo.GetVersionInfo not letting go of file

I'm trying to check the version of the Windows application the user is running against the version that is on the server to see if the local version needs to be updated. I do this by calling
FileVersionInfo.GetVersionInfo("path to file on server")
and reading the version information. This works fine for what I need, however, when I look at open files on the server from the computer management console, I see many instances of my file open in Read mode. This causes a problem when I need to copy a new version to the server. I first have to close all of the open files before it will let me write to it. Even though they are only open in Read mode, it still makes me close them.
Is there a better way to get the file version from the server? Or is there a way to dispose of the FileInfo variable that I am using so it disconnects?
I have not found a good resolution using FileVersionInfo. And from my research using FileVersionInfo does not release the variable as you would expect so I changed to getting the file information from a PowerShell script. This allows me to dispose the object and release the file as I have tested successfully. So here is the code that gets the information:
Dim server_version As String = ""
Dim invoker As New RunspaceInvoke
Dim command As String = "(Get-Item path_to_file_no_quotes_needed).VersionInfo.FileVersion"
Try
Dim outputObjects As Collection(Of PSObject) = invoker.Invoke(command)
For Each result As PSObject In outputObjects
server_version = result.ToString
Next
Catch ex As Exception
End Try
invoker.dispose
When this is run from my app, I see the file get opened in Read mode on the server but it disappears after about 3 seconds. So I can see the object is being properly disposed. Just FYI, there is no FileVersionInfo.dispose method.
In addition, for this to work you need:
Imports System.Management.Automation
which needs a reference in your project. It can be found in:
C:\Windows\assembly\GAC_MSIL\System.Management.Automation\1.0.0.0__31bf3856ad364e35\System.Management.Automation.dll
In the Shown event I have code that looks like this,
Try
If My.Application.IsNetworkDeployed AndAlso My.Application.Deployment.CheckForUpdate Then
'update available - the update will happen when app is closed
End If
Catch ex As Exception
'error while checking for update or update is corrupt
End Try
I do this so I can provide the user an indication that an update is available.
In the FormClosed event I do,
Try
'see if update is available, and install if it is
If My.Application.IsNetworkDeployed Then
If My.Application.Deployment.CheckForUpdate Then
My.Application.Deployment.Update()
End If
End If
Catch ex As Exception
End Try

Edit Settings.txt Document within Program Files directory during AutoCAD runtime

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.

Visual Basic don't see application.evtx

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")

Testing if I have full read/write access to a file in VB .NET 4.5 before processing it

I'm writing a windows service which runs as the local system account. I'm trying to make sure if I have full read/write access to a file beginning to process it any further. Here is my code:
Dim FullPath As String
FullPath = "C:\directory\file.txt"
Dim ps As Security.PermissionSet
ps = New Security.PermissionSet(Security.Permissions.PermissionState.Unrestricted)
ps.AddPermission(New Security.Permissions.FileIOPermission(Security.Permissions.FileIOPermissionAccess.AllAccess, FullPath))
ps.AddPermission(New Security.Permissions.FileIOPermission(Security.Permissions.FileIOPermissionAccess.AllAccess, IO.Path.GetDirectoryName(FullPath)))
Try
ps.Demand()
Catch ex As Security.SecurityException
System.Diagnostics.EventLog.WriteEntry("ShopLink", "File " + FullPath + " will not be parsed. " + ex.Message)
Exit Sub
Catch ex As Exception
System.Diagnostics.EventLog.WriteEntry("ShopLink", "File " + FullPath + " will not be parsed. " + ex.Message)
Exit Sub
End Try
Then I set the full access permissions for the file to "Deny" for the user account my service is running as. After executing, the code above doesn't throw any exceptions and allows file processing to begin. When the service later tries to change and/or delete the file, I get an "Access Denied" exception.
Any suggestions?
For this purpose i use thise small function:
Private Function HasAccess(ByVal ltFullPath As String)
Try
Using inputstreamreader As New StreamReader(ltFullPath)
inputstreamreader.Close()
End Using
Using inputStream As FileStream = File.Open(ltFullPath, FileMode.Open, FileAccess.ReadWrite, FileShare.None)
inputStream.Close()
Return True
End Using
Catch ex As Exception
Return False
End Try
End Function
In your case then:
If HasAccess(FullPath) ...
I have solved the problem by using My.Computer.FileSystem.DeleteFile to delete the file instead of Kill. My.Computer.FileSystem.DeleteFile was executed without problems after successfully demanding full read/write access to the file in the way described above, while Kill consistently threw an "Access denied" exception.
Using "Kill"... I know this is a very old thread but I'll add this in case anyone stumbles on it like I did. I was working on some old VB6 legacy code. One of my clients users was getting a runtime exception during a file open after a kill. The code was "Killing" the file and then rebuilding it from scratch with binary data held in memory. It tuns out that the "Kill" function triggered the user's anti-virus software which locked the file long enough to cause the next "Open" statement to fail. I discovered this using an error logging utility (the name escapes me at the moment). The line in the error log file on the failed "Open" statement was that the file's status was "Delete pending" due to the user's anti-virus software.

How to release MS Access LDB lock file after created it

sorry for long text.
Problem: I have difficulty in removing the LDB generated by the "CREATE" method of ADOX in the following code segment. Please provides some hints/pointers to the solutions, and thanks.
Aims: Create (on the fly) a new access database and then export data (says Arena modules) to that newly created database.
Expected: The newly created access database should be able to be used by some external operations, say Access.exe, after the end of the subroutine and without exiting the current VB program.
I tested that the "Arena code" do nothing about the create/release of the ldb file.
I tested the "Exclusive Mode" in connection string, but the access file is still locked by the vb program.
I tested under both inside the VB environment, and directly invoke the generated from Explorer, and same results.
Other database formats is not the options to me. (due to Arena export limit)
It is not a web app.
Code:
Sub Method1()
Dim logs As New System.Collections.Generic.List(Of String)
Dim arenaApp As Arena.Application = Nothing
Try
logs.Add("Creating access database")
Try
Dim cat As New ADOX.Catalog
cat.Create("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=new.mdb;Jet OLEDB:Engine Type=5")
cat = Nothing
Catch ex As Exception
logs.Add(ex.Message)
logs.Add(ex.StackTrace)
Finally
logs.Add("End creating access database")
End Try
'Opening Arena model"
arenaApp = New Arena.Application()
arenaApp.Models.Open(fileName)
arenaApp.ActiveModel.ExportModules("", "new.mdb", "TableName", "", Arena.smExportType.smExportAll)
Catch ex As Exception
logs.Add(ex.Message)
logs.Add(ex.StackTrace)
Finally
...
End Try
End Sub
Platform:
Windows 7 64bit, Office 2010 (32)
VB 2010 express
Lib: MS ADO Ext. 2.8 for DDL and Security
What about closing the mdb after creation, then reopening it ?
I am not a VS expert, but in Access, many things in "Design mode" put the mdb in Exclusive mode...and you can't switch back without closing it first i suspect.
If you want to create a database, its probably simpler to PInvoke SQLConfigDataSource. Then you can connect to it via ADODB, ADO.NET or your VB.NET data access methodology of choice.
I don't have an example of doing it in VB.NET, but this C# class and this powershell script demonstrate how to call the function.
I know it's an old question. I encountered exactly the same issue today. Some comments ask why use ADOX, that's because first, it's from legacy code, and second, I didn't find any other ways to dynamically create mdb file.
In VB6, whenever you set adox = Nothing, this com object will be released immediately and so is the ldb file.
In .Net, you have to rely on GC to collect the adox before ldb file is unlocked.
So, I made the following trick. I know it's ugly, but I didn't find any other ways, and at least my trick worked.
Dim t As New Thread(
Sub
'All adox code should be here
'....
'....
adox = Nothing
End Sub
)
t.Start()
t.Join()
t = Nothing
GC.Collect()
Sleep(50)