From 6f33261101610bb43cd044664bb1c58be8977999 Mon Sep 17 00:00:00 2001 From: Jonathan Jenne Date: Tue, 5 Sep 2023 10:47:37 +0200 Subject: [PATCH] Fix filesystem refs --- Base/Base.vbproj | 3 - Base/FileContainer/DocumentObject.vb | 18 - Base/FileContainer/FileContainer.vb | 193 ---- Base/FileContainer/FileContainerInner.vb | 23 - Base/FileWatcher/FileWatcher.vb | 3 +- Config/Config.vbproj | 7 +- Config/ConfigManager.vb | 8 +- Config/ConfigUtils.vb | 7 +- EDMIAPI/EDMI.API.vbproj | 4 - EDMIAPI/Helpers.vb | 7 +- EDMIAPI/Modules/BaseMethod.vb | 7 +- EDMIAPI/Modules/IDB/NewFile.vb | 1 - Interfaces/ZUGFeRDInterface/PDFEmbeds.vb | 60 ++ Jobs/Jobs.vbproj | 4 - Jobs/ZUGFeRD/FileFunctions.vb | 5 +- Jobs/ZUGFeRD/ImportZUGFeRDFiles.vb | 21 +- Logging.Test/ConstructorUnitTest.vb | 32 +- Logging.Test/Logging.Test.vbproj | 9 + Logging.Test/packages.config | 3 + Messaging/Email2.vb | 6 +- Messaging/Mail/MailSession.vb | 4 +- Messaging/Messaging.vbproj | 4 - Windream/Windream.vb | 9 +- Windream/Windream.vbproj | 7 +- Windream/Windream_alt.vb | 1214 ---------------------- 25 files changed, 132 insertions(+), 1527 deletions(-) delete mode 100644 Base/FileContainer/DocumentObject.vb delete mode 100644 Base/FileContainer/FileContainer.vb delete mode 100644 Base/FileContainer/FileContainerInner.vb delete mode 100644 Windream/Windream_alt.vb diff --git a/Base/Base.vbproj b/Base/Base.vbproj index 170d8af0..2700f98c 100644 --- a/Base/Base.vbproj +++ b/Base/Base.vbproj @@ -83,9 +83,6 @@ - - - diff --git a/Base/FileContainer/DocumentObject.vb b/Base/FileContainer/DocumentObject.vb deleted file mode 100644 index c9da13f0..00000000 --- a/Base/FileContainer/DocumentObject.vb +++ /dev/null @@ -1,18 +0,0 @@ -Imports System.Runtime.Serialization - - -Public Class DocumentObject - - - Public ReadOnly FileName As String - - Public ReadOnly ContainerId As String - - Public ReadOnly DocumentId As Int64 - - Public Sub New(ContainerId As String, DocumentId As Int64, FileName As String) - Me.ContainerId = ContainerId - Me.DocumentId = DocumentId - Me.FileName = FileName - End Sub -End Class diff --git a/Base/FileContainer/FileContainer.vb b/Base/FileContainer/FileContainer.vb deleted file mode 100644 index 54d6ce4a..00000000 --- a/Base/FileContainer/FileContainer.vb +++ /dev/null @@ -1,193 +0,0 @@ -Imports System.IO -Imports DigitalData.Modules.Logging -Imports DigitalData.Modules.Encryption -Imports ProtoBuf - -''' FileContainer -''' 0.0.0.2 -''' 21.11.2018 -''' -''' File Container for securely saving files -''' -''' -''' NLog, >= 4.5.8 -''' -''' -''' LogConfig, DigitalData.Module.Logging.LogConfig -''' A LogConfig object -''' Password, String -''' The Password to Encrypt -''' Path, String -''' The Path to save/load the container -''' -''' -''' dim oContainer = Container.Create(logConfig, "pass", "E:\some.container") -''' dim oContainer = Container.Load(logConfig, "pass", "E:\some.container") -''' -''' dim oContainer = new Container(logConfig, "pass", "E:\some.container") -''' oContainer.Save() -''' -''' dim oContainer = new Container(logConfig, "pass", "E:\some.container") -''' oContainer.Contents = oSomeData -''' oContainer.Save() -''' -''' dim oContainer = new Container(logConfig, "pass", "E:\some.container") -''' oContainer.Load() -''' dim oContents = oContainer.Contents -''' -''' dim oContainer = new Container(logConfig, "pass", "E:\some.container") -''' oContainer.Load() -''' oContainer.Contents = oSomeOtherData -''' oContainer.Save() -''' oContainer.SaveAs("E:\some2.container") -''' -Public Class FileContainer - Private _crypto As Encryption.Encryption - Private _compression As Compression - Private _inner As FileContainerInner - Private _logger As Logger - Private _logConfig As LogConfig - Private _path As String - - Public Property Contents As Byte() - Get - Return _inner.Contents - End Get - Set(value As Byte()) - _inner.Contents = value - End Set - End Property - Public ReadOnly Property ContainerId As String - Get - Return _inner.FileId - End Get - End Property - Public ReadOnly Property CreatedAt As String - Get - Return _inner.CreatedAt - End Get - End Property - Public ReadOnly Property UpdatedAt As String - Get - Return _inner.UpdatedAt - End Get - End Property - - Public Shared Function Create(LogConfig As LogConfig, Password As String) As FileContainer - Dim oContainer = New FileContainer(LogConfig, Password) - Return oContainer - End Function - - Public Shared Function Load(LogConfig As LogConfig, Password As String, Path As String) As FileContainer - Dim oContainer = New FileContainer(LogConfig, Password, Path) - oContainer.Load() - Return oContainer - End Function - - Public Sub New(LogConfig As LogConfig, Password As String) - _logger = LogConfig.GetLogger() - _crypto = New Encryption.Encryption(LogConfig, Password) - _compression = New Compression(LogConfig) - _inner = New FileContainerInner() - End Sub - - Public Sub New(LogConfig As LogConfig, Password As String, Path As String) - MyClass.New(LogConfig, Password) - _path = Path - End Sub - - Public Sub SetFile(Contents As Byte(), FileName As String) - _inner.Contents = Contents - _inner.UpdatedAt = Date.Now - _inner.FileName = FileName - End Sub - - Public Function GetFile() As FileContainerInner - Return _inner - End Function - - Public Sub Save() - If IsNothing(_path) Then - Throw New ArgumentException("Path not set") - End If - - SaveAs(_path) - End Sub - - Public Sub SaveAs(Path As String) - Try - WriteBytesToFile(TransformToBytes(_inner), Path) - Catch ex As Exception - _logger.Error(ex) - Throw ex - End Try - End Sub - - Public Sub Load() - If IsNothing(_path) Then - Throw New ArgumentException("Path not set") - End If - - LoadFrom(_path) - End Sub - - Public Sub LoadFrom(Path As String) - Try - _inner = TransformToObject(ReadBytesFromFile(_path)) - Catch ex As Exception - _logger.Error(ex) - Throw ex - End Try - End Sub - - Private Function TransformToBytes([Object] As FileContainerInner) As Byte() - Dim oBytes = Serialize([Object]) - Dim oCompressed = _compression.Compress(oBytes) - Dim oEncrypted = _crypto.Encrypt(oCompressed) - Return oEncrypted - End Function - - Private Function TransformToObject(Bytes As Byte()) As FileContainerInner - Dim oDecrypted = _crypto.Decrypt(Bytes) - Dim oDecompressed = _compression.Decompress(oDecrypted) - Dim oObject = Deserialize(oDecompressed) - Return oObject - End Function - - Private Function Serialize(InnerData As FileContainerInner) As Byte() - Dim oBinaryData As Byte() - - Using oStream As New MemoryStream - Serializer.Serialize(oStream, InnerData) - oBinaryData = oStream.ToArray() - End Using - - Return oBinaryData - End Function - - Private Function Deserialize(InnerData As Byte()) As FileContainerInner - Dim oObject As FileContainerInner - - Using oStream As New MemoryStream(InnerData) - oObject = Serializer.Deserialize(Of FileContainerInner)(oStream) - End Using - - Return oObject - End Function - - Private Sub WriteBytesToFile(Data As Byte(), FilePath As String) - Using oSourceStream As New FileStream(FilePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None) - oSourceStream.Write(Data, 0, Data.Length) - oSourceStream.Flush() - End Using - End Sub - - Private Function ReadBytesFromFile(FilePath As String) As Byte() - Using oFileStream = New FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.Read, 4096) - Dim oBuffer As Byte() = New Byte(oFileStream.Length - 1) {} - oFileStream.Read(oBuffer, 0, oFileStream.Length) - oFileStream.Close() - Return oBuffer - End Using - End Function -End Class diff --git a/Base/FileContainer/FileContainerInner.vb b/Base/FileContainer/FileContainerInner.vb deleted file mode 100644 index fc787ce0..00000000 --- a/Base/FileContainer/FileContainerInner.vb +++ /dev/null @@ -1,23 +0,0 @@ -Imports ProtoBuf - - - -Public Class FileContainerInner - - Public FileId As String - - Public Contents As Byte() - - Public CreatedAt As DateTime - - Public UpdatedAt As DateTime - - Public FileName As String - - Public Sub New() - FileId = Guid.NewGuid().ToString - CreatedAt = Date.Now - UpdatedAt = Date.Now - End Sub - -End Class \ No newline at end of file diff --git a/Base/FileWatcher/FileWatcher.vb b/Base/FileWatcher/FileWatcher.vb index 6f82047a..45511192 100644 --- a/Base/FileWatcher/FileWatcher.vb +++ b/Base/FileWatcher/FileWatcher.vb @@ -1,6 +1,5 @@ Imports System.IO -Imports DigitalData.Modules.Filesystem -Imports DigitalData.Modules.Filesystem.FileWatcherFilters +Imports DigitalData.Modules.Base.FileWatcherFilters Imports DigitalData.Modules.Logging diff --git a/Config/Config.vbproj b/Config/Config.vbproj index b1152a18..3551eb08 100644 --- a/Config/Config.vbproj +++ b/Config/Config.vbproj @@ -44,6 +44,9 @@ On + + ..\Base\bin\Debug\DigitalData.Modules.Base.dll + ..\packages\NLog.5.0.5\lib\net46\NLog.dll @@ -120,10 +123,6 @@ {8a8f20fc-c46e-41ac-bee7-218366cfff99} Encryption - - {991d0231-4623-496d-8bd0-9ca906029cbc} - Filesystem - {903b2d7d-3b80-4be9-8713-7447b704e1b0} Logging diff --git a/Config/ConfigManager.vb b/Config/ConfigManager.vb index 49cff739..8a6b75f4 100644 --- a/Config/ConfigManager.vb +++ b/Config/ConfigManager.vb @@ -2,8 +2,8 @@ Imports System.Reflection Imports System.Xml.Serialization Imports DigitalData.Modules.Logging -Imports DigitalData.Modules.Encryption Imports DigitalData.Modules.Config.ConfigAttributes +Imports DigitalData.Modules.Base Public Class ConfigManager(Of T) Private Const USER_CONFIG_NAME As String = "UserConfig.xml" @@ -12,7 +12,7 @@ Public Class ConfigManager(Of T) Private ReadOnly _LogConfig As LogConfig Private ReadOnly _Logger As Logger - Private ReadOnly _File As Filesystem.File + Private ReadOnly _File As FilesystemEx Private ReadOnly _UserDirectory As String Private ReadOnly _UserConfigPath As String @@ -104,7 +104,7 @@ Public Class ConfigManager(Of T) Public Sub New(LogConfig As LogConfig, UserConfigPath As String, ComputerConfigPath As String, Optional ApplicationStartupPath As String = "", Optional ForceUserConfig As Boolean = False) _LogConfig = LogConfig _Logger = LogConfig.GetLogger() - _File = New Filesystem.File(_LogConfig) + _File = New FilesystemEx(_LogConfig) _Blueprint = Activator.CreateInstance(Of T) _BlueprintType = _Blueprint.GetType @@ -122,7 +122,7 @@ Public Class ConfigManager(Of T) _ComputerConfigPath = Path.Combine(_ComputerDirectory, COMPUTER_CONFIG_NAME) End If - If ApplicationStartupPath <> String.Empty Then + If ApplicationStartupPath <> String.Empty Then _AppConfigPath = Path.Combine(ApplicationStartupPath, APP_CONFIG_NAME) End If diff --git a/Config/ConfigUtils.vb b/Config/ConfigUtils.vb index c9041ad7..2de1f66b 100644 --- a/Config/ConfigUtils.vb +++ b/Config/ConfigUtils.vb @@ -1,15 +1,16 @@ -Imports DigitalData.Modules.Logging +Imports DigitalData.Modules.Base +Imports DigitalData.Modules.Logging Public Class ConfigUtils Private _Logger As Logger - Private _File As Filesystem.File + Private _File As FilesystemEx Private Const MIGRATE_DIRECTORY As String = "Migrate" Public Sub New(LogConfig As LogConfig) _Logger = LogConfig.GetLogger() - _File = New Filesystem.File(LogConfig) + _File = New FilesystemEx(LogConfig) End Sub Public Function TestMigrationNeeded(TargetDirectory As String) As Boolean diff --git a/EDMIAPI/EDMI.API.vbproj b/EDMIAPI/EDMI.API.vbproj index bd822add..e5ef3373 100644 --- a/EDMIAPI/EDMI.API.vbproj +++ b/EDMIAPI/EDMI.API.vbproj @@ -308,10 +308,6 @@ {eaf0ea75-5fa7-485d-89c7-b2d843b03a96} Database - - {991d0231-4623-496d-8bd0-9ca906029cbc} - Filesystem - {d3c8cfed-d6f6-43a8-9bdf-454145d0352f} Language diff --git a/EDMIAPI/Helpers.vb b/EDMIAPI/Helpers.vb index 65ce1b6d..7a8077b0 100644 --- a/EDMIAPI/Helpers.vb +++ b/EDMIAPI/Helpers.vb @@ -1,16 +1,17 @@ -Imports DigitalData.Modules.EDMI.API.EDMIServiceReference +Imports DigitalData.Modules.Base +Imports DigitalData.Modules.EDMI.API.EDMIServiceReference Imports DigitalData.Modules.Logging Public Class Helpers Private ReadOnly LogConfig As LogConfig Private ReadOnly Logger As Logger - Private ReadOnly FileEx As Filesystem.File + Private ReadOnly FileEx As FilesystemEx Public Sub New(pLogConfig As LogConfig) LogConfig = pLogConfig Logger = pLogConfig.GetLogger() - FileEx = New Filesystem.File(pLogConfig) + FileEx = New FilesystemEx(pLogConfig) End Sub Public Function GetFileProperties(pFilePath As String, pDateImportedAt As Date) As FileProperties diff --git a/EDMIAPI/Modules/BaseMethod.vb b/EDMIAPI/Modules/BaseMethod.vb index 09893e6f..163e8183 100644 --- a/EDMIAPI/Modules/BaseMethod.vb +++ b/EDMIAPI/Modules/BaseMethod.vb @@ -1,4 +1,5 @@ -Imports DigitalData.Modules.EDMI.API.EDMIServiceReference +Imports DigitalData.Modules.Base +Imports DigitalData.Modules.EDMI.API.EDMIServiceReference Imports DigitalData.Modules.Logging Namespace Modules @@ -6,14 +7,14 @@ Namespace Modules Friend ReadOnly LogConfig As LogConfig Friend ReadOnly Logger As Logger Friend ReadOnly Channel As IEDMIServiceChannel - Friend ReadOnly FileEx As Filesystem.File + Friend ReadOnly FileEx As FilesystemEx Friend ReadOnly Helpers As Helpers Public Sub New(pLogConfig As LogConfig, pChannel As IEDMIServiceChannel) LogConfig = pLogConfig Logger = pLogConfig.GetLogger() Channel = pChannel - FileEx = New Filesystem.File(pLogConfig) + FileEx = New FilesystemEx(pLogConfig) Helpers = New Helpers(pLogConfig) End Sub End Class diff --git a/EDMIAPI/Modules/IDB/NewFile.vb b/EDMIAPI/Modules/IDB/NewFile.vb index 0908415e..ce649dc9 100644 --- a/EDMIAPI/Modules/IDB/NewFile.vb +++ b/EDMIAPI/Modules/IDB/NewFile.vb @@ -1,6 +1,5 @@ Imports DigitalData.Modules.EDMI.API.EDMIServiceReference Imports DigitalData.Modules.Logging -Imports DigitalData.Modules.Filesystem Namespace Modules.IDB Public Class NewFile diff --git a/Interfaces/ZUGFeRDInterface/PDFEmbeds.vb b/Interfaces/ZUGFeRDInterface/PDFEmbeds.vb index 2385a93b..169c5a11 100644 --- a/Interfaces/ZUGFeRDInterface/PDFEmbeds.vb +++ b/Interfaces/ZUGFeRDInterface/PDFEmbeds.vb @@ -1,5 +1,7 @@ Imports System.Collections.Generic Imports System.IO +Imports System.Reflection +Imports System.Runtime.Remoting.Messaging Imports DigitalData.Modules.Logging Imports GdPicture14 @@ -91,6 +93,64 @@ Public Class PDFEmbeds End Try End Function + Public Function RemoveEmbeddedFiles(pFilePath As String) As Boolean + Dim oFile As New List(Of EmbeddedFile) + Dim oFileInfo As FileInfo + + Logger.Debug("Removing embedded files from [{0}]", pFilePath) + + Try + oFileInfo = New FileInfo(pFilePath) + + Logger.Debug("Filename: {0}", oFileInfo.Name) + Logger.Debug("Filesize: {0} bytes", oFileInfo.Length) + Logger.Debug("Exists: {0}", oFileInfo.Exists) + Catch ex As Exception + Logger.Warn("File information for [{0}] could not be read!", pFilePath) + Logger.Error(ex) + End Try + + Try + Using oGDPicturePDF As New GdPicturePDF() + If oGDPicturePDF.LoadFromFile(pFilePath, False) <> GdPictureStatus.OK Then + Dim oMessage = String.Format("The file [{0}] can't be loaded. Status: [{1}]", pFilePath, oGDPicturePDF.GetStat().ToString()) + Throw New ApplicationException(oMessage) + End If + + If DoRemove(oGDPicturePDF) = False Then + Dim oMessage = String.Format("Attachments for file [{0}] can't be removed. Status: [{1}]", pFilePath, oGDPicturePDF.GetStat().ToString()) + Throw New ApplicationException(oMessage) + End If + End Using + + Return True + Catch ex As Exception + Logger.Warn("Unexpected Error while Extracting attachments from File [{0}]", pFilePath) + Logger.Error(ex) + Return False + End Try + End Function + + Private Function DoRemove(GDPicturePDF As GdPicturePDF) As Boolean + Dim oStatus As GdPictureStatus + + Dim oEmbeddedFileCount As Integer = GDPicturePDF.GetEmbeddedFileCount() + + If oStatus <> GdPictureStatus.OK Then + Logger.Warn("Embedded files could not be removed. Status: [{0}]", oStatus.ToString) + Return False + End If + + If oEmbeddedFileCount = 0 Then + Return True + End If + + While GDPicturePDF.GetEmbeddedFileCount() > 0 + GDPicturePDF.DeleteEmbeddedFile(0) + End While + + End Function + Private Function DoExtract(GDPicturePDF As GdPicturePDF, pExtensions As List(Of String)) As List(Of EmbeddedFile) Dim oResults As New List(Of EmbeddedFile) Dim oEmbeddedFileCount As Integer = GDPicturePDF.GetEmbeddedFileCount() diff --git a/Jobs/Jobs.vbproj b/Jobs/Jobs.vbproj index d5a85af2..69075b74 100644 --- a/Jobs/Jobs.vbproj +++ b/Jobs/Jobs.vbproj @@ -77,10 +77,6 @@ {eaf0ea75-5fa7-485d-89c7-b2d843b03a96} Database - - {991d0231-4623-496d-8bd0-9ca906029cbc} - Filesystem - {ab6f09bf-e794-4f6a-94bb-c97c0ba84d64} Interfaces diff --git a/Jobs/ZUGFeRD/FileFunctions.vb b/Jobs/ZUGFeRD/FileFunctions.vb index 8328448c..99d69e2e 100644 --- a/Jobs/ZUGFeRD/FileFunctions.vb +++ b/Jobs/ZUGFeRD/FileFunctions.vb @@ -1,6 +1,7 @@ Imports System.Collections.Generic Imports System.IO Imports System.Linq +Imports DigitalData.Modules.Base Imports DigitalData.Modules.Database Imports DigitalData.Modules.Interfaces Imports DigitalData.Modules.Logging @@ -11,13 +12,13 @@ Namespace ZUGFeRD Private ReadOnly _logConfig As LogConfig Private ReadOnly _logger As Logger Private ReadOnly _mssql As MSSQLServer - Private ReadOnly _filesystem As Filesystem.File + Private ReadOnly _filesystem As FilesystemEx Public Sub New(LogConfig As LogConfig, MSSQL As MSSQLServer) _logConfig = LogConfig _logger = _logConfig.GetLogger() _mssql = MSSQL - _filesystem = New Filesystem.File(LogConfig) + _filesystem = New FilesystemEx(LogConfig) End Sub Public Sub MoveFiles( diff --git a/Jobs/ZUGFeRD/ImportZUGFeRDFiles.vb b/Jobs/ZUGFeRD/ImportZUGFeRDFiles.vb index 3bcd31f5..403564e2 100644 --- a/Jobs/ZUGFeRD/ImportZUGFeRDFiles.vb +++ b/Jobs/ZUGFeRD/ImportZUGFeRDFiles.vb @@ -32,7 +32,7 @@ Public Class ImportZUGFeRDFiles Private ReadOnly _logger As Logger Private ReadOnly _logConfig As LogConfig - Private ReadOnly _filesystem As Filesystem.File + Private ReadOnly _filesystem As FilesystemEx Private ReadOnly _mssql As MSSQLServer Private ReadOnly _email As ZUGFeRD.EmailFunctions Private ReadOnly _file As ZUGFeRD.FileFunctions @@ -58,7 +58,7 @@ Public Class ImportZUGFeRDFiles Public Sub New(LogConfig As LogConfig, Optional MSSQL As MSSQLServer = Nothing) _logConfig = LogConfig _logger = LogConfig.GetLogger() - _filesystem = New Filesystem.File(_logConfig) + _filesystem = New FilesystemEx(_logConfig) _mssql = MSSQL _email = New ZUGFeRD.EmailFunctions(LogConfig, _mssql) _file = New ZUGFeRD.FileFunctions(LogConfig, _mssql) @@ -82,11 +82,10 @@ Public Class ImportZUGFeRDFiles _EmailOutAccountId = oArgs.EmailOutProfileId - Dim oOptions As New ZUGFeRDInterface.ZugferdOptions() With { + _zugferd = New ZUGFeRDInterface(_logConfig, _gdpictureLicenseKey, New ZUGFeRDInterface.ZugferdOptions() With { .AllowFacturX_Filename = oArgs.AllowFacturX, .AllowXRechnung_Filename = oArgs.AllowXRechnung - } - _zugferd = New ZUGFeRDInterface(_logConfig, _gdpictureLicenseKey, oOptions) + }) _logger.Debug("Starting Job {0}", [GetType].Name) @@ -523,8 +522,6 @@ Public Class ImportZUGFeRDFiles End Try End Sub - - #Region "=== REFACTOR" Private Function ProcessFileGroup(oMessageId As String, pFiles As List(Of FileInfo), oConnections As DatabaseConnections, pArgs As WorkerArgs) Dim oMissingProperties = New List(Of String) @@ -1069,14 +1066,14 @@ Public Class ImportZUGFeRDFiles End If End Sub - Private Function CreateMD5(ByVal Filename As String) As String + Private Function CreateMD5(pFilename As String) As String Try Dim oMD5 As New MD5CryptoServiceProvider Dim oHash As Byte() Dim oHashString As String Dim oResult As String = "" - Using oFileStream As New FileStream(Filename, FileMode.Open, FileAccess.Read, FileShare.Read, 8192) + Using oFileStream As New FileStream(pFilename, FileMode.Open, FileAccess.Read, FileShare.Read, 8192) oHash = oMD5.ComputeHash(oFileStream) oHashString = BitConverter.ToString(oHash) End Using @@ -1236,11 +1233,11 @@ Public Class ImportZUGFeRDFiles Return oEmailData End Function - Private Sub AddRejectedState(oMessageID As String, oTitle As String, oTitle1 As String, oComment As String, Transaction As SqlTransaction) + Private Sub AddRejectedState(pMessageID As String, pTitle As String, pTitle1 As String, pComment As String, pTransaction As SqlTransaction) Try 'PRCUST_ADD_HISTORY_STATE: @MessageID VARCHAR(250), @TITLE1 VARCHAR(250), @TITLE2 VARCHAR(250) - Dim oSQL = $"EXEC PRCUST_ADD_HISTORY_STATE '{oMessageID}','{oTitle}','{oTitle1}','{oComment.Replace("'", "''")}'" - _mssql.ExecuteNonQuery(oSQL, Transaction) + Dim oSQL = $"EXEC PRCUST_ADD_HISTORY_STATE '{pMessageID}','{pTitle}','{pTitle1}','{pComment.Replace("'", "''")}'" + _mssql.ExecuteNonQuery(oSQL, pTransaction) Catch ex As Exception _logger.Error(ex) End Try diff --git a/Logging.Test/ConstructorUnitTest.vb b/Logging.Test/ConstructorUnitTest.vb index 3a790cfd..c45f1cbb 100644 --- a/Logging.Test/ConstructorUnitTest.vb +++ b/Logging.Test/ConstructorUnitTest.vb @@ -1,46 +1,46 @@ -Imports System.Text -Imports System.IO -Imports Microsoft.VisualStudio.TestTools.UnitTesting -Imports DigitalData.Modules.Logging +Imports System.IO +Imports FluentAssertions ''' ''' Test creating the log path in various configurations ''' Public Class ConstructorUnitTest - Private Shared _currentDirectoryLogPath = Path.Combine(Directory.GetCurrentDirectory(), "Log") - Private Shared _appdataDirectoryLogPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Digital Data", "Modules.Logging", "Log") - Private Shared _customDirectoryLogPath = Path.Combine(Directory.GetCurrentDirectory(), "CustomLogFolder") - Private Shared _restrictedDirectoryLogPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "ShouldNotBeCreated") - Private Shared _nonsenseDirectoryLogPath = "X:\FOO\BAR\BAZ\QUUX" + Private Shared ReadOnly _currentDirectoryLogPath = Path.Combine(Directory.GetCurrentDirectory(), "Log") + Private Shared ReadOnly _appdataDirectoryLogPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Digital Data", "Modules.Logging.Test", "Log") + Private Shared ReadOnly _customDirectoryLogPath = Path.Combine(Directory.GetCurrentDirectory(), "CustomLogFolder") + Private Shared ReadOnly _restrictedDirectoryLogPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "ShouldNotBeCreated") + Private Shared ReadOnly _nonsenseDirectoryLogPath = "X:\DOES\NOT\EVER\EXIST" Public Sub TestConstructorCurrentDirectory() - Assert.ThrowsException(Of ArgumentException)(Sub() - Dim oLogConfig As New LogConfig(LogConfig.PathType.Temp) - End Sub) + Dim oLogConfig As New LogConfig(LogConfig.PathType.Temp) + Dim oTempPath = Path.GetTempPath + oLogConfig.LogDirectory.Should.Be(oTempPath) End Sub Public Sub TestConstructorApplicationDirectory() Dim oLogConfig As New LogConfig(LogConfig.PathType.AppData, Nothing, Nothing, "Digital Data", "Modules.Logging") - Assert.AreEqual(_appdataDirectoryLogPath, oLogConfig.LogDirectory) + oLogConfig.LogDirectory.Should.Be(_appdataDirectoryLogPath) End Sub Public Sub TestConstructorCustomDirectory() Dim oLogConfig As New LogConfig(LogConfig.PathType.CustomPath, _customDirectoryLogPath) - Assert.AreEqual(_customDirectoryLogPath, oLogConfig.LogDirectory) + oLogConfig.LogDirectory.Should.Be(_customDirectoryLogPath) End Sub Public Sub TestConstructorRestrictedDirectory() Dim oLogConfig As New LogConfig(LogConfig.PathType.CustomPath, _restrictedDirectoryLogPath) + Dim oTempPath = Path.GetTempPath - Assert.AreEqual(Path.GetTempPath, oLogConfig.LogDirectory) + oLogConfig.LogDirectory.Should.Be(oTempPath) End Sub Public Sub TestConstructorNonsenseDirectory() Dim oLogConfig As New LogConfig(LogConfig.PathType.CustomPath, _nonsenseDirectoryLogPath) + Dim oTempPath = Path.GetTempPath - Assert.AreEqual(Path.GetTempPath, oLogConfig.LogDirectory) + oLogConfig.LogDirectory.Should.Be(oTempPath) End Sub Public Shared Sub Cleanup() diff --git a/Logging.Test/Logging.Test.vbproj b/Logging.Test/Logging.Test.vbproj index 8e5cd852..fd2b9608 100644 --- a/Logging.Test/Logging.Test.vbproj +++ b/Logging.Test/Logging.Test.vbproj @@ -52,6 +52,9 @@ On + + ..\packages\FluentAssertions.6.12.0\lib\netstandard2.0\FluentAssertions.dll + ..\packages\MSTest.TestFramework.2.1.2\lib\net45\Microsoft.VisualStudio.TestPlatform.TestFramework.dll @@ -60,6 +63,12 @@ + + ..\packages\System.Runtime.CompilerServices.Unsafe.4.5.0\lib\netstandard2.0\System.Runtime.CompilerServices.Unsafe.dll + + + ..\packages\System.Threading.Tasks.Extensions.4.5.0\lib\netstandard2.0\System.Threading.Tasks.Extensions.dll + diff --git a/Logging.Test/packages.config b/Logging.Test/packages.config index 371adee0..98ee6605 100644 --- a/Logging.Test/packages.config +++ b/Logging.Test/packages.config @@ -1,5 +1,8 @@  + + + \ No newline at end of file diff --git a/Messaging/Email2.vb b/Messaging/Email2.vb index 40072604..a03189dd 100644 --- a/Messaging/Email2.vb +++ b/Messaging/Email2.vb @@ -1,6 +1,6 @@ Imports System.IO Imports DigitalData.Modules.Logging -Imports DigitalData.Modules.Filesystem +Imports DigitalData.Modules.Base Imports Limilabs.Mail Imports Limilabs.Mail.MIME Imports Limilabs.Mail.MSG @@ -11,7 +11,7 @@ Public Class Email2 Private ReadOnly Logger As Logger Private ReadOnly LoggerMail As Logger Private ReadOnly LogConfig As LogConfig - Private ReadOnly FileEx As Filesystem.File + Private ReadOnly FileEx As FilesystemEx Private ReadOnly MailBuilder As New MailBuilder() Private ReadOnly TempFiles As New List(Of String) @@ -21,7 +21,7 @@ Public Class Email2 LogConfig = pLogConfig Logger = pLogConfig.GetLogger() LoggerMail = pLogConfig.GetLogger("Limilabs.Mail") - FileEx = New Filesystem.File(pLogConfig) + FileEx = New FilesystemEx(pLogConfig) ' Turn on internal Mail.dll logging Limilabs.Mail.Log.Enabled = True diff --git a/Messaging/Mail/MailSession.vb b/Messaging/Mail/MailSession.vb index fafa086e..1ac583e5 100644 --- a/Messaging/Mail/MailSession.vb +++ b/Messaging/Mail/MailSession.vb @@ -244,8 +244,8 @@ Namespace Mail End Try End Function - Public Async Function TestLogin(pServer As String, pPort As Integer, pUser As String, pPassword As String, pAuthType As String, pOptions As MailSessionOptions) As Task(Of Boolean) - Dim oInfo = Await ConnectToServer(pServer, pPort, pUser, pPassword, pAuthType, pOptions) + Public Function TestLogin(pServer As String, pPort As Integer, pUser As String, pPassword As String, pAuthType As String, pOptions As MailSessionOptions) As Boolean + Dim oInfo = ConnectToServer(pServer, pPort, pUser, pPassword, pAuthType, pOptions) If oInfo.Connected Then If DisconnectFromServer() Then Return True diff --git a/Messaging/Messaging.vbproj b/Messaging/Messaging.vbproj index 59d8ef79..46292b10 100644 --- a/Messaging/Messaging.vbproj +++ b/Messaging/Messaging.vbproj @@ -140,10 +140,6 @@ {6ea0c51f-c2b1-4462-8198-3de0b32b74f8} Base - - {991d0231-4623-496d-8bd0-9ca906029cbc} - Filesystem - {d3c8cfed-d6f6-43a8-9bdf-454145d0352f} Language diff --git a/Windream/Windream.vb b/Windream/Windream.vb index 93bb1785..3317bf30 100644 --- a/Windream/Windream.vb +++ b/Windream/Windream.vb @@ -13,6 +13,7 @@ Imports WMOTOOLLib Imports DigitalData.Modules.Logging Imports DigitalData.Modules.Language +Imports DigitalData.Modules.Base ''' Windream ''' 0.0.0.2 @@ -97,7 +98,7 @@ Public Class Windream #Region "Private Properties" Private ReadOnly _logger As Logger Private ReadOnly _logConfig As LogConfig - Private ReadOnly _fileSystem As Filesystem.File + Private ReadOnly _fileSystem As FilesystemEx Private ReadOnly _sessionDomain As String Private ReadOnly _sessionPassword As String Private ReadOnly _sessionUsername As String @@ -149,7 +150,7 @@ Public Class Windream ' Create logger and save LogFactory for dependent classes _logger = LogConfig.GetLogger() _logConfig = LogConfig - _fileSystem = New Filesystem.File(LogConfig) + _fileSystem = New FilesystemEx(LogConfig) ' Create a session Dim oSession As IWMSession2 = NewSession(SessionServerName, SessionUserName, SessionPassword, SessionDomain) @@ -584,9 +585,7 @@ Public Class Windream ''' changes the archive end date ''' ''' WM Filepath - ''' number/count of period (if - ''' date_unity (d,m,y or day(s),month(s),years(s) - ''' dateFrom_value + ''' number/count of period (if ''' Returns true when date was set, false if not ''' Public Function NewLifecycle_PeriodTEST(ByVal wmfilepath As String, ByVal oArchUntil As String) diff --git a/Windream/Windream.vbproj b/Windream/Windream.vbproj index 21e62780..a2b67d1d 100644 --- a/Windream/Windream.vbproj +++ b/Windream/Windream.vbproj @@ -110,7 +110,6 @@ Settings.settings True - @@ -134,9 +133,9 @@ - - {991d0231-4623-496d-8bd0-9ca906029cbc} - Filesystem + + {6EA0C51F-C2B1-4462-8198-3DE0B32B74F8} + Base {d3c8cfed-d6f6-43a8-9bdf-454145d0352f} diff --git a/Windream/Windream_alt.vb b/Windream/Windream_alt.vb deleted file mode 100644 index 14e77697..00000000 --- a/Windream/Windream_alt.vb +++ /dev/null @@ -1,1214 +0,0 @@ -Imports WINDREAMLib -Imports WINDREAMLib.WMCOMEvent -Imports WINDREAMLib.WMEntity -Imports WINDREAMLib.WMObjectEditMode -Imports WINDREAMLib.WMSearchOperator -Imports WINDREAMLib.WMSearchRelation -Imports WMOBRWSLib -Imports WMOSRCHLib -Imports WMCNNCTDLLLib -Imports WMOTOOLLib -Public Class Windream_alt - Inherits Constants -#Region "+++++ Variables +++++" - Private Shared Logger As NLog.Logger = NLog.LogManager.GetCurrentClassLogger - - Private ServerBrowser As IServerBrowser - - Private CurrentController As WMOSearchController - Private CurrentSession As WMSession - Private CurrentConnect As WMConnect - Private CurrentServer As String - Private CurrentObjecttypes As WMObjects - - Public ReadOnly Property ReconnectSession As Boolean - Public ReadOnly Property DriveLetter As String - Public ReadOnly Property Support64Bit As Boolean - Public Property LoggedInSession As Boolean = False -#End Region -#Region "+++++ Init +++++" - ''' - ''' Initializes windream and creates a windream session with the actual user - ''' - ''' - Public Sub New( - Optional DriveLetter As String = "W", - Optional ReconnectSession As Boolean = False, - Optional Support64Bit As Boolean = False, - Optional ServerName As String = Nothing, - Optional UserName As String = Nothing, - Optional UserPass As String = Nothing, - Optional UserDomain As String = Nothing - ) - Try - Me.DriveLetter = DriveLetter - Me.ReconnectSession = ReconnectSession - Me.Support64Bit = Support64Bit - - Dim session As WMSession = NewSession(ServerName, UserName, UserPass, UserDomain) - - If session Is Nothing Then - Throw New Exception("Login failed") - End If - - CurrentSession = session - CurrentServer = ServerName - CurrentObjecttypes = GetObjectTypes() - - Catch ex As Exception - Logger.Error(ex) - End Try - End Sub - - Public Function NewSession(Optional serverName As String = Nothing) As WMSession - Dim browser As ServerBrowser - Dim connect As WMConnect - Dim session As WMSession - Dim credentials As WMUserIdentity - - Try - browser = New ServerBrowser() - connect = New WMConnect() - Logger.Info("Successfully created windream objects") - Catch ex As Exception - Logger.Error(ex, "Error while creating windream objects") - Return Nothing - End Try - - Try - If serverName Is Nothing OrElse serverName.Length = 0 Then - serverName = browser.GetCurrentServer() - End If - Catch ex As Exception - Logger.Error(ex, "Error while getting current server") - Return Nothing - End Try - - Try - credentials = New WMUserIdentity() With { - .aServerName = serverName - } - Catch ex As Exception - Logger.Error(ex, "Error while creating user identity") - Return Nothing - End Try - - Try - session = connect.Login(credentials) - 'LoggedInSession = True - CurrentServer = serverName - - Return session - Catch ex As Exception - Logger.Error(ex, "Error while logging in") - Return Nothing - End Try - End Function - - Public Function NewSession(Optional serverName As String = Nothing, Optional userName As String = Nothing, Optional password As String = Nothing, Optional domain As String = Nothing) As WMSession - Dim browser As ServerBrowser - Dim connect As WMConnect - Dim session As WMSession - Dim credentials As WMUserIdentity - - Dim impersonation As Boolean - Dim serverNameFromClient As Boolean - - Try - browser = New ServerBrowser() - connect = New WMConnect() - Logger.Info("Successfully created windream objects") - Catch ex As Exception - Logger.Error(ex, "Error while creating windream objects") - Return Nothing - End Try - - ' If no server was supplied, try to get the current server set in the client - Try - If serverName Is Nothing OrElse serverName.Length = 0 Then - serverName = browser.GetCurrentServer - serverNameFromClient = True - Else - serverNameFromClient = False - End If - Catch ex As Exception - Logger.Error(ex, "Error while getting Servername") - Return Nothing - End Try - - Logger.Info("Servername: {0}", serverName) - Logger.Info("Servername aquired from client: {0}", serverNameFromClient) - - 'TODO: Test connection to windream server - - ' If username, password and domain are set, login with impersonation - ' Else, login with current credentials - If userName IsNot Nothing And password IsNot Nothing And domain IsNot Nothing Then - impersonation = True - credentials = New WMUserIdentity() With { - .aServerName = serverName, - .aUserName = userName, - .aPassword = password, - .aDomain = domain - } - - connect.ModuleId = 9 - - Logger.Info("Impersonated Login: True") - Logger.Info("Username: {0}", userName) - Logger.Info("Domain: {0}", domain) - Else - impersonation = False - credentials = New WMUserIdentity() With { - .aServerName = serverName - } - - Logger.Info("Impersonated Login: False") - Logger.Info("Username: {0}", Environment.UserName) - Logger.Info("Domain: {0}", Environment.UserDomainName) - End If - - Try - session = connect.Login(credentials) - Catch ex As Exception - Logger.Error(ex, "Error while logging in") - Return Nothing - End Try - - Try - ' Standardmässig hinterlegen dass abgelegte Dateien keine Indexmaske öffnet - session.SwitchEvents(WMCOMEventWMSessionNeedIndex, False) - Catch ex As Exception - Logger.Error(ex, "Could not SwitchEvents") - Return Nothing - End Try - - If session.aLoggedin = False Then - Logger.Warn("Session created but user {0} could not be logged in", Environment.UserName) - Return Nothing - End If - - Return session - End Function - - - Private Function GetObjectTypes() As WMObjects - Dim objectTypes As WMObjects - - Try - objectTypes = CurrentSession.GetWMObjectTypes(WMEntityDocument) - Return objectTypes - Catch ex As Exception - Logger.Error(ex) - Return Nothing - End Try - End Function - - ''' - ''' Returns all Objecttypes of current server as list of strings - ''' - ''' List of String of all objecttypes - ''' - Public Function GetObjecttypeNames() As List(Of String) - Dim objectTypes As New List(Of String) - - Try - For i As Integer = 0 To CurrentObjecttypes.Count - objectTypes.Add(CurrentObjecttypes.Item(i).aName) - Next - Return objectTypes - Catch ex As Exception - Logger.Error(ex) - Return Nothing - End Try - End Function - - Private Function NormalizePath(path As String) - Dim normalizedPath = path - - If Not path.StartsWith("\") And path.ToUpper().StartsWith(DriveLetter.ToUpper) Then - normalizedPath = path.Substring(2) - End If - - Return normalizedPath - End Function - - - ''' - ''' Creates a windream session with the current user and the current server - ''' - ''' Returns true when created, false if not - ''' - 'Public Function NewSession() As Boolean - ' Try - ' ServerBrowser = New ServerBrowser() - ' CurrentServer = ServerBrowser.GetCurrentServer - ' Catch ex As Exception - ' Logger.Error(ex, "Could not create ServerBrowser") - ' Return False - ' End Try - - ' Try - ' ' Create Connect Object for Session - ' CurrentConnect = New WMConnect - ' Catch ex As Exception - ' Logger.Error(ex, "Could not create WMConnect") - ' Return False - ' End Try - - ' Try - ' ' Create session object with severname set - ' CurrentSession = CreateObject("Windream.WMSession", ServerBrowser.GetCurrentServer) - ' Catch ex As Exception - ' Logger.Error(ex, "Could not create WMConnect") - ' Return False - ' End Try - - ' Try - ' CurrentConnect.LoginSession(CurrentSession) - ' LoggedInSession = True - ' Catch ex As Exception - ' Logger.Error(ex, "Could not login session") - ' Return False - ' End Try - - ' Try - ' ' Standardmässig hinterlegen dass abgelegte Dateien keine Indexmaske öffnet - ' CurrentSession.SwitchEvents(WMCOMEventWMSessionNeedIndex, False) - ' Catch ex As Exception - ' Logger.Error(ex, "Could not SwitchEvents") - ' Return False - ' End Try - - ' If TestLoggedInSession() = False Then - ' Logger.Warn("Session created but user {0} could not be logged in", Environment.UserName) - ' Return False - ' End If - - ' Return True - 'End Function -#End Region -#Region "+++++ New +++++" - ''' - ''' Creates a folder in windream. All folder-parts will be checked - ''' - ''' full path of new folder - ''' Returns true when folder was created, false if not - ''' - Public Function NewFolder(ByVal folderpath As String) - Try - If TestLoggedInSession() = False Then - Return False - End If - folderpath = NormalizePath(folderpath) - Dim folders() As String = folderpath.Split("\") - For Each folder As String In folders - Dim WMObject As WINDREAMLib.WMObject - If TestFolderExists(folder) = False Then - Try - WMObject = CurrentSession.GetNewWMObjectFS(WMEntityFolder, folder, WMObjectEditModeNoEdit) - Catch ex As Exception - Logger.Error(ex) - 'clsLogger.Add("Could not create WMObject for folderpath '" & folder & "': " & ex.Message, True) - Return False - End Try - - End If - Next - Return True - Catch ex As Exception - Logger.Error(ex) - 'clsLogger.Add("Unexpected error in NewFolder: " & ex.Message, True) - Return False - End Try - End Function - ''' - ''' Indexes the file with the given values - ''' - ''' full filepath - ''' Name of the index - ''' values as array - ''' Returns true when folder was created, false if not - ''' - Public Function NewIndexFile(WMFile As String, ByVal indexname As String, ByVal aValues() As String) As Boolean - If TestLoggedInSession() = False Then - Return False - End If - Dim oWMFile As WMObject = GetWMObjectForFile(WMFile) - If IsNothing(oWMFile) Then - Return False - End If - Dim vektInsState As Integer = 1 - Try - If Not oWMFile.aLocked Then - oWMFile.lock() - Else - Logger.Info("WMDoc is locked already!") - Return False - End If - - - If aValues.Length = 1 And aValues(0) = "" Then - Logger.Info("Indexvalue is empty - No indexing") - - Return False - End If - Logger.Info("Indexing of index '" & indexname) - - Dim oWMType - Try - ' das entsprechende Attribut aus windream auslesen - Dim oAttribute = CurrentSession.GetWMObjectByName(WINDREAMLib.WMEntity.WMEntityAttribute, indexname) - ' den Variablentyp (String, Integer, ...) auslesen - oWMType = oAttribute.GetVariableValue("dwAttrType") - Catch ex As Exception - Logger.Error(ex) - Return False - End Try - - ' wenn in aValues an Position i ein Wert steht - Dim i As Integer = 0 - Dim value = aValues(i) - - Dim oWMValueConverted = Nothing - - Dim vektor As Boolean = False - 'Den Typ des Index-Feldes auslesen - Logger.Info("type of windreamIndex: " & oWMType.ToString) - Select Case (oWMType) - - Case INDEX_TYPE_STRING - oWMValueConverted = CStr(value) - Case INDEX_TYPE_INTEGER - value = value.ToString.Replace(" ", "") - value = value.ToString.Replace(" ", "") - oWMValueConverted = CInt(value) - Case INDEX_TYPE_FLOAT - value = value.ToString.Replace(" ", "") - oWMValueConverted = CDbl(value) - Case INDEX_TYPE_FIXED_POINT - value = value.ToString.Replace(" ", "") - oWMValueConverted = CDbl(value) - Case INDEX_TYPE_BOOLEAN - oWMValueConverted = CBool(value) - Case INDEX_TYPE_DATE - 'Dim _date As Date = value - oWMValueConverted = value - Case INDEX_TYPE_TIME - oWMValueConverted = CDbl(value) - Case INDEX_TYPE_CURRENCY - 'Wegen currency muß ein eigenes Objekt vom typ Variant erzeugt werden - Dim aValueWrapper As System.Runtime.InteropServices.CurrencyWrapper = New System.Runtime.InteropServices.CurrencyWrapper(CDec(value)) - oWMValueConverted = aValueWrapper - Case INDEX_TYPE_TIME - 'If ((value)) Then - ' oWMValueConverted = CDate(value) - 'Else - ' oWMValueConverted = "" - 'End If - 'Dim _date As Date = value - oWMValueConverted = oWMValueConverted '*_date.ToShortTimeString - Case INDEX_TYPE_FLOAT - oWMValueConverted = CStr(value) - Case INDEX_TYPE_VARIANT - - oWMValueConverted = CStr(value) - Case INDEX_TYPE_FULLTEXT - oWMValueConverted = CStr(value) - Case 4097 - 'Vektor alphanumerisch - vektor = True - Case 4098 - 'Vektor Numerisch - vektor = True - Case 4099 - 'Vektor Kommazahl - vektor = True - Case 4100 - 'Vektor Kommazahl - vektor = True - Case 4101 - 'Vektor Kommazahl - vektor = True - Case 4103 - 'Vektor DateTime - vektor = True - Case 4107 - vektor = True - Case 36865 - 'Vektor Kommazahl - vektor = True - Case Else - oWMValueConverted = "" - End Select - If vektor = False Then - If oWMValueConverted.ToString Is Nothing = False Then - Logger.Info("Converted value is: " & oWMValueConverted.ToString) - End If - End If - '############################################################################################ - '####################### Der eigentliche Indexierungsvorgang ################################ - '############################################################################################ - If vektor = False Then - Try - If oWMValueConverted.ToString Is Nothing = False Then - Logger.Info("Now: oWMFile.SetVariableValue(" & indexname & ", " & oWMValueConverted & ")") - oWMFile.SetVariableValue(indexname, oWMValueConverted) - 'Die Datei speichern - oWMFile.Save() - Logger.Info("Index has been written!") - Else - Logger.Info("No indexvalue exists!") - End If - Catch ex As Exception - Logger.Error(ex) - oWMFile.Save() - oWMFile.unlock() - Return False - End Try - - Else - Logger.Info("Vectorfield: Preparing of Array!") - Dim myArray() - Dim Anzahl As Integer = aValues.Length - 'Vektorfeld wird mit EINEM Wert gefüllt - If Anzahl = 1 Then - Logger.Info("Vectorfield will be filled with ONE VALUE!") - ReDim myArray(0) - myArray(0) = Helpers.ConvertVectorType(oWMType, value) - 'Jetzt überprüfen ob Werte in Vektorfeld angefügt oder überschrieben werden sollen - Logger.Info("Converted Value: " & myArray(0).ToString) - Dim VektorArray() - VektorArray = Return_VektorArray(oWMFile, indexname, myArray, oWMType) - If VektorArray Is Nothing = False Then - ReDim myArray(VektorArray.Length - 1) - Array.Copy(VektorArray, myArray, VektorArray.Length) - 'Jetzt die Nachindexierung - oWMFile.SetVariableValue(indexname, myArray) ' - Logger.Info("Vectorindex has been written!") - 'Die Änderungen festsschreiben/speichern - oWMFile.Save() - End If - - End If - - End If - i += 1 - - oWMFile.unlock() - Logger.Info("...and unlock") - Return True - Catch ex As Exception - Logger.Error(ex) - oWMFile.Save() - oWMFile.unlock() - Return False - End Try - End Function - Private Function NewLockWMFile(oWMFile As WMObject) As Boolean - Try - oWMFile.lock() - Return True - Catch ex As Exception - Logger.Error(ex) - Return False - End Try - End Function - ''' - ''' Sets the folder-objecttype. - ''' - ''' full path of folder - ''' Obcjectype Name - ''' Returns true when Otype was set, false if not - ''' - Public Function NewObjecttypeForFolder(folderpath As String, folderObjecttype As String) As Boolean - Try - If TestLoggedInSession() = False Then - Return False - End If - Dim result As Boolean = False - Dim WMFolder As WINDREAMLib.WMObject - folderpath = NormalizePath(folderpath) - - If TestFolderExists(folderpath) = True Then - WMFolder = CurrentSession.GetWMObjectByPath(WMEntityFolder, folderpath) - Try - ' die Datei sperren - WMFolder.lock() - Catch ex As Exception - ' nichts tun (Datei ist bereits gesperrt) - End Try - - ' wenn der Datei noch kein Dokumenttyp zugewiesen wurde - If WMFolder.aObjectType.aName = "Standard" Then - - ' ihr den entsprechenden Dokumenttyp zuweisen - WMFolder.aObjectType = CurrentSession.GetWMObjectByName(WINDREAMLib.WMEntity.WMEntityObjectType, folderObjecttype) - ' WMObject.aObjectType = Me.selectedProfile.Dokumenttyp - Logger.Info("Objecttype has been set") - result = True - Else - If WMFolder.aObjectType.aName <> "Standard" Then - Logger.Warn("An Objecttype has already been set!") - End If - End If - - Try - WMFolder.Save() - Catch ex As Exception - ' wenn es einen Fehler beim speichern gab, dann konnte auch kein Dokumenttyp gesetzt werden -> es kann also auch keine - ' Indexierung stattfinden und die Indexierung muss nicht fortgesetzt werden - Return False - End Try - - Try - WMFolder.unlock() - Catch ex As Exception - ' wenn das entsperren nicht geklappt hat, dann war die Datei auch nicht gesperrt - End Try - End If - Return result - - Catch ex As Exception - Logger.Error(ex) - Return False - End Try - End Function - ''' - ''' Creates a new version of the file - ''' - ''' full path to the file - ''' Comment - ''' Returns true when version was created, false if not - ''' - Public Function NewVersion(ByVal WMPath As String, ByVal Comment As String) - Try - If TestLoggedInSession() = False Then - Return False - End If - WMPath = NormalizePath(WMPath) - - Dim WMObject As WMObject '= CreateObject("WINDREAMLib.WMObject") 'New WINDREAMLib.WMObject - Try - WMObject = CurrentSession.GetWMObjectByPath(WMEntityDocument, WMPath) 'WINDREAMLib.WMEntity.WMEntityDocument - Catch ex As Exception - Logger.Warn("Could not create WMObject in Create_Version for file '" & WMPath & "': " & ex.Message) - Return False - End Try - WMObject.CreateVersion2(False, "HISTORY_New_From_Version", Comment) - Return True - Catch ex As Exception - Logger.Error(ex) - Return False - End Try - End Function -#End Region -#Region "+++++ Get +++++" - ''' - ''' Returns all choicelists - ''' - ''' Choicelists as List of Strings or empty list if no choice lists are found - Public Function GetChoiceLists() As List(Of String) - Dim items As New List(Of String) - - If TestLoggedInSession() = False Then - Return items - End If - - Try - Dim choiceLists As WMObjects - Dim choiceList As IWMObject2 - 'load list of choicelists - choiceLists = CurrentSession.GetAllObjects(WMEntityChoiceList) - - For Each choiceList In choiceLists - items.Add(choiceList.aName) - Next - - Return items - Catch ex As Exception - Logger.Error(ex) - Return items - End Try - End Function - - ''' - ''' Returns all indices for an objecttype - ''' - ''' Name of objecttype - ''' Names of indices as list of String - ''' - Public Function GetIndicesByObjecttype(ByVal ObjecttypeName As String) As List(Of String) - Try - If TestLoggedInSession() = False Then - Return Nothing - End If - - Dim oObjectType As WMObject - Dim oIndexAttributes As WMObjectRelation - Dim oIndexAttribute As WMObject - Dim oIndex As WMObject - Dim oRelProperties As WMObjectRelation - ' den Objekttyp laden - oObjectType = CurrentSession.GetWMObjectByName(WMEntityObjectType, ObjecttypeName) - - ' Beziehung zu Indizes des Objekttyp auslesen - oIndexAttributes = oObjectType.GetWMObjectRelationByName("TypeAttributes") - - ' Array für Indizes vorbereiten - 'Dim aIndexNames(oIndexAttributes.Count - 1) As String - Dim indexNames As New List(Of String) - ' alle Indizes durchlaufen - For j As Integer = 0 To oIndexAttributes.Count - 1 - ' aktuellen Index auslesen - oIndexAttribute = oIndexAttributes.Item(j) - - ' Eigenschaften des Index auslesen - oRelProperties = oIndexAttribute.GetWMObjectRelationByName("Attribute") - - ' Index aus den Eigenschaften auslesen - oIndex = oRelProperties.Item(0) - - ' Indexname speichern - 'aIndexNames(j) = oIndex.aName - indexNames.Add(oIndex.aName) - Next - - ' Indexarray zurückgeben - 'Return aIndexNames - Return indexNames - - Catch ex As Exception - Logger.Error(ex) - Return Nothing - End Try - End Function - - ''' - ''' Returns all items of a choicelist - ''' - ''' name of choicelist - ''' Items as list of String - ''' - Public Function GetChoicelistItems(ByVal NameChoicelist As String) As List(Of String) - Dim items As New List(Of String) - - If TestLoggedInSession() = False Then - Return Nothing - End If - - Dim choiceList As WMObject - - ' Try to get the choicelist first and abort if an error occurs - Try - Dim session As IWMSession2 = DirectCast(CurrentSession, IWMSession2) - choiceList = session.GetWMObjectByName(WMEntityChoiceList, NameChoicelist) - Catch ex As Exception - Logger.Error(ex) - Return Nothing - End Try - - ' Try to get choicelist items - Try - Dim values As Object = choiceList.GetVariableValue("vItems") - - ' If values is nothing, the list is empty - If values Is Nothing Then - Return items - End If - - For Each value In values - items.Add(value) - Next - Catch ex As Exception - Logger.Error(ex) - Return Nothing - End Try - - Return items - End Function - - ''' - ''' Returns the result of windream-search - ''' - ''' filepath of windreamSearch-file - ''' Name of the Docid Index - ''' Returns datatable - ''' - Public Function GetSearchDocuments(ByVal wdfLocation As String, NameIndexDocID As String) As DataTable - Dim dtresult As New DataTable - dtresult.Columns.Add("DOC_ID", GetType(Integer)) - dtresult.Columns.Add("PATH", GetType(String)) - If TestLoggedInSession() = False Then - Return dtresult - End If - If TestWMFileExists(wdfLocation) = False Then - Return dtresult - End If - Try - Dim ProfileName = wdfLocation.Substring(wdfLocation.LastIndexOf("\") + 1) - Dim ProfilePath = wdfLocation.Substring(0, wdfLocation.Length - ProfileName.Length) - - CurrentController = New WMOSearchController - CurrentController.CheckSearchProfile(wdfLocation.ToLower) - Dim suchTyp = CurrentController.SearchProfileTargetProgID - Dim ExSettings As Object - Dim oSearch As Object - ExSettings = CurrentController.SearchProfileExSettings - If ExSettings = 0 Then ExSettings = 7 - - Dim srchQuick As WMOSRCHLib.WMQuickSearch = CreateObject("WMOSrch.WMQuickSearch") - Dim srchIndex As WMOSRCHLib.WMIndexSearch = CreateObject("WMOSrch.WMIndexSearch") - Dim srchObjectType As WMOSRCHLib.WMObjectTypeSearch = CreateObject("WMOSrch.WMObjectTypeSearch") - Dim suchTyp1 = suchTyp.ToString.ToUpper - '' Der öffentliche Member CheckSearchProfile für den Typ IWMQuickSearch7 wurde nicht gefunden. [Microsoft.VisualBasic] => GetSearchDocuments() - Select Case suchTyp.ToString.ToUpper - Case "WMOSRCH.WMQUICKSEARCH" - srchQuick.WMSession = CreateObject("Windream.WMSession", CurrentServer) - - CurrentConnect.LoginSession(srchQuick.WMSession) - - srchQuick.ClearSearch() - srchQuick.SearchProfilePath = ProfilePath - srchQuick.LoadSearchProfile(ProfileName) - - oSearch = srchQuick.GetSearch() - - Case "WMOSRCH.WMINDEXSEARCH" - srchIndex.WMSession = CreateObject("Windream.WMSession", CurrentServer) - - CurrentConnect.LoginSession(srchIndex.WMSession) - - srchIndex.ClearSearch() - srchIndex.SearchProfilePath = ProfilePath - srchIndex.LoadSearchProfile(ProfileName) - - oSearch = srchIndex.GetSearch() - - Case "WMOSRCH.WMOBJECTTYPESEARCH" - srchObjectType.WMSession = CreateObject("Windream.WMSession", CurrentServer) - - CurrentConnect.LoginSession(srchObjectType.WMSession) - - srchObjectType.ClearSearch() - srchObjectType.SearchProfilePath = ProfilePath - srchObjectType.LoadSearchProfile(ProfileName) - - oSearch = srchObjectType.GetSearch() - - Case Else - Logger.Warn("No valid WM-SearchType") - Return dtresult - End Select - Dim WMObjects As Object - WMObjects = oSearch.Execute - 'If returnDT = True Then - If WMObjects.Count > 0 Then - - For Each dok As WMObject In WMObjects - Dim path As String = dok.aPath - Dim DOC_ID = dok.GetVariableValue(NameIndexDocID) - Logger.Info("Adding DocInfo for DocID: " & DOC_ID.ToString) - dtresult.Rows.Add(DOC_ID, path) - - Next - dtresult.AcceptChanges() - End If - Return dtresult - Catch ex As Exception - Logger.Error(ex) - Return dtresult - End Try - End Function - ''' - ''' Returns a windream-type as Integer. - ''' - ''' Name of indexfield - ''' Returns integer, which describes the type - ''' - Public Function GetTypeOfIndexAsInt(ByVal indexname As String) As Integer - Try - If TestLoggedInSession() = False Then - Return False - End If - Dim oAttribute = CurrentSession.GetWMObjectByName(WMEntityAttribute, indexname) - Dim vType = oAttribute.GetVariableValue("dwAttrType") - Return vType - Catch ex As Exception - Return Nothing - End Try - End Function - ''' - ''' Returns the value(s) for an index as a datatable - ''' - ''' filepath of windream-file - ''' Name of the index - ''' Datatable - ''' - Public Function GetValueforIndex(ByVal WMFile As String, ByVal NameIndex As String) As DataTable - Dim dt As New DataTable - dt.Columns.Add("RESULT", GetType(String)) - If TestLoggedInSession() = False Then - Return dt - End If - Try - - If Not WMFile.StartsWith("\") And WMFile.ToUpper.StartsWith(DriveLetter.ToUpper) Then - WMFile = WMFile.Substring(2) - End If - Dim WMObject As WINDREAMLib.WMObject '= CreateObject("WINDREAMLib.WMObject") 'New WINDREAMLib.WMObject - Try - WMObject = CurrentSession.GetWMObjectByPath(WINDREAMLib.WMEntity.WMEntityDocument, WMFile) 'WINDREAMLib.WMEntity.WMEntityDocument - Catch ex As Exception - Logger.Error(ex) - Return dt - End Try - - Dim result = WMObject.GetVariableValue(NameIndex) - If IsNothing(result) Then - Return Nothing - Else - If result.GetType.ToString.Contains("System.Object") Then - For Each val As String In result - dt.Rows.Add(val) - Next - dt.AcceptChanges() - Else - dt.Rows.Add(result) - End If - End If - Return dt - Catch ex As Exception - Logger.Error(ex) - Return dt - End Try - End Function - ''' - ''' Returns the values for a vektorfield plus the new ones - ''' - ''' windream-file as Object - ''' Name of the index - ''' Returns value as Datatable - ''' - Public Function Return_VektorArray(ByVal oDocument As WMObject, vktIndexName As String, arrIndexwerte As Object, vType As Object) - Try - If TestLoggedInSession() = False Then - Return False - End If - Dim missing As Boolean = False - Dim valueCount As Integer = 0 - Dim ValueArray() = Nothing - 'Jeden Wert des Vektorfeldes durchlaufen - Dim DT_RESULT = GetValueforIndex(oDocument.aPath, vktIndexName) - If DT_RESULT.Rows.Count > 0 Then - 'Erst die aktuellen Werte speichern und schreiben - For Each row As DataRow In DT_RESULT.Rows - - ReDim Preserve ValueArray(valueCount) - 'Den Wert im Array speichern - ValueArray(valueCount) = Helpers.ConvertVectorType(vType, row.Item(0)) - valueCount += 1 - Next - 'Jetzt die Neuen Werte auf Duplikate überprüfen - For Each NewValue As Object In arrIndexwerte - If NewValue Is Nothing = False Then - If ValueArray.Contains(NewValue) = False Then - 'Das Array anpassen - ReDim Preserve ValueArray(valueCount) - 'Den Wert im Array speichern - ValueArray(valueCount) = Helpers.ConvertVectorType(vType, NewValue) - valueCount += 1 - Else - Logger.Info("Value '" & NewValue.ToString & "' already existing in vectorfield(1)") - - End If - End If - Next - Else - Logger.Info(" vectorfield is empty....") - - 'Den/die Neuen Wert(e) anfügen - For Each NewValue As Object In arrIndexwerte - If NewValue Is Nothing = False Then - If ValueArray Is Nothing = False Then - If ValueArray.Contains(NewValue) = False Then - 'Das Array anpassen - ReDim Preserve ValueArray(valueCount) - 'Den Wert im Array speichern - ValueArray(valueCount) = Helpers.ConvertVectorType(vType, NewValue) - valueCount += 1 - Else - Logger.Info("Value '" & NewValue.ToString & "' already existing in vectorfield(2)") - - End If - Else 'Dererste Wert, also hinzufügen - 'Das Array anpassen - ReDim Preserve ValueArray(valueCount) - 'Den Wert im Array speichern - ValueArray(valueCount) = Helpers.ConvertVectorType(vType, NewValue) - valueCount += 1 - - End If - - - End If - Next - End If - - Return ValueArray - Catch ex As Exception - Logger.Error(ex) - End Try - End Function - ''' - ''' Returns a WMObject if file exists - ''' - ''' full path to the file - ''' Returns WMObject - ''' - Public Function GetWMObjectForFile(ByVal WMPath As String) As WMObject - Try - If TestLoggedInSession() = False Then - Return Nothing - End If - WMPath = NormalizePath(WMPath) - Dim oWMObject As WINDREAMLib.WMObject - Try - oWMObject = CurrentSession.GetWMObjectByPath(WINDREAMLib.WMEntity.WMEntityDocument, WMPath) - Catch ex As Exception - Logger.Warn("Could not create WMObject for file '" & WMPath & "': " & ex.Message) - Return Nothing - End Try - Return oWMObject - Catch ex As Exception - Logger.Error(ex) - Return Nothing - End Try - End Function -#End Region -#Region "+++++ Test +++++" - ''' - ''' Checks if the folder exists - ''' - ''' The path of the folder - ''' True if exists or false if not or error occured - ''' - Public Function TestFolderExists(folderpath As String) - Try - If TestLoggedInSession() = False Then - Return False - End If - folderpath = NormalizePath(folderpath) - Try - Dim exists = CurrentSession.WMObjectExists(WMEntityFolder, folderpath, 0, 0) - Return exists - Catch ex As Exception - Logger.Error(ex) - Return False - End Try - Catch ex As Exception - Return False - End Try - End Function - ''' - ''' Checks wether file exists in windream - ''' - ''' full path to the file - ''' Returns true when file was deleted, false if not - ''' - Public Function TestWMFileExists(ByVal WMPath As String) - Try - If TestLoggedInSession() = False Then - Return False - End If - WMPath = NormalizePath(WMPath) - If IsNothing(GetWMObjectForFile(WMPath)) Then - Return False - Else - Return True - End If - Catch ex As Exception - Logger.Error(ex) - Return False - End Try - End Function - - - Private Function TestLoggedInSession() As Boolean - Try - If CurrentSession.aLoggedin Then - Return True - Else - Logger.Warn("There is no active WM-SSession!") - Return False - End If - Catch ex As Exception - Return False - End Try - End Function - ''' - ''' Checks if user exists in windream. - ''' - ''' test username - ''' Returns true if exists, false if not - ''' - Public Function TestWMUSerExists(username As String) As Boolean - Try - If TestLoggedInSession() = False Then - Return False - End If - Return CurrentSession.WMObjectExists(WMEntityUser, username, 0, 0) - Catch ex As Exception - Logger.Error(ex) - Return False - End Try - End Function - ''' - ''' Checks if group exists in windream. - ''' - ''' test username - ''' Returns true if exists, false if not - ''' - Public Function TestWMGroupExists(groupname As String) - Try - If TestLoggedInSession() = False Then - Return False - End If - Return CurrentSession.WMObjectExists(WMEntityGroups, groupname, 0, 0) - Catch ex As Exception - Logger.Error(ex) - Return False - End Try - End Function -#End Region -#Region "+++++ Remove +++++" - ''' - ''' Deletes a file in windream including all preversions - ''' - ''' full path to the file - ''' Returns true when file was deleted, false if not - ''' - Public Function RemFile(ByVal WMPath As String) - Try - Const COL_Document_VersionID = "dwVersionID" - Const WMObjectPartVersion = 128 - Dim oUnexpected_Error As Boolean = False - WMPath = NormalizePath(WMPath) - Dim oWMObject = GetWMObjectForFile(WMPath) - If IsNothing(oWMObject) = False Then - Try - If (oWMObject.aPart And WMObjectPartVersion) Then - Dim oWMObjects As WMObjects - Dim oWMVersion As WMObject - Dim iCount As Integer - oWMObjects = oWMObject.aVersions - iCount = oWMObjects.Count - If iCount > 0 Then - For Each oWMVersion In oWMObjects - oWMVersion.Delete() - Logger.Info($">> Deleted version '{oWMVersion.GetVariableValue(COL_Document_VersionID)}' of file '{oWMVersion.aName}'!") - Next - End If - End If - Catch ex As Exception - Logger.Warn($"Unexpected Error in CheckingDeleting Prevesions: {ex.Message}") - oUnexpected_Error = True - End Try - If oUnexpected_Error = False Then - oWMObject.Delete() - Logger.Info($">> File '{oWMObject.aName}' has been deleted!") - Return True - Else - Return False - End If - Else - Return False - End If - Catch ex As Exception - Logger.Error(ex) - Return False - End Try - End Function - ''' - ''' Removes the vektorlink from windream - ''' - ''' full path to the file - ''' Indexname of Vektor-Index - ''' Value which is to be deleted - ''' Returns true when indexing was successfull, false if not - ''' - Public Function REMOVE_VEKTOR_LINK(ByVal WMPath As String, vktIndexName As String, deleteValue As String) - Try - Logger.Info("Removing Value '" & deleteValue & "' of Index '" & vktIndexName & "' " & WMPath) - Dim oWMFile As WMObject = GetWMObjectForFile(WMPath) - If IsNothing(oWMFile) Then - Logger.Warn("Exit from REMOVE_VEKTOR_LINK...") - Return False - End If - Dim containsvalue As Boolean = False - Dim ValueArray() = Nothing - 'Jeden Wert des Vektorfeldes durchlaufen - Dim WMValue = oWMFile.GetVariableValue(vktIndexName) - If WMValue Is Nothing = False Then - 'Nochmals prüfen ob wirklich Array - If WMValue.GetType.ToString.Contains("System.Object") Then - ' das entsprechende Attribut aus windream auslesen - Dim oAttribute = CurrentSession.GetWMObjectByName(WMEntityAttribute, vktIndexName) - ' den Variablentyp (String, Integer, ...) auslesen - Dim vType = oAttribute.getVariableValue("dwAttrType") - Dim Anzahl As Integer = 0 - For Each WDValue As Object In WMValue - If WDValue Is Nothing = False Then - If WDValue = deleteValue Then - containsvalue = True - Logger.Info("The Index contains the value to be deleted!") - End If - If WDValue <> deleteValue Then - 'Erst die ALten Werte schreiben - ReDim Preserve ValueArray(Anzahl) - 'Den Wert im Array speichern - ValueArray(Anzahl) = Helpers.ConvertVectorType(vType, WDValue) - Anzahl += 1 - End If - End If - Next - Else - Logger.Warn("Index is not a vector") - Return False - End If - Else - Logger.Warn("oWMObject is nothing") - Return True - End If - - If containsvalue = True Then 'And Not IsNothing(ValueArray) - If NewLockWMFile(oWMFile) = False Then - Return False - End If - 'Indexiern des Vektorfeldes - oWMFile.SetVariableValue(vktIndexName, ValueArray) - ' die Indexinformationen des Dokuments speichern - oWMFile.Save() - Logger.Info("The new vectorvalues were saved!") - ' Unlock in einem unbehandelten Try-Block um Fehler abzufangen, - Try - ' die Sperrung des Dokuments aufheben - oWMFile.unlock() - - Catch ex As Exception - ' nichts tun (Datei war nicht gesperrt) - End Try - 'Zurückgeben - Return True - Else - Logger.Info("containsvalue is not true") - Return True - End If - - Catch ex As Exception - Logger.Error(ex) - Return False - End Try - End Function -#End Region -End Class