WIDIG/WiDigShared/ClassWIDig.vb
2021-08-12 10:46:09 +02:00

353 lines
15 KiB
VB.net

Imports DigitalData.Modules.Logging
Imports DigitalData.Modules.Encryption
Imports DigitalData.Modules.Windream
Imports DigitalData.Modules.Database
Imports System.Text.RegularExpressions
Public Class ClassWIDig
Private LogConfig As LogConfig
Private Config As ClassConfig
Private Windream As Windream
Private Logger As Logger
Private Database As MSSQLServer
Public oRegex As New Regex("([\s\S]+)\={([\s\S]+)}")
Public Const CODE_SUCCESS = 0
Public Const CODE_ERROR = 1
Public Const MODE_OVERWRITE = "IMPO"
Public Const MODE_VERSION = "IMPV"
Public Const MODE_NACHINDEXIERUNG = "NI"
Public Const PARAM_SOURCE = "-Source@"
Public Const PARAM_MODE = "-Mode@"
Public Const PARAM_TARGET = "-Target@"
Public Const PARAM_WMTO = "-WMOT@"
Public Const PARAM_INDEX = "-index@"
Public Property ErrorMessage As String
Public Property ErrorWhileParsing As Boolean
Public Property ErrorWhileImporting As Boolean
Public Property RunMode As String
Public Property SourceFile As Object
Public Property TargetPath As Object
Public Property WindreamObjectType As String
Public Property WindreamIndicies As List(Of String)
Public Property IndexArray As List(Of String)
Public Sub New(pLogConfig As LogConfig, pConfig As ClassConfig)
LogConfig = pLogConfig
Logger = pLogConfig.GetLogger
Config = pConfig
End Sub
Public Shared Function GetProgramDataPath()
Return IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "Digital Data", "WIDig")
End Function
Public Shared Function GetAppDataPath()
Return IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Digital Data", "WIDig")
End Function
Public Function GetUserPWPlain()
Try
Dim oPassword As String
Dim oEncryption As New EncryptionLegacy("!35452didalog=")
If Config.WMUserPW = String.Empty Then
oPassword = ""
Else
oPassword = oEncryption.DecryptData(Config.WMUserPW)
End If
Return oPassword
Catch ex As Exception
Logger.Warn("Error in GetUserPWPlain - the password [" & Config.WMUserPW & "] could not be decrypted", False)
Return String.Empty
End Try
End Function
Public Function Connect2Windream(oPW As String)
Try
Windream = New Windream(LogConfig, False, Config.WMDrive, Config.WMRelPath, True, Config.WMServer, Config.WMUsername, oPW, Config.Domain)
If Not IsNothing(Windream) Then
If Windream.SessionLoggedin = True Then
Logger.Debug("windream initialisiert")
Return True
End If
End If
Return False
Catch ex As Exception
Logger.Warn("CHECKING WMConnectivity: " & ex.Message)
Return False
End Try
End Function
Public Function InitDatabase() As Boolean
If Config.ConnectionString.Length = 0 Then
Return False
End If
Try
Dim oDecryptedConnectionString = MSSQLServer.DecryptConnectionString(Config.ConnectionString)
Database = New MSSQLServer(LogConfig, oDecryptedConnectionString)
If Database.DBInitialized = True Then
Return True
Else
Return False
End If
Catch ex As Exception
Logger.Error(ex)
Return False
End Try
End Function
Public Function ParseArgs(pArguments As String(), Optional pTest As Boolean = False)
Dim oINDEXInfoStarted As Boolean = False
Dim oINDEXInfotemp As String = ""
Try
If pArguments.Length <= 3 Then
Logger.Warn($"Insufficient number of arguments [{pArguments.Length}]!")
System.Console.WriteLine($"Insufficient number of arguments - {Now.ToString}")
ErrorWhileParsing = True
Return False
End If
Dim oCount As Integer = 0
For Each oArg As String In pArguments
Logger.Debug($"[{oCount}] {oArg}")
oArg = oArg.Replace("""", "")
If oArg.StartsWith(PARAM_SOURCE) Then
SourceFile = oArg.Replace(PARAM_SOURCE, "")
If IsNumeric(SourceFile) Then
Logger.Info($"SourceFile seems to be a DocID [{SourceFile}]")
Dim oSQL = $"SELECT [dbo].[FNDD_GET_WINDREAM_FILE_PATH] ({SourceFile})"
SourceFile = Database.GetScalarValue(oSQL)
End If
If System.IO.File.Exists(SourceFile) = False Then
Logger.Warn($"Parser@Sourcefile - File [{SourceFile}] is not existing!")
ErrorMessage &= vbNewLine & $"Parser@Sourcefile - File [{SourceFile}] is not existing!"
ErrorWhileParsing = True
Return False
End If
ElseIf oArg.StartsWith(PARAM_MODE) Then
RunMode = oArg.Replace(PARAM_MODE, "").ToUpper
ElseIf oArg.StartsWith(PARAM_TARGET) Then
TargetPath = oArg.Replace(PARAM_TARGET, "")
Dim oWMFolder = System.IO.Path.GetDirectoryName(TargetPath)
Dim oWindowsPath = TargetPath
Dim oExtension = IO.Path.GetExtension(oWindowsPath)
Dim oNormalizePath = Windream.GetNormalizedPath(TargetPath)
If Windream.TestFileExists(TargetPath) = False Then
Logger.Info($"WMFile [{TargetPath}] not existing!")
End If
If RunMode = MODE_VERSION Then
Dim oWMCheckPath = Windream.VersionWMFilename(TargetPath, System.IO.Path.GetExtension(TargetPath))
If oNormalizePath.ToUpper <> oWMCheckPath.ToString.ToUpper Then
Logger.Info($"Target [{oNormalizePath}] already existed!! - NewWMFilename [{oWMCheckPath}]")
TargetPath = oWMCheckPath
End If
End If
'Checks and creates the path if necessary
Windream.NewFolder(TargetPath, oExtension)
ElseIf oArg.StartsWith(PARAM_WMTO) Then
WindreamObjectType = oArg.Replace(PARAM_WMTO, "")
Dim oObjectTypExists As Boolean = False
Dim myWMOTypes = Windream.ObjectTypes
For Each otype As String In myWMOTypes
If WindreamObjectType = otype Then
oObjectTypExists = True
Exit For
End If
Next
If oObjectTypExists = False Then
Logger.Info($"WindreamObjectType [{WindreamObjectType}] not existing!!")
ErrorMessage &= vbNewLine & $"WindreamObjectType [{WindreamObjectType}] not existing!!"
Return False
ErrorWhileParsing = True
Else
WindreamIndicies = Windream.GetIndiciesByObjecttype(WindreamObjectType)
End If
ElseIf oArg.StartsWith(PARAM_INDEX) Then
oINDEXInfotemp = oArg
oINDEXInfoStarted = True
oINDEXInfotemp = oINDEXInfotemp.Replace(PARAM_INDEX, "")
Else
' All args that do not start with an argument identifier (-EXAMPLE@) are just parts of other arguments
' and are put back together just like they used to be before.
If oINDEXInfoStarted Then
oINDEXInfotemp &= " " & oArg
End If
End If
oCount += 1
Next
Logger.Debug("INDEXInfoTemp: [{0}]", oINDEXInfotemp)
Dim oIndexparts As List(Of String) = oINDEXInfotemp.
Split(New String() {"#~#"}, StringSplitOptions.RemoveEmptyEntries).
ToList()
For Each oIndexPart As String In oIndexparts
Logger.Debug(oIndexPart)
Next
Logger.Info($" [{oIndexparts.Count}] Indices parsed")
IndexArray = oIndexparts
Return True
Catch ex As Exception
Logger.Error(ex)
Logger.Warn("Error in ParseArgs:" & vbNewLine & ex.Message)
ErrorMessage &= vbNewLine & "Error in ParseArgs:" & vbNewLine & ex.Message
ErrorWhileParsing = True
System.Console.WriteLine($"Error in ParseArgs - {Now.ToString}")
Return False
End Try
End Function
Public Function StreamORIndexFile()
Try
Dim oResult As Boolean = False
If RunMode = MODE_VERSION Then
oResult = Windream.NewFileStream(SourceFile, TargetPath)
ElseIf RunMode = MODE_OVERWRITE Then
Dim oDeleted = Windream.RemoveFile(TargetPath)
If oDeleted = True Then
oResult = Windream.NewFileStream(SourceFile, TargetPath)
Else
Logger.Warn($"Mode ImportOverwrite is active - but WMFile could not be deleted!!")
End If
ElseIf RunMode = MODE_NACHINDEXIERUNG Then
oResult = True
End If
If oResult = True Then
Dim oFilePathToIndex As String = TargetPath
If RunMode = MODE_NACHINDEXIERUNG Then
oFilePathToIndex = SourceFile
Logger.Info($"Using Sourcefile as FileName: [{SourceFile}]")
Else
Logger.Info($"File successfully streamed to windream [{TargetPath}]!")
End If
Logger.Info("Indexing file [{0}]", oFilePathToIndex)
For Each oIndex As String In IndexArray
Dim oMatch As Match = oRegex.Match(oIndex)
If oMatch.Success Then
Dim oIndexName = oMatch.Groups(1)?.Value
Dim oIndexValues = oMatch.Groups.Item(2)?.Value
Dim oSplitValue = New String() {"~#~"}
Dim oIndexValueArray = oIndexValues.Split(oSplitValue, StringSplitOptions.RemoveEmptyEntries)
Dim oIndexResult = False
Logger.Info("Setting Index [{0}] to [{1}].", oIndexName, oIndexValues)
If Windream.TestIndexNameIsVectorIndex(oIndexName) Then
Dim oCombinedIndexValues = Windream.GetVectorData(oFilePathToIndex, oIndexName, oIndexValueArray, False)
oIndexResult = Windream.SetFileIndex(oFilePathToIndex, oIndexName, oCombinedIndexValues.ToList, WindreamObjectType)
Else
oIndexResult = Windream.SetFileIndex(oFilePathToIndex, oIndexName, oIndexValueArray(0), WindreamObjectType)
End If
oResult = oIndexResult
Else
oResult = False
End If
If oResult = False Then
Logger.Warn("Indexing failed. Exiting.")
Exit For
End If
Next
End If
If oResult = True Then
Logger.Info("## All Tasks finished ##")
ErrorWhileImporting = False
End If
#Region "Old Logic"
'If oResult = True Then
' If oMode <> MODE_NACHINDEXIERUNG Then
' LOGGER.Info($"File successfully streamed to windream [{oTargetPath}]! Now indexing...")
' End If
' For Each oIndex2 As String In oIndexArr
' Dim oIndexInfo() = oIndex2.Split("={")
' Dim oIndexName = oIndexInfo(0)
' Dim oIndexvalue
' Dim r As Regex = New Regex(oRegExArg, RegexOptions.IgnoreCase)
' ' ' Match the regular expression pattern against a text string.
' Dim m As Match = r.Match(oIndex2)
' Do While m.Success
' ' oClearedBodyText = oClearedBodyText.Replace(m.Value, "")
' 'Dim g As Group = m.Groups(1)
' Dim g1 As Group = m.Groups(2)
' Dim g2 As Group = m.Groups(3)
' If Not IsNothing(g2.Value) Then
' oIndexvalue = g2.Value
' Console.WriteLine($"Indexvalue: {oIndexvalue}")
' End If
' If Len(oIndexvalue) > 0 Then
' If WMIndices.Contains(oIndexName) Then
' LOGGER.Info($"Setting Index: oIndexName [{oIndexName}] - oIndexvalue [{oIndexvalue}]")
' 'DEBUG
' oIndexvalue = New List(Of String) From {"Wert 1", "Wert 2", "wert 3"}
' 'DEBUG
' If WINDREAM.SetFileIndex(oTargetPath, oIndexName, oIndexvalue, oWMObjecttype) = False Then
' LOGGER.Info($"Index could not be set...")
' If WINDREAM.RemoveFile(oTargetPath) = True Then
' LOGGER.Info($"File deleted after error!")
' End If
' oResult = False
' Exit For
' End If
' Else
' LOGGER.Warn($"Transmitted index with name [{oIndexName}] is not existing in WM Objecttype!")
' If WINDREAM.RemoveFile(oTargetPath) = True Then
' LOGGER.Info($"File deleted after error!")
' End If
' oResult = False
' Exit For
' End If
' End If
' m = m.NextMatch()
' Loop
' Next
' If oResult = True Then
' LOGGER.Info("## All Tasks finished ##")
' oErrorImport = False
' End If
'End If
#End Region
Return oResult
Catch ex As Exception
Logger.Warn($"Unexpected Error in StreamORIndexFile: {ex.Message}")
Logger.Error(ex)
Return False
End Try
End Function
End Class