Imports DigitalData.Modules.Logging Imports DigitalData.Modules.ZooFlow.Base Imports DigitalData.Modules.Language.DateTimeEx Imports System.IO Imports System.Text Imports System.Timers Namespace DocumentResultList Public Class Opener Inherits BaseClass Private WithEvents FileOpenTimer As New Timer ' TODO: Hashes for checking if the opened file was modified externally Private HashOriginalFile As String = Nothing Private HashOpenedFile As String = Nothing Private OpenFiles As New Dictionary(Of Integer, Document) Public Event ProcessEnded As EventHandler(Of Document) Public Sub New(pLogConfig As LogConfig) MyBase.New(pLogConfig) End Sub Public Function OpenDocument(pDocument As Document) As Boolean Dim oProcessId As Integer = Nothing If pDocument.FullPath Is Nothing OrElse pDocument.FullPath.Trim = String.Empty Then oProcessId = OpenFileFromPath(pDocument) ElseIf pDocument.Extension IsNot Nothing AndAlso pDocument.Contents IsNot Nothing Then oProcessId = OpenFileFromByteArry(pDocument) End If If IsNothing(oProcessId) Then Logger.Warn("Process Id was empty. Returning false.") Return False End If OpenFiles.Add(oProcessId, pDocument) Return True End Function Private Function OpenFileFromByteArry(pDocument As Document) As Integer Try ' TODO: Open file from temp folder Dim oTempPath = Path.Combine(Path.GetTempPath(), Constants.TEMP_PATH_SUBFOLDER) Dim oDirectory = Directory.CreateDirectory(oTempPath) Dim oFileName = $"{pDocument.Id}-{Now.UnixTimestamp}.{pDocument.Extension}" Dim oFilePath = Path.Combine(oTempPath, oFileName) Using oMemoryStream As New MemoryStream(pDocument.Contents) Using oStreamWriter As New StreamWriter(oFilePath, append:=False, Encoding.UTF8) oMemoryStream.CopyTo(oMemoryStream) End Using End Using Dim oProcess = OpenFile(oFilePath) Return oProcess.Id Catch ex As Exception Logger.Error(ex) Return Nothing End Try End Function Private Function OpenFileFromPath(pDocument As Document) As Integer Try Dim oProcess = OpenFile(pDocument.FullPath) Return oProcess.Id Catch ex As Exception Logger.Error(ex) Return Nothing End Try End Function Private Function OpenFile(pFilePath As String) As Process Dim oProcess = Process.Start(New ProcessStartInfo With { .FileName = pFilePath }) Return oProcess End Function Private Sub FileOpenTimer_Elapsed() Handles FileOpenTimer.Elapsed Try Dim oIds = Process.GetProcesses(). Select(Function(process) process.Id). ToList() Dim oNewFileOpenList As New Dictionary(Of Integer, Document) For Each oOpenFile In OpenFiles If oIds.Contains(oOpenFile.Key) Then oNewFileOpenList.Add(oOpenFile.Key, oOpenFile.Value) End If Next If oNewFileOpenList.Count < OpenFiles.Count Then Dim oClosedFiles = OpenFiles. Except(oNewFileOpenList). ToList() If oClosedFiles.Count = 1 Then Dim oOpenFile = oClosedFiles.First() RaiseEvent ProcessEnded(Me, oOpenFile.Value) End If OpenFiles = oNewFileOpenList End If Catch ex As Exception Logger.Error(ex) End Try End Sub End Class End Namespace