Check if file is locked or not and present to end user if it is locked and by what.

Resulted in breaking some of my habits and putting a messagebox windows in libraries.  Not my favorite thing, but it works.

This helps debug issue 3, it does not resolve issue 3.

To test it - open an office document (such as Word or Excel) and try to overwrite the office document with the RDP file including the office document extention (xls, xlsx, doc, docx, etc).  The application will tell you that the file is locked, locked by Word/Excel/etc and the PID that is locking it just in case you have multiple copies of the application that is locking it open.

A lot of the code was borrowed from Microsoft (https://code.msdn.microsoft.com/windowsapps/How-to-know-the-process-170ed5f3/sourcecode?fileId=151114&pathId=1558127374).
This commit is contained in:
brianga 2019-11-13 13:09:43 -06:00
parent f7a343e216
commit 57111a3d21
19 changed files with 808 additions and 15 deletions

233
LockChecker/LockCheck.vb Normal file
View File

@ -0,0 +1,233 @@
' code sample taken from:
'https://code.msdn.microsoft.com/windowsapps/How-to-know-the-process-170ed5f3/sourcecode?fileId=151114&pathId=1558127374
' Modified to suit the needs of this application
Imports System.ComponentModel
Imports System.Runtime.InteropServices
Module LockCheck
' maximum character count of application friendly name.
Private Const CCH_RM_MAX_APP_NAME As Integer = 255
' maximum character count of service short name.
Private Const CCH_RM_MAX_SVC_NAME As Integer = 63
' A system restart is not required.
Private Const RmRebootReasonNone As Integer = 0
''' <summary>
''' Uniquely identifies a process by its PID and the time the process began.
''' An array of RM_UNIQUE_PROCESS structures can be passed
''' to the RmRegisterResources function.
''' </summary>
<StructLayout(LayoutKind.Sequential)>
Private Structure RM_UNIQUE_PROCESS
' The product identifier (PID).
Public dwProcessId As Integer
' The creation time of the process.
Public ProcessStartTime As System.Runtime.InteropServices.ComTypes.FILETIME
End Structure
''' <summary>
''' Specifies the type of application that is described by
''' the RM_PROCESS_INFO structure.
''' </summary>
Private Enum RM_APP_TYPE
' The application cannot be classified as any other type.
RmUnknownApp = 0
' A Windows application run as a stand-alone process that
' displays a top-level window.
RmMainWindow = 1
' A Windows application that does not run as a stand-alone
' process and does not display a top-level window.
RmOtherWindow = 2
' The application is a Windows service.
RmService = 3
' The application is Windows Explorer.
RmExplorer = 4
' The application is a stand-alone console application.
RmConsole = 5
' A system restart is required to complete the installation because
' a process cannot be shut down.
RmCritical = 1000
End Enum
''' <summary>
''' Describes an application that is to be registered with the Restart Manager.
''' </summary>
<StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Auto)>
Private Structure RM_PROCESS_INFO
' Contains an RM_UNIQUE_PROCESS structure that uniquely identifies the
' application by its PID and the time the process began.
Public Process As RM_UNIQUE_PROCESS
' If the process is a service, this parameter returns the
' long name for the service.
<MarshalAs(UnmanagedType.ByValTStr, SizeConst:=CCH_RM_MAX_APP_NAME + 1)>
Public strAppName As String
' If the process is a service, this is the short name for the service.
<MarshalAs(UnmanagedType.ByValTStr, SizeConst:=CCH_RM_MAX_SVC_NAME + 1)>
Public strServiceShortName As String
' Contains an RM_APP_TYPE enumeration value.
Public ApplicationType As RM_APP_TYPE
' Contains a bit mask that describes the current status of the application.
Public AppStatus As UInteger
' Contains the Terminal Services session ID of the process.
Public TSSessionId As UInteger
' TRUE if the application can be restarted by the
' Restart Manager; otherwise, FALSE.
<MarshalAs(UnmanagedType.Bool)>
Public bRestartable As Boolean
End Structure
''' <summary>
''' Registers resources to a Restart Manager session. The Restart Manager uses
''' the list of resources registered with the session to determine which
''' applications and services must be shut down and restarted. Resources can be
''' identified by filenames, service short names, or RM_UNIQUE_PROCESS structures
''' that describe running applications.
''' </summary>
''' <param name="pSessionHandle">
''' A handle to an existing Restart Manager session.
''' </param>
''' <param name="nFiles">The number of files being registered</param>
''' <param name="rgsFilenames">
''' An array of null-terminated strings of full filename paths.
''' </param>
''' <param name="nApplications">The number of processes being registered</param>
''' <param name="rgApplications">An array of RM_UNIQUE_PROCESS structures</param>
''' <param name="nServices">The number of services to be registered</param>
''' <param name="rgsServiceNames">
''' An array of null-terminated strings of service short names.
''' </param>
''' <returns>The function can return one of the system error codes that
''' are defined in Winerror.h
''' </returns>
<DllImport("rstrtmgr.dll", CharSet:=CharSet.Auto, SetLastError:=True)>
Private Function RmRegisterResources(pSessionHandle As UInteger, nFiles As UInt32, rgsFilenames As String(), nApplications As UInt32, <[In]> rgApplications As RM_UNIQUE_PROCESS(), nServices As UInt32,
rgsServiceNames As String()) As Integer
End Function
''' <summary>
''' Starts a new Restart Manager session. A maximum of 64 Restart Manager
''' sessions per user session can be open on the system at the same time.
''' When this function starts a session, it returns a session handle and
''' session key that can be used in subsequent calls to the Restart Manager API.
''' </summary>
''' <param name="pSessionHandle">
''' A pointer to the handle of a Restart Manager session.
''' </param>
''' <param name="dwSessionFlags">Reserved. This parameter should be 0.</param>
''' <param name="strSessionKey">
''' A null-terminated string that contains the session key to the new session.
''' </param>
''' <returns></returns>
<DllImport("rstrtmgr.dll", CharSet:=CharSet.Auto, SetLastError:=True)>
Private Function RmStartSession(ByRef pSessionHandle As UInteger, dwSessionFlags As Integer, strSessionKey As String) As Integer
End Function
''' <summary>
''' Ends the Restart Manager session. This function should be called by the
''' primary installer that has previously started the session by calling the
''' RmStartSession function. The RmEndSession function can be called by a
''' secondary installer that is joined to the session once no more resources
''' need to be registered by the secondary installer.
''' </summary>
''' <param name="pSessionHandle">
''' A handle to an existing Restart Manager session.
''' </param>
''' <returns>
''' The function can return one of the system error codes
''' that are defined in Winerror.h.
''' </returns>
<DllImport("rstrtmgr.dll", CharSet:=CharSet.Auto, SetLastError:=True)>
Private Function RmEndSession(pSessionHandle As UInteger) As Integer
End Function
''' <summary>
''' Gets a list of all applications and services that are currently using
''' resources that have been registered with the Restart Manager session.
''' </summary>
''' <param name="dwSessionHandle">
''' A handle to an existing Restart Manager session.
''' </param>
''' <param name="pnProcInfoNeeded">A pointer to an array size necessary to
''' receive RM_PROCESS_INFO structures required to return information for
''' all affected applications and services.
''' </param>
''' <param name="pnProcInfo">
''' A pointer to the total number of RM_PROCESS_INFO structures in an array
''' and number of structures filled.
''' </param>
''' <param name="rgAffectedApps">
''' An array of RM_PROCESS_INFO structures that list the applications and
''' services using resources that have been registered with the session.
''' </param>
''' <param name="lpdwRebootReasons">
''' Pointer to location that receives a value of the RM_REBOOT_REASON
''' enumeration that describes the reason a system restart is needed.
''' </param>
''' <returns></returns>
<DllImport("rstrtmgr.dll", CharSet:=CharSet.Auto, SetLastError:=True)>
Private Function RmGetList(dwSessionHandle As UInteger, ByRef pnProcInfoNeeded As UInteger, ByRef pnProcInfo As UInteger, <[In], Out> rgAffectedApps As RM_PROCESS_INFO(), ByRef lpdwRebootReasons As UInteger) As Integer
End Function
Function LockCheck(Filename As String)
Dim handle As UInteger
Dim sessionkey As String = Guid.NewGuid().ToString()
Dim processes As New List(Of Process)()
Dim result As String = ""
Dim res As Integer = RmStartSession(handle, 0, sessionkey)
If res <> 0 Then
Throw New Exception("Could not begin restart session.")
End If
Try
Dim pnProcInfoNeeded As UInteger = 0, pnProcInfo As UInteger = 100, lpdwRebootReasons As UInteger = RmRebootReasonNone
Dim resources As String() = New String() {Filename}
' Create an array to store the process results.
Dim processInfo As RM_PROCESS_INFO() = New RM_PROCESS_INFO(pnProcInfo - 1) {}
res = RmRegisterResources(handle, CUInt(resources.Length), resources, 0, Nothing, 0,
Nothing)
If res <> 0 Then
Throw New Exception("Could not register resource.")
End If
res = RmGetList(handle, pnProcInfoNeeded, pnProcInfo, processInfo, lpdwRebootReasons)
If res = 0 Then
'The function completed successfully.
If pnProcInfo <> 0 Then
For i As Integer = 0 To pnProcInfo - 1
'Console.WriteLine("File Name :" + resources(0))
result = result + "File Name :" + resources(0) + vbNewLine
'Console.WriteLine("Application locking the file :" + processInfo(i).strAppName)
result = result + "Application locking the file : " + processInfo(i).strAppName + vbNewLine
result = result + "PID of process locking the file: " + processInfo(i).Process.dwProcessId.ToString() + vbNewLine
Next
Else
'Console.WriteLine("The specified file '{0}' is not locked by any process", resources(0))
result = result + "No locks"
End If
Else
Throw New Exception("Could not list processes locking resource.")
End If
If res <> 0 Then
Throw New Win32Exception(Marshal.GetLastWin32Error())
End If
Catch exception As Exception
'Console.WriteLine(exception.Message)
result = result + exception.Message
Finally
RmEndSession(handle)
End Try
Return result
End Function
End Module
Public Class LockChecker
Public Function CheckLock(FileName As String)
Return LockCheck.LockCheck(FileName)
End Function
End Class

View File

@ -0,0 +1,102 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{029C010D-728B-4B87-B54A-08B2BBF49BD7}</ProjectGuid>
<OutputType>Library</OutputType>
<RootNamespace>LockChecker</RootNamespace>
<AssemblyName>LockChecker</AssemblyName>
<FileAlignment>512</FileAlignment>
<MyType>Windows</MyType>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<Deterministic>true</Deterministic>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<DefineDebug>true</DefineDebug>
<DefineTrace>true</DefineTrace>
<OutputPath>bin\Debug\</OutputPath>
<DocumentationFile>LockChecker.xml</DocumentationFile>
<NoWarn>42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<DefineDebug>false</DefineDebug>
<DefineTrace>true</DefineTrace>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DocumentationFile>LockChecker.xml</DocumentationFile>
<NoWarn>42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
</PropertyGroup>
<PropertyGroup>
<OptionExplicit>On</OptionExplicit>
</PropertyGroup>
<PropertyGroup>
<OptionCompare>Binary</OptionCompare>
</PropertyGroup>
<PropertyGroup>
<OptionStrict>Off</OptionStrict>
</PropertyGroup>
<PropertyGroup>
<OptionInfer>On</OptionInfer>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
</ItemGroup>
<ItemGroup>
<Import Include="Microsoft.VisualBasic" />
<Import Include="System" />
<Import Include="System.Collections" />
<Import Include="System.Collections.Generic" />
<Import Include="System.Data" />
<Import Include="System.Diagnostics" />
<Import Include="System.Linq" />
<Import Include="System.Xml.Linq" />
</ItemGroup>
<ItemGroup>
<Compile Include="LockCheck.vb" />
<Compile Include="My Project\AssemblyInfo.vb" />
<Compile Include="My Project\Application.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Application.myapp</DependentUpon>
</Compile>
<Compile Include="My Project\Resources.Designer.vb">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<Compile Include="My Project\Settings.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="My Project\Resources.resx">
<Generator>VbMyResourcesResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.vb</LastGenOutput>
<CustomToolNamespace>My.Resources</CustomToolNamespace>
<SubType>Designer</SubType>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Include="My Project\Application.myapp">
<Generator>MyApplicationCodeGenerator</Generator>
<LastGenOutput>Application.Designer.vb</LastGenOutput>
</None>
<None Include="My Project\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<CustomToolNamespace>My</CustomToolNamespace>
<LastGenOutput>Settings.Designer.vb</LastGenOutput>
</None>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.VisualBasic.targets" />
</Project>

View File

@ -0,0 +1,13 @@
'------------------------------------------------------------------------------
' <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 On
Option Explicit On

View File

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<MyApplicationData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<MySubMain>false</MySubMain>
<SingleInstance>false</SingleInstance>
<ShutdownMode>0</ShutdownMode>
<EnableVisualStyles>true</EnableVisualStyles>
<AuthenticationMode>0</AuthenticationMode>
<ApplicationType>1</ApplicationType>
<SaveMySettingsOnExit>true</SaveMySettingsOnExit>
</MyApplicationData>

View File

@ -0,0 +1,35 @@
Imports System
Imports System.Reflection
Imports System.Runtime.InteropServices
' General Information about an assembly is controlled through the following
' set of attributes. Change these attribute values to modify the information
' associated with an assembly.
' Review the values of the assembly attributes
<Assembly: AssemblyTitle("LockChecker")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyCompany("")>
<Assembly: AssemblyProduct("LockChecker")>
<Assembly: AssemblyCopyright("Copyright © 2019")>
<Assembly: AssemblyTrademark("")>
<Assembly: ComVisible(False)>
'The following GUID is for the ID of the typelib if this project is exposed to COM
<Assembly: Guid("6422a30e-03d9-4b6d-af72-79c2a4b849a1")>
' Version information for an assembly consists of the following four values:
'
' Major Version
' Minor Version
' Build Number
' Revision
'
' You can specify all the values or you can default the Build and Revision Numbers
' by using the '*' as shown below:
' <Assembly: AssemblyVersion("1.0.*")>
<Assembly: AssemblyVersion("1.0.0.0")>
<Assembly: AssemblyFileVersion("1.0.0.0")>

View File

@ -0,0 +1,62 @@
'------------------------------------------------------------------------------
' <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 On
Option Explicit On
Namespace My.Resources
'This class was auto-generated by the StronglyTypedResourceBuilder
'class via a tool like ResGen or Visual Studio.
'To add or remove a member, edit your .ResX file then rerun ResGen
'with the /str option, or rebuild your VS project.
'''<summary>
''' A strongly-typed resource class, for looking up localized strings, etc.
'''</summary>
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0"), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.Microsoft.VisualBasic.HideModuleNameAttribute()> _
Friend Module Resources
Private resourceMan As Global.System.Resources.ResourceManager
Private resourceCulture As Global.System.Globalization.CultureInfo
'''<summary>
''' Returns the cached ResourceManager instance used by this class.
'''</summary>
<Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Friend ReadOnly Property ResourceManager() As Global.System.Resources.ResourceManager
Get
If Object.ReferenceEquals(resourceMan, Nothing) Then
Dim temp As Global.System.Resources.ResourceManager = New Global.System.Resources.ResourceManager("LockChecker.Resources", GetType(Resources).Assembly)
resourceMan = temp
End If
Return resourceMan
End Get
End Property
'''<summary>
''' Overrides the current thread's CurrentUICulture property for all
''' resource lookups using this strongly typed resource class.
'''</summary>
<Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Friend Property Culture() As Global.System.Globalization.CultureInfo
Get
Return resourceCulture
End Get
Set(ByVal value As Global.System.Globalization.CultureInfo)
resourceCulture = value
End Set
End Property
End Module
End Namespace

View File

@ -0,0 +1,117 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -0,0 +1,73 @@
'------------------------------------------------------------------------------
' <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 On
Option Explicit On
Namespace My
<Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0"), _
Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Partial Friend NotInheritable Class MySettings
Inherits Global.System.Configuration.ApplicationSettingsBase
Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings), MySettings)
#Region "My.Settings Auto-Save Functionality"
#If _MyType = "WindowsForms" Then
Private Shared addedHandler As Boolean
Private Shared addedHandlerLockObject As New Object
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Private Shared Sub AutoSaveSettings(ByVal sender As Global.System.Object, ByVal e As Global.System.EventArgs)
If My.Application.SaveMySettingsOnExit Then
My.Settings.Save()
End If
End Sub
#End If
#End Region
Public Shared ReadOnly Property [Default]() As MySettings
Get
#If _MyType = "WindowsForms" Then
If Not addedHandler Then
SyncLock addedHandlerLockObject
If Not addedHandler Then
AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings
addedHandler = True
End If
End SyncLock
End If
#End If
Return defaultInstance
End Get
End Property
End Class
End Namespace
Namespace My
<Global.Microsoft.VisualBasic.HideModuleNameAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute()> _
Friend Module MySettingsProperty
<Global.System.ComponentModel.Design.HelpKeywordAttribute("My.Settings")> _
Friend ReadOnly Property Settings() As Global.LockChecker.My.MySettings
Get
Return Global.LockChecker.My.MySettings.Default
End Get
End Property
End Module
End Namespace

View File

@ -0,0 +1,7 @@
<?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)" UseMySettingsClassName="true">
<Profiles>
<Profile Name="(Default)" />
</Profiles>
<Settings />
</SettingsFile>

View File

@ -1,5 +1,5 @@
Imports System.Reflection.Assembly
Imports System.Windows.Forms
Public Class RDP
Private rdpFilePath As String
@ -67,16 +67,45 @@ Public Class RDP
'Define temp files to delete
Dim FilesToDelete As List(Of String) = New List(Of String)(New String() {wxsPath, wixobjPath, wixpdbPath})
Dim LockCheck As New LockChecker.LockChecker()
Dim FileLocked As String
Dim SkipFile As Boolean = False
'Check if rdp file is already in TEMP folder
If rdpParentFolder = TempPath Then rdpInTemp = True
'if RDP file not in temp, copy to temp
If Not rdpInTemp Then
My.Computer.FileSystem.CopyFile(rdpFilePath, rdpTempPath, True)
FileLocked = LockCheck.CheckLock(rdpTempPath)
While Not (FileLocked = "No locks")
If (MessageBox.Show("The file " + rdpTempPath + " is currently locked. Lock information:" + FileLocked + vbNewLine + "Do you want to try again?", "File Locked", MessageBoxButtons.YesNo) = DialogResult.Yes) Then
FileLocked = LockCheck.CheckLock(rdpTempPath)
Else
MessageBox.Show("The following file will not be deleted:" + vbNewLine + rdpTempPath)
SkipFile = True
FileLocked = "No locks"
End If
End While
If Not (SkipFile) Then
My.Computer.FileSystem.CopyFile(rdpFilePath, rdpTempPath, True)
End If
FilesToDelete.Add(rdpTempPath)
If hasIcon Then
My.Computer.FileSystem.CopyFile(IconFilePath, icoTempPath, True)
FileLocked = LockCheck.CheckLock(icoTempPath)
While Not (FileLocked = "No locks")
If (MessageBox.Show("The file " + icoTempPath + " is currently locked. Lock information:" + FileLocked + vbNewLine + "Do you want to try again?", "File Locked", MessageBoxButtons.YesNo) = DialogResult.Yes) Then
FileLocked = LockCheck.CheckLock(icoTempPath)
Else
MessageBox.Show("The following file will not be deleted:" + vbNewLine + icoTempPath)
SkipFile = True
FileLocked = "No locks"
End If
End While
If Not (SkipFile) Then
My.Computer.FileSystem.CopyFile(IconFilePath, icoTempPath, True)
End If
FilesToDelete.Add(icoTempPath)
End If
@ -95,7 +124,21 @@ Public Class RDP
'If Not LightExitCode = 0 Then Exit Sub
'Move MSI file to destination and delete temp files
My.Computer.FileSystem.MoveFile(msiPath, DestinationPath, True)
FileLocked = LockCheck.CheckLock(DestinationPath)
While Not (FileLocked = "No locks")
If (MessageBox.Show("The file " + DestinationPath + " is currently locked. Lock information:" + FileLocked + vbNewLine + "Do you want to try again?", "File Locked", MessageBoxButtons.YesNo) = DialogResult.Yes) Then
FileLocked = LockCheck.CheckLock(DestinationPath)
Else
MessageBox.Show("The following file will not be deleted:" + vbNewLine + DestinationPath)
SkipFile = True
FileLocked = "No locks"
End If
End While
If Not (SkipFile) Then
My.Computer.FileSystem.MoveFile(msiPath, DestinationPath, True)
End If
DeleteFiles(FilesToDelete)
End Sub
@ -122,7 +165,22 @@ Public Class RDP
Private Sub DeleteFiles(FilesArray As List(Of String))
For Each dFile In FilesArray
If My.Computer.FileSystem.FileExists(dFile) Then My.Computer.FileSystem.DeleteFile(dFile)
Dim LockCheck As New LockChecker.LockChecker()
Dim FileLocked As String
Dim SkipFile As Boolean = False
FileLocked = LockCheck.CheckLock(dFile)
While Not (FileLocked = "No locks")
If (MessageBox.Show("The file " + dFile + " is currently locked. Lock information:" + FileLocked + vbNewLine + "Do you want to try again?", "File Locked", MessageBoxButtons.YesNo) = DialogResult.Yes) Then
FileLocked = LockCheck.CheckLock(dFile)
Else
MessageBox.Show("The following file will not be deleted:" + vbNewLine + dFile)
SkipFile = True
FileLocked = "No locks"
End If
End While
If Not (SkipFile) Then
If My.Computer.FileSystem.FileExists(dFile) Then My.Computer.FileSystem.DeleteFile(dFile)
End If
Next
End Sub

View File

@ -46,6 +46,7 @@
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Data" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
@ -99,6 +100,12 @@
<LastGenOutput>Settings.Designer.vb</LastGenOutput>
</None>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\LockChecker\LockChecker.vbproj">
<Project>{029c010d-728b-4b87-b54a-08b2bbf49bd7}</Project>
<Name>LockChecker</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.VisualBasic.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.

View File

@ -1,4 +1,7 @@
Public Class RDPFile
Imports System.Windows.Forms
Imports LockChecker
Public Class RDPFile
Public administrative_session As Integer = 0
Public allow_desktop_composition As Integer = 0
Public allow_font_smoothing As Integer = 0
@ -76,7 +79,23 @@
Public winposstr As String = "0,3,0,0,800,600"
Public Sub SaveRDPfile(FilePath As String, Optional SaveDefaultSettings As Boolean = False)
My.Computer.FileSystem.WriteAllText(FilePath, GetRDPstring(SaveDefaultSettings), False)
Dim LockCheck As New LockChecker.LockChecker()
Dim FileLocked As String
Dim SkipFile As Boolean = False
FileLocked = LockCheck.CheckLock(FilePath)
While Not (FileLocked = "No locks")
If (MessageBox.Show("The file " + FilePath + " is currently locked. Lock information:" + FileLocked + vbNewLine + "Do you want to try again?", "File Locked", MessageBoxButtons.YesNo) = DialogResult.Yes) Then
FileLocked = LockCheck.CheckLock(FilePath)
Else
MessageBox.Show("The following file will not be copied:" + vbNewLine + FilePath)
SkipFile = True
FileLocked = "No locks"
End If
End While
If Not (SkipFile) Then
My.Computer.FileSystem.WriteAllText(FilePath, GetRDPstring(SaveDefaultSettings), False)
End If
End Sub
Public Function GetRDPstring(Optional SaveDefaultSettings As Boolean = False)

View File

@ -46,6 +46,7 @@
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Data" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
@ -100,6 +101,12 @@
<LastGenOutput>Settings.Designer.vb</LastGenOutput>
</None>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\LockChecker\LockChecker.vbproj">
<Project>{029C010D-728B-4B87-B54A-08B2BBF49BD7}</Project>
<Name>LockChecker</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.VisualBasic.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.

View File

@ -100,11 +100,27 @@ Public Class RDPSign
End If
If CreateBackup Then
Dim BackupFile = System.IO.Path.GetDirectoryName(RDPFileLocation) & "\" & System.IO.Path.GetFileNameWithoutExtension(RDPFileLocation) & "-Unsigned.rdp"
System.IO.File.Copy(RDPFileLocation, BackupFile, True) 'backup file with overwrite
Dim LockCheck As New LockChecker.LockChecker()
Dim FileLocked As String
Dim SkipFile As Boolean = False
FileLocked = LockCheck.CheckLock(BackupFile)
While Not (FileLocked = "No locks")
If (MessageBox.Show("The file " + BackupFile + " is currently locked. Lock information:" + FileLocked + vbNewLine + "Do you want to try again?", "File Locked", MessageBoxButtons.YesNo) = DialogResult.Yes) Then
FileLocked = LockCheck.CheckLock(BackupFile)
Else
MessageBox.Show("The following file will not be copied:" + vbNewLine + BackupFile)
SkipFile = True
FileLocked = "No locks"
End If
End While
If Not (SkipFile) Then
System.IO.File.Copy(RDPFileLocation, BackupFile, True) 'backup file with overwrite
End If
End If
'If we get here, we should be good to run the command to sign the RDP file.
Dim Command As String = GetSysDir() & "\rdpsign.exe"
'If we get here, we should be good to run the command to sign the RDP file.
Dim Command As String = GetSysDir() & "\rdpsign.exe"
If My.Computer.FileSystem.FileExists(Command) Then
Dim Arguments As String
Dim FileVersionInfo As FileVersionInfo = FileVersionInfo.GetVersionInfo(Command)

View File

@ -103,5 +103,11 @@
<LastGenOutput>Settings.Designer.vb</LastGenOutput>
</None>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\LockChecker\LockChecker.vbproj">
<Project>{029c010d-728b-4b87-b54a-08b2bbf49bd7}</Project>
<Name>LockChecker</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.VisualBasic.targets" />
</Project>

View File

@ -24,6 +24,8 @@ Project("{F184B08F-C81C-45F6-A57F-5ABD9991F28F}") = "RDPFileLib", "..\RDPFileLib
EndProject
Project("{F184B08F-C81C-45F6-A57F-5ABD9991F28F}") = "RDPSign", "..\RDPSign\RDPSign.vbproj", "{57DABB69-B1D3-445F-91E7-B0412ABAC218}"
EndProject
Project("{F184B08F-C81C-45F6-A57F-5ABD9991F28F}") = "LockChecker", "..\LockChecker\LockChecker.vbproj", "{029C010D-728B-4B87-B54A-08B2BBF49BD7}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@ -54,6 +56,10 @@ Global
{57DABB69-B1D3-445F-91E7-B0412ABAC218}.Debug|Any CPU.Build.0 = Debug|Any CPU
{57DABB69-B1D3-445F-91E7-B0412ABAC218}.Release|Any CPU.ActiveCfg = Release|Any CPU
{57DABB69-B1D3-445F-91E7-B0412ABAC218}.Release|Any CPU.Build.0 = Release|Any CPU
{029C010D-728B-4B87-B54A-08B2BBF49BD7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{029C010D-728B-4B87-B54A-08B2BBF49BD7}.Debug|Any CPU.Build.0 = Debug|Any CPU
{029C010D-728B-4B87-B54A-08B2BBF49BD7}.Release|Any CPU.ActiveCfg = Release|Any CPU
{029C010D-728B-4B87-B54A-08B2BBF49BD7}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

View File

@ -268,10 +268,18 @@
<WCFMetadata Include="Service References\" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\LockChecker\LockChecker.vbproj">
<Project>{029c010d-728b-4b87-b54a-08b2bbf49bd7}</Project>
<Name>LockChecker</Name>
</ProjectReference>
<ProjectReference Include="..\RDP2MSILib\RDP2MSILib.vbproj">
<Project>{e1cb5f9c-230f-4967-8f19-335f8e4a4906}</Project>
<Name>RDP2MSILib</Name>
</ProjectReference>
<ProjectReference Include="..\RDP2MSI\RDP2MSI.vbproj">
<Project>{1001a958-40db-4444-9cd7-09d1188072d1}</Project>
<Name>RDP2MSI</Name>
</ProjectReference>
<ProjectReference Include="..\RDPFileLib\RDPFileLib.vbproj">
<Project>{258307d5-a407-4622-bf1a-bdca8e3d2faa}</Project>
<Name>RDPFileLib</Name>

View File

@ -1,5 +1,4 @@
Imports System.Text.RegularExpressions
Imports RemoteAppLib
Module RemoteAppFunction
@ -99,7 +98,23 @@ Module RemoteAppFunction
Public Sub DeleteFiles(FilesArray As ArrayList)
For Each dFile In FilesArray
If My.Computer.FileSystem.FileExists(dFile) Then My.Computer.FileSystem.DeleteFile(dFile)
Dim LockCheck As New LockChecker.LockChecker()
Dim FileLocked As String
Dim SkipFile As Boolean = False
FileLocked = LockCheck.CheckLock(dFile)
While Not (FileLocked = "No locks")
If (MessageBox.Show("The file " + dFile + " is currently locked. Lock information:" + FileLocked + vbNewLine + "Do you want to try again?", "File Locked", MessageBoxButtons.YesNo) = DialogResult.Yes) Then
FileLocked = LockCheck.CheckLock(dFile)
Else
MessageBox.Show("The following file will not be deleted:" + vbNewLine + dFile)
SkipFile = True
FileLocked = "No locks"
End If
End While
If Not (SkipFile) Then
If My.Computer.FileSystem.FileExists(dFile) Then My.Computer.FileSystem.DeleteFile(dFile)
End If
Next
End Sub

View File

@ -1,6 +1,5 @@
Imports System.Reflection.Assembly
Public Class RemoteAppCollection
Public Class RemoteAppCollection
Inherits System.Collections.CollectionBase
Public Sub Add(RemoteApp As RemoteApp)