public override kCura.EventHandler.Response Execute()
        {
            var response = new kCura.EventHandler.Response {
                Success = true, Message = String.Empty
            };
            var artifactQueries     = new ArtifactQueries();
            var servicesMgr         = Helper.GetServicesManager();
            var workspaceArtifactId = Helper.GetActiveCaseID();

            try
            {
                List <ExtractorRegullarExpression> regExList = PopulateRegExList();

                //Populates Regular Expressions
                foreach (var regEx in regExList)
                {
                    artifactQueries.CreateExtractorRegularExpressionRecord(servicesMgr, Relativity.API.ExecutionIdentity.System, workspaceArtifactId, regEx.Name, regEx.RegularExpression, regEx.Description);
                }
            }
            catch (Exception ex)
            {
                response.Success = false;
                response.Message = "Post-Install regular expression population failed with message: " + ex;
            }
            return(response);
        }
        public async Task <kCura.EventHandler.Response> ExecuteAsync()
        {
            return(await Task.Run(() =>
            {
                _logger = Helper.GetLoggerFactory().GetLogger();

                var response = new kCura.EventHandler.Response
                {
                    Success = true,
                    Message = String.Empty
                };
                var sqlQueryHelper = new SqlQueryHelper();

                //Create the Export Utility Job Manager queue table if it doesn't already exist
                _logger.LogDebug($"{Constant.Names.ApplicationName} - Creating Export Utility Job Manager queue table if it doesn't already exist");
                var exportManagerTableTask = sqlQueryHelper.CreateExportManagerQueueTableAsync(Helper.GetDBContext(-1));
                _logger.LogDebug($"{Constant.Names.ApplicationName} - Created Export Utility Job Manager queue table if it doesn't already exist");

                //Create the Export Utility Job Worker queue table if it doesn't already exist
                _logger.LogDebug($"{Constant.Names.ApplicationName} - Creating Export Utility Job Worker queue table if it doesn't already exist");
                var exportWorkerTableTask = sqlQueryHelper.CreateExportWorkerQueueTableAsync(Helper.GetDBContext(-1));
                _logger.LogDebug($"{Constant.Names.ApplicationName} - Created Export Utility Job Worker queue table if it doesn't already exist");

                //Create the Export Utility Job Error log table if it doesn't already exist
                _logger.LogDebug($"{Constant.Names.ApplicationName} - Creating Export Utility Job Error Log table if it doesn't already exist");
                var exportErrorLogTableTask = sqlQueryHelper.CreateExportErrorLogTableAsync(Helper.GetDBContext(-1));
                _logger.LogDebug($"{Constant.Names.ApplicationName} - Created Export Utility Job Error Log table if it doesn't already exist");

                //Create the Import Utility Job Manager queue table if it doesn't already exist
                _logger.LogDebug($"{Constant.Names.ApplicationName} - Creating Import Utility Job Manager queue table if it doesn't already exist");
                var importManagerTableTask = sqlQueryHelper.CreateImportManagerQueueTableAsync(Helper.GetDBContext(-1));
                _logger.LogDebug($"{Constant.Names.ApplicationName} - Created Import Utility Job Manager queue table if it doesn't already exist");

                //Create the Import Utility Job Worker queue table if it doesn't already exist
                _logger.LogDebug($"{Constant.Names.ApplicationName} - Creating Import Utility Job Worker queue table if it doesn't already exist");
                var importWorkerTableTask = sqlQueryHelper.CreateImportWorkerQueueTableAsync(Helper.GetDBContext(-1));
                _logger.LogDebug($"{Constant.Names.ApplicationName} - Created Import Utility Job Worker queue table if it doesn't already exist");

                //Create the Import Utility Job Error log table if it doesn't already exist
                _logger.LogDebug($"{Constant.Names.ApplicationName} - Creating Import Utility Job Error Log table if it doesn't already exist");
                var importErrorLogTableTask = sqlQueryHelper.CreateImportErrorLogTableAsync(Helper.GetDBContext(-1));
                _logger.LogDebug($"{Constant.Names.ApplicationName} - Created Import Utility Job Error Log table if it doesn't already exist");


                try
                {
                    // Waits for all tasks, otherwise exceptions would be lost
                    Task.WaitAll(exportManagerTableTask, exportWorkerTableTask, exportErrorLogTableTask, importManagerTableTask, importWorkerTableTask, importErrorLogTableTask);
                }
                catch (AggregateException aex)
                {
                    _logger.LogError(aex, $"{Constant.Names.ApplicationName} - Post-Install failed. {aex}");
                    var ex = aex.Flatten();
                    var message = ex.Message + " : " + (ex.InnerException?.Message ?? "None");
                    response.Success = false;
                    response.Message = "Post-Install field rename failed with message: " + message;
                }
                return response;
            }));
        }
Пример #3
0
        public override kCura.EventHandler.Response Execute()
        {
            kCura.EventHandler.Response response = new kCura.EventHandler.Response();
            string tableName = null;

            response.Success = true;
            response.Message = "";

            //If job is new
            if (this.ActiveArtifact.IsNew)
            {
                try {
                    //Make sure a record does not already exist
                    tableName = RetrieveArtifactTypeName();
                    if (DoesRecordExist(tableName))
                    {
                        response.Success = false;
                        response.Message = NSerio.FileValidation.MainApp.Helper.Constant.EM_JOB_ALREADY_EXISTS;
                        return(response);
                    }

                    //Set job status to New
                    UpdateStatus();
                } catch (Exception ex) {
                    response.Success = false;
                    response.Message = ex.Message;
                }
            }

            return(response);
        }
Пример #4
0
        public async Task <kCura.EventHandler.Response> ExecuteAsync()
        {
            var response = new kCura.EventHandler.Response {
                Success = true, Message = string.Empty
            };

            try
            {
                Logger.LogDebug(Constant.Names.ApplicationName + " - [{@this}] Creating tables...", this);

                //Create the Export Utility Job Manager queue table if it doesn't already exist
                Logger.LogDebug($"{Constant.Names.ApplicationName} - Creating Export Utility Job Manager queue table if it doesn't already exist.");
                await SqlQueryHelper.CreateExportManagerQueueTableAsync(DbContextEdds);

                Logger.LogDebug($"{Constant.Names.ApplicationName} - Created Export Utility Job Manager queue table if it doesn't already exist.");

                //Create the Export Utility Job Worker queue table if it doesn't already exist
                Logger.LogDebug($"{Constant.Names.ApplicationName} - Creating Export Utility Job Worker queue table if it doesn't already exist.");
                await SqlQueryHelper.CreateExportWorkerQueueTableAsync(DbContextEdds);

                Logger.LogDebug($"{Constant.Names.ApplicationName} - Created Export Utility Job Worker queue table if it doesn't already exist.");

                //Create the Export Utility Job Error log table if it doesn't already exist
                Logger.LogDebug($"{Constant.Names.ApplicationName} - Creating Export Utility Job Error Log table if it doesn't already exist.");
                await SqlQueryHelper.CreateExportErrorLogTableAsync(DbContextEdds);

                Logger.LogDebug($"{Constant.Names.ApplicationName} - Created Export Utility Job Error Log table if it doesn't already exist.");

                //Create the Import Utility Job Manager queue table if it doesn't already exist
                Logger.LogDebug($"{Constant.Names.ApplicationName} - Creating Import Utility Job Manager queue table if it doesn't already exist.");
                await SqlQueryHelper.CreateImportManagerQueueTableAsync(DbContextEdds);

                Logger.LogDebug($"{Constant.Names.ApplicationName} - Created Import Utility Job Manager queue table if it doesn't already exist.");

                //Create the Import Utility Job Worker queue table if it doesn't already exist
                Logger.LogDebug($"{Constant.Names.ApplicationName} - Creating Import Utility Job Worker queue table if it doesn't already exist.");
                await SqlQueryHelper.CreateImportWorkerQueueTableAsync(DbContextEdds);

                Logger.LogDebug($"{Constant.Names.ApplicationName} - Created Import Utility Job Worker queue table if it doesn't already exist.");

                //Create the Import Utility Job Error log table if it doesn't already exist
                Logger.LogDebug($"{Constant.Names.ApplicationName} - Creating Import Utility Job Error Log table if it doesn't already exist.");
                await SqlQueryHelper.CreateImportErrorLogTableAsync(DbContextEdds);

                Logger.LogDebug($"{Constant.Names.ApplicationName} - Created Import Utility Job Error Log table if it doesn't already exist.");

                Logger.LogDebug(Constant.Names.ApplicationName + " - [{@this}] Created tables successfully...", this);
            }
            catch (AdminMigrationUtilityException ex)
            {
                var message = ex.Message + " : " + (ex.InnerException?.Message ?? "None");
                Logger.LogError($"{Constant.Names.ApplicationName} - Post-Install failed. {message}");

                response.Success = false;
                response.Message = $"Post-Install table creation(s) failed with message: {ex.Message}";
                throw new AdminMigrationUtilityException(ex.Message);
            }

            return(response);
        }
Пример #5
0
        public override kCura.EventHandler.Response Execute()
        {
            //Construct a response object with default values.
            var retVal = new kCura.EventHandler.Response
            {
                Success = true,
                Message = string.Empty
            };

            try
            {
                var currentWorkspaceArtifactId = Helper.GetActiveCaseID();

                //ActiveArtifact is null so this is how we get the IDs of the objects to delete
                var tempTableNameWithParentArtifactsToDelete = TempTableNameWithParentArtifactsToDelete;
                _workspaceContext = Helper.GetDBContext(currentWorkspaceArtifactId);
                var eddsDbContext = Helper.GetDBContext(-1);
                var isOkToDelete  = IsOkToDelete(eddsDbContext, tempTableNameWithParentArtifactsToDelete, _workspaceContext.Database);

                if (!isOkToDelete)
                {
                    throw new SystemException("Unable to delete job(s) in progress.");
                }
            }
            catch (Exception ex)
            {
                //Change the response Success property to false to let the user know an error occurred
                retVal.Success   = false;
                retVal.Message   = ex.ToString();
                retVal.Exception = ex;
                retVal.Exception = ex;
            }

            return(retVal);
        }
        public override kCura.EventHandler.Response Execute()
        {
            var response = new kCura.EventHandler.Response {
                Success = true, Message = String.Empty
            };
            var queryHelper = new SqlQueryHelper();

            try
            {
                //Create manager queue table if it doesn't already exist
                queryHelper.CreateManagerQueueTable(Helper.GetDBContext(-1));

                //Create worker queue table if it doesn't already exist
                queryHelper.CreateWorkerQueueTable(Helper.GetDBContext(-1));

                //Create error log table if it doesn't already exist
                queryHelper.CreateErrorLogTable(Helper.GetDBContext(-1));
            }
            catch (Exception ex)
            {
                response.Success = false;
                response.Message = "Post-Install queue table creation failed with message: " + ex;
            }
            return(response);
        }
        public override kCura.EventHandler.Response Execute()
        {
            // Update Security Protocol
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

            // Get logger
            Relativity.API.IAPILog _logger = this.Helper.GetLoggerFactory().GetLogger().ForContext <PreInstallEventHandler>();

            // Init general response
            kCura.EventHandler.Response response = new kCura.EventHandler.Response()
            {
                Success = true,
                Message = ""
            };

            // Get current Workspace ID
            int workspaceId = this.Helper.GetActiveCaseID();

            _logger.LogDebug("Audit Log Elastic Search, current Workspace ID: {workspaceId}", workspaceId.ToString());

            // Get database context of the instance
            IDBContext instanceContext = Helper.GetDBContext(-1);

            // Current Relativity version
            string currentRelativityVersion = "";

            try
            {
                // Get Relativity version
                currentRelativityVersion = instanceContext.ExecuteSqlStatementAsScalar("SELECT [Value] FROM [eddsdbo].[Relativity] WHERE [Key] = 'Version'").ToString();
                _logger.LogDebug("Audit Log Elastic Search, current Relativity version: {version}", currentRelativityVersion);
                _logger.LogDebug("Audit Log Elastic Search, minimum required Relativity version: {version}", this.MinRelativityVersion);
            }
            catch (Exception e)
            {
                _logger.LogError(e, "Audit Log Elastic Search, Pre Install EventHandler Relativity version error");

                response.Success = false;
                response.Message = "Pre Install EventHandler Relativity version error";
                return(response);
            }

            // Check Relativity version requirements
            if (new Version(currentRelativityVersion) < new Version(this.MinRelativityVersion))
            {
                _logger.LogError("Audit Log Elastic Search, old Relativity instance (version: {version})", currentRelativityVersion);

                response.Success = false;
                response.Message = string.Format("This application requires Relativity {0} or later", this.MinRelativityVersion);
                return(response);
            }

            // Log end of Pre Install EventHandler
            _logger.LogDebug("Audit Log Elastic Search, Pre Install EventHandler successfully finished");

            return(response);
        }
Пример #8
0
 /*
  * Occurs after the user has inputted data to a layout and pressed OK.
  * This function runs as a pre-save eventhandler.
  * This is NOT called if the mass operation does not have a layout.
  */
 public override kCura.EventHandler.Response ValidateLayout()
 {
     // Init general response
     kCura.EventHandler.Response response = new kCura.EventHandler.Response()
     {
         Success = true,
         Message = ""
     };
     return(response);
 }
Пример #9
0
 /*
  * Occurs after all batching is completed.
  */
 public override kCura.EventHandler.Response PostMassOperation()
 {
     // Init general response
     kCura.EventHandler.Response response = new kCura.EventHandler.Response()
     {
         Success = true,
         Message = ""
     };
     return(response);
 }
        public override kCura.EventHandler.Response Execute()
        {
            //Executed ONLY if the file object is associated with jobs, no need to query the db to check.
            var retVal = new kCura.EventHandler.Response()
            {
                Success   = false,
                Message   = "The file is associated with jobs.",
                Exception = new SystemException("Unable to delete: the file is associated with one or more Import or Export Jobs.")
            };

            return(retVal);
        }
Пример #11
0
        /*
         * Occurs after the user has selected items and pressed go.
         * In this function you can validate the items selected and return a warning/error message.
         */
        public override kCura.EventHandler.Response ValidateSelection()
        {
            // Get logger
            Relativity.API.IAPILog _logger = this.Helper.GetLoggerFactory().GetLogger().ForContext <MassOperationHandler>();

            // Init general response
            kCura.EventHandler.Response response = new kCura.EventHandler.Response()
            {
                Success = true,
                Message = ""
            };

            // Get current Workspace ID
            int workspaceId = this.Helper.GetActiveCaseID();

            _logger.LogDebug("Azure Translator, current Workspace ID: {workspaceId}", workspaceId.ToString());

            // Check if all Instance Settings are in place
            IDictionary <string, string> instanceSettings = this.GetInstanceSettings(ref response, new string[] { "SourceField", "DestinationField", "LogField", "Cost1MCharacters", "AzureServiceRegion", "AzureSubscriptionKey", "AzureTranslatorEndpoint", "TranslateFrom", "TranslateTo" });

            // Check if there was not error
            if (!response.Success)
            {
                return(response);
            }

            /*
             * Calculate the translation costs
             */
            // TODO: redo in Object Manager API
            try
            {
                // Construct and execute SQL Query to get the characters count
                string sqlText = "SELECT SUM(LEN(CAST([" + instanceSettings["SourceField"].Replace(" ", "") + "] AS NVARCHAR(MAX)))) FROM [EDDSDBO].[Document] AS [Document] JOIN [Resource].[" + this.MassActionTableName + "] AS [MassActionTableName] ON [Document].[ArtifactID] = [MassActionTableName].[ArtifactID]";
                _logger.LogDebug("Azure Translator, translation cost SQL Parameter and Query: {query}", sqlText);
                long count = (long)this.Helper.GetDBContext(workspaceId).ExecuteSqlStatementAsScalar(sqlText);

                // Calculate translation cost
                float cost = (count / 1000000f) * float.Parse(instanceSettings["Cost1MCharacters"]);
                _logger.LogDebug("Azure Translator, translation cost: {price}CHF, ({chars} chars)", cost.ToString("0.00"), count.ToString());
                response.Message = string.Format("Translation cost is {0}CHF, ({1} chars)", cost.ToString("0.00"), count.ToString());
            }
            catch (Exception e)
            {
                _logger.LogError(e, "Azure Translator, translation cost error ({SourceField}, {Cost1MCharacters})", instanceSettings["SourceField"], instanceSettings["Cost1MCharacters"]);

                response.Success = false;
                response.Message = "Translation cost error";
            }

            return(response);
        }
Пример #12
0
        /*
         * Custom method to get required Relativity Instance Settings
         */
        private IDictionary <string, string> GetInstanceSettings(ref kCura.EventHandler.Response response, string[] instanceSettingsNames)
        {
            // Get logger
            Relativity.API.IAPILog _logger = this.Helper.GetLoggerFactory().GetLogger().ForContext <MassOperationHandler>();

            // Output Dictionary
            IDictionary <string, string> instanceSettingsValues = new Dictionary <string, string>();

            // Get and validate instance settings
            foreach (string name in instanceSettingsNames)
            {
                try
                {
                    instanceSettingsValues.Add(name, this.Helper.GetInstanceSettingBundle().GetString("Azure.Translator", name));
                    if (instanceSettingsValues[name].Length <= 0)
                    {
                        _logger.LogError("Azure Translator, Instance Settings empty error: {section}/{name}", "Azure.Translator", name);

                        response.Success = false;
                        response.Message = "Instance Settings error";
                        return(instanceSettingsValues);
                    }
                }
                catch (Exception e)
                {
                    _logger.LogError(e, "Azure Translator, Instance Settings error: {section}/{name}", "Azure.Translator", name);

                    response.Success = false;
                    response.Message = "Instance Settings error";
                    return(instanceSettingsValues);
                }

                _logger.LogDebug("Azure Translator, Instance Setting: {name}=>{value}", name, instanceSettingsValues[name]);
            }

            // Check Cost1MCharacters Instance Settings is a number
            try
            {
                float.Parse(instanceSettingsValues["Cost1MCharacters"]);
            }
            catch (Exception e)
            {
                _logger.LogError(e, "Azure Translator, Instance Settings error: {section}/{name}", "Azure.Translator", "Cost1MCharacters");

                response.Success = false;
                response.Message = "Instance Settings error";
                return(instanceSettingsValues);
            }

            return(instanceSettingsValues);
        }
        public override kCura.EventHandler.Response Execute()
        {
            kCura.EventHandler.Response retVal = new kCura.EventHandler.Response();
            retVal.Success = true;
            retVal.Message = string.Empty;
            try
            {
                this.InstallTables();
                this.InstallTabs();
            }
            catch (System.Exception ex)
            {
                retVal.Success = false;
                retVal.Message = ex.ToString();
            }

            return(retVal);
        }
        public override kCura.EventHandler.Response Execute()
        {
            // Update Security Protocol
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

            // Get logger
            Relativity.API.IAPILog _logger = this.Helper.GetLoggerFactory().GetLogger().ForContext <PostWorkspaceCreateEventHandlerBase>();

            // Init general response
            kCura.EventHandler.Response response = new kCura.EventHandler.Response()
            {
                Success = true,
                Message = ""
            };

            // Get current Workspace ID
            int workspaceId = this.Helper.GetActiveCaseID();

            _logger.LogDebug("Audit Log Elastic Search, current Workspace ID: {workspaceId}", workspaceId.ToString());

            // Get database context of the instance
            IDBContext instanceContext = Helper.GetDBContext(-1);

            // Add line to the application management table for current workspace
            try
            {
                // Insert to the application management table
                SqlParameter workspaceIdParam = new SqlParameter("@workspaceId", workspaceId);
                instanceContext.ExecuteNonQuerySQLStatement("INSERT INTO [eddsdbo].[" + this.TableName + "] ([CaseArtifactID], [AuditRecordID], [Status], [LastUpdated]) VALUES (@workspaceId, 0, 1, CURRENT_TIMESTAMP)", new SqlParameter[] { workspaceIdParam });
            }
            catch (Exception e)
            {
                _logger.LogError(e, "Audit Log Elastic Search, Post Workspace Create EventHandler application management table insert error");

                response.Success = false;
                response.Message = "Post Workspace Create EventHandler application management table insert error";
                return(response);
            }

            // Log end of Post Workspace Create EventHandler
            _logger.LogDebug("Audit Log Elastic Search, Post Workspace Create EventHandler successfully finished");

            return(response);
        }
        public override kCura.EventHandler.Response Execute()
        {
            // Update Security Protocol
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

            // Get logger
            Relativity.API.IAPILog _logger = this.Helper.GetLoggerFactory().GetLogger().ForContext <PreUninstallEventHandler>();

            // Init general response
            kCura.EventHandler.Response response = new kCura.EventHandler.Response()
            {
                Success = true,
                Message = ""
            };

            // Get current Workspace ID
            int workspaceId = this.Helper.GetActiveCaseID();

            _logger.LogDebug("Audit Log Elastic Search, current Workspace ID: {workspaceId}", workspaceId.ToString());

            // Get database context of the instance
            IDBContext instanceContext = Helper.GetDBContext(-1);

            // Update line of the application management and set current workspace to disabled
            try
            {
                // Update the application management table
                SqlParameter workspaceIdParam = new SqlParameter("@workspaceId", workspaceId);
                instanceContext.ExecuteNonQuerySQLStatement("UPDATE [eddsdbo].[" + this.TableName + "] SET [Status] = 0, [LastUpdated] = CURRENT_TIMESTAMP WHERE [CaseArtifactID] = @workspaceId", new SqlParameter[] { workspaceIdParam });
            }
            catch (Exception e)
            {
                _logger.LogError(e, "Audit Log Elastic Search, Pre Uninstall EventHandler application management table update error");

                response.Success = false;
                response.Message = "Pre Uninstall EventHandler application management table update error";
                return(response);
            }

            // Log end of Pre Uninstall EventHandler
            _logger.LogDebug("Audit Log Elastic Search, Pre Uninstall EventHandler successfully finished");

            return(response);
        }
        public async Task <kCura.EventHandler.Response> ExecuteAsync()
        {
            var response = new kCura.EventHandler.Response {
                Success = true, Message = string.Empty
            };

            try
            {
                Logger.LogDebug(Constant.Names.ApplicationName + " - [{@this}] Checking to see if this application can be installed in this version of Relativity.", this);

                var currentRelativityVersion   = Utility.GetRelativityVersion(typeof(kCura.EventHandler.Application));
                var supportedRelativityVersion = new Version(Constant.Relativity.SupportedVersion);

                if (currentRelativityVersion >= supportedRelativityVersion)
                {
                    Logger.LogDebug(Constant.Names.ApplicationName + " - [{@this}] Checking to see if application is installed elsewhere.", this);

                    if (await ApplicationInstalledInAnotherWorkspace(DbContextEdds))
                    {
                        Logger.LogDebug($"{Constant.Names.ApplicationName} - Application cannot be installed as it currently exists in another Workspace.");
                        throw new AdminMigrationUtilityException(Constant.ErrorMessages.ApplicationInstallationFailure);
                    }
                    else
                    {
                        Logger.LogDebug($"{Constant.Names.ApplicationName} - Application does not exist elsewhere, proceeding with installation.");
                    }
                }
                else
                {
                    Logger.LogDebug(Constant.Names.ApplicationName + " - [{@this}] This application cannot be installed in this version of Relativity. Your version of Relativity (" + currentRelativityVersion + ") must be equal to or greater than " + Constant.Relativity.SupportedVersion + ".", this);
                    response.Success = false;
                    response.Message = "Pre-Install failed with error: " + string.Format(Constant.ErrorMessages.UnsupportedRelativityVersion, Constant.Relativity.SupportedVersion);
                }
            }
            catch (AdminMigrationUtilityException aex)
            {
                Logger.LogError(aex, $"{Constant.Names.ApplicationName} - Pre-Install failed. {aex}");
                response.Success = false;
                response.Message = "Pre-Install failed with error: " + aex.Message;
            }

            Logger.LogDebug(Constant.Names.ApplicationName + " - [{@this}] Successfully checked to see if application is installed elsewhere.", this);
            return(response);
        }
Пример #17
0
        public override kCura.EventHandler.Response Execute()
        {
            kCura.EventHandler.Response response = new kCura.EventHandler.Response();
            string sql = null;

            response.Success = true;
            response.Message = "";

            try {
                sql = string.Format(Database.Resources.RemoveFromCasesQueue, this.Application.ArtifactID.ToString(), this.ActiveArtifact.ArtifactID.ToString());
                Helper.GetDBContext(-1).ExecuteNonQuerySQLStatement(sql);
                sql = string.Format(Database.Resources.RemoveFromDocumentQueue, this.Application.ArtifactID.ToString(), this.ActiveArtifact.ArtifactID.ToString());
                Helper.GetDBContext(-1).ExecuteNonQuerySQLStatement(sql);
            } catch (Exception ex) {
                response.Success = false;
                response.Message = ex.Message;
            }

            return(response);
        }
Пример #18
0
        public override kCura.EventHandler.Response Execute()
        {
            kCura.EventHandler.Response response = new kCura.EventHandler.Response();
            response.Success = true;
            response.Message = "";

            try
            {
                Helper.GetDBContext(-1).ExecuteNonQuerySQLStatement(Database.Resources.CreateCasesQueueTable);
                Helper.GetDBContext(-1).ExecuteNonQuerySQLStatement(Database.Resources.CreateIndexOnCasesQueue);
                Helper.GetDBContext(-1).ExecuteNonQuerySQLStatement(Database.Resources.CreateDocumentQueueTable);
                Helper.GetDBContext(-1).ExecuteNonQuerySQLStatement(Database.Resources.CreateIndexOnDocumentQueue);
                Helper.GetDBContext(Helper.GetActiveCaseID()).ExecuteNonQuerySQLStatement(Database.Resources.CreateMissingFilesTable);
            }
            catch (Exception ex)
            {
                response.Success = false;
                response.Message = ex.Message;
            }

            return(response);
        }
Пример #19
0
        public static void ValidateEmailAddresses(String delimitedEmailAddresses, String delimiter, kCura.EventHandler.Response response)
        {
            if (!String.IsNullOrWhiteSpace(delimitedEmailAddresses))
            {
                var invalidEmailAddresses  = new List <String>();
                var individualEmailAddress = delimitedEmailAddresses.Split(delimiter.ToCharArray());
                if (individualEmailAddress.Any())
                {
                    foreach (var emailAddress in individualEmailAddress)
                    {
                        var match = System.Text.RegularExpressions.Regex.Match(emailAddress, Constant.RegExPatterns.EmailAddress);
                        if (!match.Success)
                        {
                            invalidEmailAddresses.Add(emailAddress);
                        }
                    }
                }

                if (invalidEmailAddresses.Any())
                {
                    response.Success = false;
                    response.Message = response.Message ?? String.Empty;
                    response.Message = response.Message + String.Format(Constant.ErrorMessages.InvalidEmailAddresses, String.Join(",", invalidEmailAddresses));
                }
            }
        }
Пример #20
0
        /*
         * This function is called in batches based on the size defined in configuration.
         */
        public override kCura.EventHandler.Response DoBatch()
        {
            // Get logger
            Relativity.API.IAPILog _logger = this.Helper.GetLoggerFactory().GetLogger().ForContext <MassOperationHandler>();

            // Init general response
            kCura.EventHandler.Response response = new kCura.EventHandler.Response()
            {
                Success = true,
                Message = ""
            };

            // Get current Workspace ID
            int workspaceId = this.Helper.GetActiveCaseID();

            _logger.LogDebug("Azure Translator, current Workspace ID: {workspaceId}", workspaceId.ToString());

            // Check if all Instance Settings are in place
            IDictionary <string, string> instanceSettings = this.GetInstanceSettings(ref response, new string[] { "SourceField", "DestinationField", "LogField", "Cost1MCharacters", "AzureServiceRegion", "AzureSubscriptionKey", "AzureTranslatorEndpoint", "TranslateFrom", "TranslateTo" });

            // Check if there was not error
            if (!response.Success)
            {
                return(response);
            }

            // Update general status
            this.ChangeStatus("Translating documents");

            // For each document create translation task
            List <Task <int> > translationTasks = new List <Task <int> >();
            int runningTasks    = 0;
            int concurrentTasks = 16;

            for (int i = 0; i < this.BatchIDs.Count; i++)
            {
                // Translate documents in Azure and update Relativity using Object Manager API
                translationTasks.Add(TranslateDocument(workspaceId, this.BatchIDs[i], instanceSettings["SourceField"], instanceSettings["DestinationField"], instanceSettings["LogField"], instanceSettings["AzureServiceRegion"], instanceSettings["AzureSubscriptionKey"], instanceSettings["AzureTranslatorEndpoint"], instanceSettings["TranslateFrom"], instanceSettings["TranslateTo"]));

                // Update progreass bar
                this.IncrementCount(1);

                // Allow only certain number of tasks to run concurrently
                do
                {
                    runningTasks = 0;
                    foreach (Task <int> translationTask in translationTasks)
                    {
                        if (!translationTask.IsCompleted)
                        {
                            runningTasks++;
                        }
                    }
                    if (runningTasks >= concurrentTasks)
                    {
                        Thread.Sleep(100);
                    }
                } while (runningTasks >= concurrentTasks);
            }

            // Update general status
            this.ChangeStatus("Waiting to finish the document translation");

            // Wait for all translations to finish
            _logger.LogDebug("Azure Translator, waiting for all documents finish translating ({n} document(s))", this.BatchIDs.Count.ToString());
            Task.WaitAll(translationTasks.ToArray());

            // Update general status
            this.ChangeStatus("Checking the results of the document translation");

            // Check results
            List <string> translationErrors = new List <string>();

            for (int i = 0; i < translationTasks.Count; i++)
            {
                // If translation was not done add to the error List
                _logger.LogDebug("Azure Translator, translation task result: {result} (task: {task})", translationTasks[i].Result.ToString(), translationTasks[i].Id.ToString());
                if (translationTasks[i].Result != 0)
                {
                    translationErrors.Add(translationTasks[i].Result.ToString());
                }
            }

            // If there are any errors adjust response
            if (translationErrors.Count > 0)
            {
                _logger.LogError("Azure Translator, not all documents have been translated: ({documents})", string.Join(", ", translationErrors));

                response.Success = false;
                response.Message = "Not all documents have been translated";
            }

            return(response);
        }
Пример #21
0
        public override kCura.EventHandler.Response Execute()
        {
            // Update Security Protocol
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

            // Get logger
            Relativity.API.IAPILog _logger = this.Helper.GetLoggerFactory().GetLogger().ForContext <PostInstallEventHandler>();

            // Init general response
            kCura.EventHandler.Response response = new kCura.EventHandler.Response()
            {
                Success = true,
                Message = ""
            };

            // Get current Workspace ID
            int workspaceId = this.Helper.GetActiveCaseID();

            _logger.LogDebug("Audit Log Elastic Search, current Workspace ID: {workspaceId}", workspaceId.ToString());

            // Get database context of the instance
            IDBContext instanceContext = Helper.GetDBContext(-1);

            // Existing application management table name
            string tableExisting = "";

            try
            {
                // Get application management table
                tableExisting = instanceContext.ExecuteSqlStatementAsScalar("SELECT ISNULL((SELECT '" + this.TableName + "' FROM [INFORMATION_SCHEMA].[TABLES] WHERE [TABLE_SCHEMA] = 'eddsdbo' AND [TABLE_NAME] = '" + this.TableName + "'), '')").ToString();
            }
            catch (Exception e)
            {
                _logger.LogError(e, "Audit Log Elastic Search, Post Install EventHandler application management table error");

                response.Success = false;
                response.Message = "Post Install EventHandler management application table error";
                return(response);
            }

            // If application management table not present, create it
            if (tableExisting != this.TableName)
            {
                instanceContext.BeginTransaction();
                try
                {
                    // Create application management table
                    instanceContext.ExecuteNonQuerySQLStatement("CREATE TABLE [eddsdbo].[" + this.TableName + "] ([CaseArtifactID] [int] NOT NULL, [AuditRecordID] [bigint] NOT NULL, [Status] [bit] NOT NULL, [LastUpdated] [datetime] NOT NULL, [AgentArtifactID] [int] NULL)");
                    instanceContext.CommitTransaction();
                }
                catch (Exception e)
                {
                    instanceContext.RollbackTransaction();

                    _logger.LogError(e, "Audit Log Elastic Search, Post Install EventHandler application management table creation error");

                    response.Success = false;
                    response.Message = "Post Install EventHandler application management table creation error";
                    return(response);
                }
            }

            // Add line to the application management table for current workspace
            try
            {
                // Insert to the application management table
                SqlParameter workspaceIdParam = new SqlParameter("@workspaceId", workspaceId);
                instanceContext.ExecuteNonQuerySQLStatement("INSERT INTO [eddsdbo].[" + this.TableName + "] ([CaseArtifactID], [AuditRecordID], [Status], [LastUpdated]) VALUES (@workspaceId, 0, 1, CURRENT_TIMESTAMP)", new SqlParameter[] { workspaceIdParam });
            }
            catch (Exception e)
            {
                _logger.LogError(e, "Audit Log Elastic Search, Post Install EventHandler application management table insert error");

                response.Success = false;
                response.Message = "Post Install EventHandler application management table insert error";
                return(response);
            }

            // Log end of Post Install EventHandler
            _logger.LogDebug("Audit Log Elastic Search, Post Install EventHandler successfully finished");

            return(response);
        }
Пример #22
0
        public async Task <kCura.EventHandler.Response> ExecuteAsync()
        {
            IQuery                  query                  = new Query();
            IArtifactQueries        artifactQueries        = new ArtifactQueries();
            IPostInstallSetupHelper postInstallSetupHelper = new PostInstallSetupHelper(query, artifactQueries);

            //Create Tables
            var returnResponse = await Task.Run(() =>
            {
                var response = new kCura.EventHandler.Response
                {
                    Success = true,
                    Message = string.Empty
                };

                //Create Export Manager Queue table if it doesn't already exist
                var exportManagerTableTask = query.CreateExportManagerQueueTableAsync(Helper.GetDBContext(-1));

                //Create Export Worker Queue table if it doesn't already exist
                var exportWorkerTableTask = query.CreateExportWorkerQueueTableAsync(Helper.GetDBContext(-1));

                var reproduceWorkerTableTask = query.CreateReproduceWorkerQueueTableAsync(Helper.GetDBContext(-1));

                //Create Export Error Log table if it doesn't already exist
                var exportErrorLogTableTask = query.CreateExportErrorLogTableAsync(Helper.GetDBContext(-1));

                //Create Import Manager Queue table if it doesn't already exist
                var importManagerTableTask = query.CreateImportManagerQueueTableAsync(Helper.GetDBContext(-1));

                //Create Import Worker Queue table if it doesn't already exist
                var importWorkerTableTask = query.CreateImportWorkerQueueTableAsync(Helper.GetDBContext(-1));

                //Create Import Error Log table if it doesn't already exist
                var importErrorLogTableTask = query.CreateImportErrorLogTableAsync(Helper.GetDBContext(-1));

                //Create Export Results table if it doesn't already exist
                var importExportResultsTableTask = query.CreateExportResultsTableAsync(Helper.GetDBContext(-1));

                //Create Reproduce Manager Queue table if it doesn't already exist
                var reproduceManagerTableTask = query.CreateReproduceManagerQueueTableAsync(Helper.GetDBContext(-1));

                //Create Reproduce Error Log table if it doesn't already exist
                var reproduceErrorLogTableTask = query.CreateReproduceErrorLogTableAsync(Helper.GetDBContext(-1));

                try
                {
                    //Waits for all tasks, otherwise exceptions would be lost
                    Task.WaitAll(exportManagerTableTask, exportWorkerTableTask, exportErrorLogTableTask, importManagerTableTask, importWorkerTableTask, importErrorLogTableTask, importExportResultsTableTask, reproduceManagerTableTask, reproduceErrorLogTableTask, reproduceWorkerTableTask);
                }
                catch (AggregateException aex)
                {
                    var ex           = aex.Flatten();
                    var message      = ex.Message + " : " + (ex.InnerException?.Message ?? "None");
                    response.Success = false;
                    response.Message = "Post-Install queue and error log table creation failed with message: " + message;
                }

                ////If table(s) creation fails return error response
                if (!response.Success)
                {
                    return(response);
                }
                {
                    //Create records for MarkupUtilityType Rdo
                    var workspaceArtifactId = Helper.GetActiveCaseID();
                    var servicesManager     = Helper.GetServicesManager();
                    var workspaceDbContext  = Helper.GetDBContext(workspaceArtifactId);

                    var createRecordsForMarkupUtilityTypeRdoTask = Task.Run(async() =>
                    {
                        await postInstallSetupHelper.CreateRecordsForMarkupUtilityTypeRdoAsync(servicesManager, ExecutionIdentity.CurrentUser, workspaceArtifactId, workspaceDbContext);
                    });

                    try
                    {
                        createRecordsForMarkupUtilityTypeRdoTask.Wait();
                    }
                    catch (Exception ex)
                    {
                        var message      = ex.Message + " : " + (ex.InnerException?.Message ?? "None");
                        response.Success = false;
                        response.Message = "Post-Install queue and error log table creation failed with message: " + message;
                    }
                }

                return(response);
            });

            return(returnResponse);
        }